text
stringlengths
8
4.13M
#![feature(core_intrinsics)] fn get_name<T>(_t: &T) -> String { unsafe { (*std::intrinsics::type_name::<T>()).to_string() } } fn main() { println!("{}", get_name(&get_name::<i32>)); }
// Copyright 2022 Datafuse Labs. // // 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_ast::ast::*; use common_exception::Result; use itertools::Itertools; use crate::binder::Binder; use crate::normalize_identifier; use crate::plans::AlterShareTenantsPlan; use crate::plans::CreateSharePlan; use crate::plans::DescSharePlan; use crate::plans::DropSharePlan; use crate::plans::GrantShareObjectPlan; use crate::plans::Plan; use crate::plans::RevokeShareObjectPlan; use crate::plans::ShowGrantTenantsOfSharePlan; use crate::plans::ShowObjectGrantPrivilegesPlan; use crate::plans::ShowSharesPlan; impl Binder { pub(in crate::planner::binder) async fn bind_create_share( &mut self, stmt: &CreateShareStmt, ) -> Result<Plan> { let CreateShareStmt { if_not_exists, share, comment, } = stmt; let share = normalize_identifier(share, &self.name_resolution_ctx).name; let plan = CreateSharePlan { if_not_exists: *if_not_exists, tenant: self.ctx.get_tenant(), share, comment: comment.as_ref().cloned(), }; Ok(Plan::CreateShare(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_drop_share( &mut self, stmt: &DropShareStmt, ) -> Result<Plan> { let DropShareStmt { if_exists, share } = stmt; let share = normalize_identifier(share, &self.name_resolution_ctx).name; let plan = DropSharePlan { if_exists: *if_exists, tenant: self.ctx.get_tenant(), share, }; Ok(Plan::DropShare(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_grant_share_object( &mut self, stmt: &GrantShareObjectStmt, ) -> Result<Plan> { let GrantShareObjectStmt { share, object, privilege, } = stmt; let share = normalize_identifier(share, &self.name_resolution_ctx).name; let plan = GrantShareObjectPlan { share, object: object.clone(), privilege: *privilege, }; Ok(Plan::GrantShareObject(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_revoke_share_object( &mut self, stmt: &RevokeShareObjectStmt, ) -> Result<Plan> { let RevokeShareObjectStmt { share, object, privilege, } = stmt; let share = normalize_identifier(share, &self.name_resolution_ctx).name; let plan = RevokeShareObjectPlan { share, object: object.clone(), privilege: *privilege, }; Ok(Plan::RevokeShareObject(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_alter_share_accounts( &mut self, stmt: &AlterShareTenantsStmt, ) -> Result<Plan> { let AlterShareTenantsStmt { share, if_exists, tenants, is_add, } = stmt; let share = normalize_identifier(share, &self.name_resolution_ctx).name; let plan = AlterShareTenantsPlan { share, if_exists: *if_exists, is_add: *is_add, accounts: tenants.iter().map(|v| v.to_string()).collect_vec(), }; Ok(Plan::AlterShareTenants(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_desc_share( &mut self, stmt: &DescShareStmt, ) -> Result<Plan> { let DescShareStmt { share } = stmt; let share = normalize_identifier(share, &self.name_resolution_ctx).name; let plan = DescSharePlan { share }; Ok(Plan::DescShare(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_show_shares( &mut self, _stmt: &ShowSharesStmt, ) -> Result<Plan> { Ok(Plan::ShowShares(Box::new(ShowSharesPlan {}))) } pub(in crate::planner::binder) async fn bind_show_object_grant_privileges( &mut self, stmt: &ShowObjectGrantPrivilegesStmt, ) -> Result<Plan> { let ShowObjectGrantPrivilegesStmt { object } = stmt; let plan = ShowObjectGrantPrivilegesPlan { object: object.clone(), }; Ok(Plan::ShowObjectGrantPrivileges(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_show_grants_of_share( &mut self, stmt: &ShowGrantsOfShareStmt, ) -> Result<Plan> { let ShowGrantsOfShareStmt { share_name } = stmt; let plan = ShowGrantTenantsOfSharePlan { share_name: share_name.clone(), }; Ok(Plan::ShowGrantTenantsOfShare(Box::new(plan))) } }
#[doc = "Reader of register EM23PERNORETAINSTATUS"] pub type R = crate::R<u32, super::EM23PERNORETAINSTATUS>; #[doc = "Reader of field `ACMP0LOCKED`"] pub type ACMP0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `ACMP1LOCKED`"] pub type ACMP1LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `PCNT0LOCKED`"] pub type PCNT0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `PCNT1LOCKED`"] pub type PCNT1LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `PCNT2LOCKED`"] pub type PCNT2LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `I2C0LOCKED`"] pub type I2C0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `I2C1LOCKED`"] pub type I2C1LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `DAC0LOCKED`"] pub type DAC0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `IDAC0LOCKED`"] pub type IDAC0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `ADC0LOCKED`"] pub type ADC0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `LETIMER0LOCKED`"] pub type LETIMER0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `WDOG0LOCKED`"] pub type WDOG0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `WDOG1LOCKED`"] pub type WDOG1LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `LESENSE0LOCKED`"] pub type LESENSE0LOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `CSENLOCKED`"] pub type CSENLOCKED_R = crate::R<bool, bool>; #[doc = "Reader of field `LEUART0LOCKED`"] pub type LEUART0LOCKED_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Indicates If ACMP0 Powered Down During EM23"] #[inline(always)] pub fn acmp0locked(&self) -> ACMP0LOCKED_R { ACMP0LOCKED_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Indicates If ACMP1 Powered Down During EM23"] #[inline(always)] pub fn acmp1locked(&self) -> ACMP1LOCKED_R { ACMP1LOCKED_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Indicates If PCNT0 Powered Down During EM23"] #[inline(always)] pub fn pcnt0locked(&self) -> PCNT0LOCKED_R { PCNT0LOCKED_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Indicates If PCNT1 Powered Down During EM23"] #[inline(always)] pub fn pcnt1locked(&self) -> PCNT1LOCKED_R { PCNT1LOCKED_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Indicates If PCNT2 Powered Down During EM23"] #[inline(always)] pub fn pcnt2locked(&self) -> PCNT2LOCKED_R { PCNT2LOCKED_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Indicates If I2C0 Powered Down During EM23"] #[inline(always)] pub fn i2c0locked(&self) -> I2C0LOCKED_R { I2C0LOCKED_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Indicates If I2C1 Powered Down During EM23"] #[inline(always)] pub fn i2c1locked(&self) -> I2C1LOCKED_R { I2C1LOCKED_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Indicates If DAC0 Powered Down During EM23"] #[inline(always)] pub fn dac0locked(&self) -> DAC0LOCKED_R { DAC0LOCKED_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Indicates If IDAC0 Powered Down During EM23"] #[inline(always)] pub fn idac0locked(&self) -> IDAC0LOCKED_R { IDAC0LOCKED_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Indicates If ADC0 Powered Down During EM23"] #[inline(always)] pub fn adc0locked(&self) -> ADC0LOCKED_R { ADC0LOCKED_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Indicates If LETIMER0 Powered Down During EM23"] #[inline(always)] pub fn letimer0locked(&self) -> LETIMER0LOCKED_R { LETIMER0LOCKED_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - Indicates If WDOG0 Powered Down During EM23"] #[inline(always)] pub fn wdog0locked(&self) -> WDOG0LOCKED_R { WDOG0LOCKED_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - Indicates If WDOG1 Powered Down During EM23"] #[inline(always)] pub fn wdog1locked(&self) -> WDOG1LOCKED_R { WDOG1LOCKED_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - Indicates If LESENSE0 Powered Down During EM23"] #[inline(always)] pub fn lesense0locked(&self) -> LESENSE0LOCKED_R { LESENSE0LOCKED_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - Indicates If CSEN Powered Down During EM23"] #[inline(always)] pub fn csenlocked(&self) -> CSENLOCKED_R { CSENLOCKED_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - Indicates If LEUART0 Powered Down During EM23"] #[inline(always)] pub fn leuart0locked(&self) -> LEUART0LOCKED_R { LEUART0LOCKED_R::new(((self.bits >> 15) & 0x01) != 0) } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use spin::RwLock; use core::ops::Deref; use super::waitlist::*; use super::entry::*; use super::*; #[derive(Default, Clone)] pub struct Queue(Arc<RwLock<WaitList>>); impl Deref for Queue { type Target = Arc<RwLock<WaitList>>; fn deref(&self) -> &Arc<RwLock<WaitList>> { &self.0 } } impl Waitable for Queue { fn Readiness(&self, _task: &Task,_mask: EventMask) -> EventMask { return 0; } fn EventRegister(&self, _task: &Task,e: &WaitEntry, mask: EventMask) { let mut q = self.write(); e.lock().mask = mask; q.PushBack(e) } fn EventUnregister(&self, _task: &Task,e: &WaitEntry) { let mut q = self.write(); q.Remove(e) } } impl Queue { //notify won't remove the trigged waitentry pub fn Notify(&self, mask: EventMask) { let q = self.read(); let mut entry = q.Front(); while entry.is_some() { let tmp = entry.clone().unwrap(); tmp.Notify(mask); entry = tmp.lock().next.clone(); } } pub fn Clear(&self) { let q = self.read(); let mut entry = q.Front(); while entry.is_some() { let tmp = entry.clone().unwrap(); tmp.Clear(); entry = tmp.lock().next.clone(); } } pub fn Events(&self) -> EventMask { let mut ret = 0; let q = self.read(); let mut entry = q.Front(); while entry.is_some() { let tmp = entry.clone().unwrap(); ret |= tmp.Mask(); entry = tmp.lock().next.clone(); } return ret; } }
// still prototyping so having one state driving everything for RenderToWindow extern crate amethyst; use prelude::*; struct GameState { } impl SimpleState for GameState { }
use tui::style::{Color, Style}; use tui::widgets::Text; #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] pub enum Item { KeyCard, Crowbar, } #[derive(Debug)] pub struct Player { pub health: i32, pub attack_strength: i32, pub items: Vec<Item>, } impl Player { pub fn format_player_info(&self) -> Vec<Text> { vec![ Text::raw("Health: "), Text::styled( format!("{}", self.health), match self.health { 0...30 => Style::default().fg(Color::Red), 30...70 => Style::default().fg(Color::Yellow), 70...100 => Style::default().fg(Color::Green), _ => Style::default(), }, ), ] } pub fn has_item(&self, item: Item) -> bool { for owned_item in &self.items { if item == *owned_item { return true; } } false } }
mod messages; mod ws; mod coordinator; mod worker_client; mod uuid; use actix::*; use actix_web::{ web, App, // HttpResponse, HttpServer, // Responder, Result }; use actix_files::{Files,NamedFile}; pub use coordinator::Coordinator; pub use worker_client::{ WorkerClient }; use ws::websocket_route; fn main() { let sys = System::new("ruddy-controller"); let coordinator = Coordinator::default().start(); println!("Starting controller server on port 3100."); HttpServer::new(move || { App::new() .data(coordinator.clone()) .route("/", web::get().to(index_html)) .service(Files::new("/static", "./public/static").show_files_listing()) // TODO: remove the directory listing .route("/ws/", web::get().to(websocket_route)) }) .bind("127.0.0.1:3100") .unwrap() .start(); sys.run().expect("Could not start actix System"); } fn index_html() -> Result<NamedFile> { Ok(NamedFile::open("public/controller.html").unwrap()) }
//! Consensus module. //! //! Low level consensus module for communicating with the consensus layer. use std::str::FromStr; use thiserror::Error; use oasis_core_runtime::{ common::versioned::Versioned, consensus::{ roothash::{Message, StakingMessage}, staking, staking::Account as ConsensusAccount, state::{staking::ImmutableState as StakingImmutableState, StateError}, }, }; use crate::{ context::{Context, TxContext}, module, module::Module as _, modules, modules::core::{Module as Core, API as _}, types::{ address::{Address, SignatureAddressSpec}, message::MessageEventHookInvocation, token, transaction::{AddressSpec, TransactionWeight}, }, }; #[cfg(test)] mod test; /// Unique module name. const MODULE_NAME: &str = "consensus"; /// Parameters for the consensus module. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct Parameters { pub consensus_denomination: token::Denomination, } impl Default for Parameters { fn default() -> Self { Self { consensus_denomination: token::Denomination::from_str("TEST").unwrap(), } } } impl module::Parameters for Parameters { type Error = (); } /// Events emitted by the consensus module (none so far). #[derive(Debug, cbor::Encode, oasis_runtime_sdk_macros::Event)] #[cbor(untagged)] pub enum Event {} /// Genesis state for the consensus module. #[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)] pub struct Genesis { pub parameters: Parameters, } #[derive(Error, Debug, oasis_runtime_sdk_macros::Error)] pub enum Error { #[error("invalid argument")] #[sdk_error(code = 1)] InvalidArgument, #[error("invalid denomination")] #[sdk_error(code = 2)] InvalidDenomination, #[error("internal state: {0}")] #[sdk_error(code = 3)] InternalStateError(#[from] StateError), #[error("core: {0}")] #[sdk_error(transparent)] Core(#[from] modules::core::Error), #[error("consensus incompatible signer")] #[sdk_error(code = 4)] ConsensusIncompatibleSigner, } /// Interface that can be called from other modules. pub trait API { /// Transfer an amount from the runtime account. fn transfer<C: TxContext>( ctx: &mut C, to: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error>; /// Withdraw an amount into the runtime account. fn withdraw<C: TxContext>( ctx: &mut C, from: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error>; /// Escrow an amount of the runtime account funds. fn escrow<C: TxContext>( ctx: &mut C, to: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error>; /// Reclaim an amount of runtime staked shares. fn reclaim_escrow<C: TxContext>( ctx: &mut C, from: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error>; /// Returns consensus token denomination. fn consensus_denomination<C: Context>(ctx: &mut C) -> Result<token::Denomination, Error>; /// Ensures transaction signer is consensus compatible. fn ensure_compatible_tx_signer<C: TxContext>(ctx: &C) -> Result<(), Error>; /// Query consensus account info. fn account<C: Context>(ctx: &C, addr: Address) -> Result<ConsensusAccount, Error>; } pub struct Module; impl Module { fn ensure_consensus_denomination<C: Context>( ctx: &mut C, denomination: &token::Denomination, ) -> Result<(), Error> { if denomination != &Self::consensus_denomination(ctx)? { return Err(Error::InvalidDenomination); } Ok(()) } } impl API for Module { fn transfer<C: TxContext>( ctx: &mut C, to: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error> { Self::ensure_consensus_denomination(ctx, amount.denomination())?; Core::add_weight(ctx, TransactionWeight::ConsensusMessages, 1)?; if ctx.is_check_only() { return Ok(()); } ctx.emit_message( Message::Staking(Versioned::new( 0, StakingMessage::Transfer(staking::Transfer { to: to.into(), amount: amount.amount().into(), }), )), hook, )?; Ok(()) } fn withdraw<C: TxContext>( ctx: &mut C, from: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error> { Self::ensure_consensus_denomination(ctx, amount.denomination())?; Core::add_weight(ctx, TransactionWeight::ConsensusMessages, 1)?; if ctx.is_check_only() { return Ok(()); } ctx.emit_message( Message::Staking(Versioned::new( 0, StakingMessage::Withdraw(staking::Withdraw { from: from.into(), amount: amount.amount().into(), }), )), hook, )?; Ok(()) } fn escrow<C: TxContext>( ctx: &mut C, to: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error> { Self::ensure_consensus_denomination(ctx, amount.denomination())?; Core::add_weight(ctx, TransactionWeight::ConsensusMessages, 1)?; if ctx.is_check_only() { return Ok(()); } ctx.emit_message( Message::Staking(Versioned::new( 0, StakingMessage::AddEscrow(staking::Escrow { account: to.into(), amount: amount.amount().into(), }), )), hook, )?; Ok(()) } fn reclaim_escrow<C: TxContext>( ctx: &mut C, from: Address, amount: &token::BaseUnits, hook: MessageEventHookInvocation, ) -> Result<(), Error> { Self::ensure_consensus_denomination(ctx, amount.denomination())?; Core::add_weight(ctx, TransactionWeight::ConsensusMessages, 1)?; if ctx.is_check_only() { return Ok(()); } ctx.emit_message( Message::Staking(Versioned::new( 0, StakingMessage::ReclaimEscrow(staking::ReclaimEscrow { account: from.into(), shares: amount.amount().into(), }), )), hook, )?; Ok(()) } fn consensus_denomination<C: Context>(ctx: &mut C) -> Result<token::Denomination, Error> { let params = Self::params(ctx.runtime_state()); Ok(params.consensus_denomination) } fn ensure_compatible_tx_signer<C: TxContext>(ctx: &C) -> Result<(), Error> { match ctx.tx_auth_info().signer_info[0].address_spec { AddressSpec::Signature(SignatureAddressSpec::Ed25519(_)) => Ok(()), _ => Err(Error::ConsensusIncompatibleSigner), } } fn account<C: Context>(ctx: &C, addr: Address) -> Result<ConsensusAccount, Error> { let state = StakingImmutableState::new(ctx.consensus_state()); state .account(ctx.io_ctx(), addr.into()) .map_err(Error::InternalStateError) } } impl module::Module for Module { const NAME: &'static str = MODULE_NAME; const VERSION: u32 = 1; type Error = Error; type Event = Event; type Parameters = Parameters; } impl module::MethodHandler for Module {} impl module::MigrationHandler for Module { type Genesis = Genesis; fn init_or_migrate<C: Context>( ctx: &mut C, meta: &mut modules::core::types::Metadata, genesis: Self::Genesis, ) -> bool { let version = meta.versions.get(Self::NAME).copied().unwrap_or_default(); if version == 0 { // TODO: enable loading consensus denomination from consensus state after: // https://github.com/oasisprotocol/oasis-core/issues/3868 // Initialize state from genesis. Self::set_params(ctx.runtime_state(), genesis.parameters); meta.versions.insert(Self::NAME.to_owned(), Self::VERSION); return true; } // Migrations are not supported. false } } impl module::AuthHandler for Module {} impl module::BlockHandler for Module {} impl module::InvariantHandler for Module {}
use std::io::Cursor; use gfx::Factory; use gfx_device_gl::CommandBuffer; use gfx_device_gl::Resources; pub type RgbSurfaceFormat = gfx::format::R8_G8_B8_A8; pub type YuvSurfaceFormat = gfx::format::R8; pub type ColorFormat = (RgbSurfaceFormat, gfx::format::Unorm); /// /// Can be used to replace parts of or a whole texture. /// /// # Example /// /// To replace 64x64 pixels in the lower left of the texture with 0xff00ff, do: /// /// ```rust,ignore /// let arr = vec![0xffff00ff; 64*64]; /// let data = gfx::memory::cast_slice(&arr); /// let size = [64, 64]; /// let offset = [0, 0]; /// update_texture(encoder, &self.texture, size, offset, data); /// ``` /// pub fn update_texture( encoder: &mut gfx::Encoder<Resources, CommandBuffer>, texture: &gfx::handle::Texture<Resources, RgbSurfaceFormat>, size: [u16; 2], offset: [u16; 2], raw_data: &[u8], ) { let img_info = gfx::texture::ImageInfoCommon { xoffset: offset[0], yoffset: offset[1], zoffset: 0, width: size[0], height: size[1], depth: 0, format: (), mipmap: 0, }; let data = gfx::memory::cast_slice(&raw_data); let _msg = encoder.update_texture::<RgbSurfaceFormat, ColorFormat>(texture, None, img_info, data); } pub fn load_texture( factory: &mut gfx_device_gl::Factory, data: Cursor<Vec<u8>>, ) -> Result< ( gfx::handle::Texture<Resources, RgbSurfaceFormat>, gfx::handle::ShaderResourceView<Resources, [f32; 4]>, ), String, > { let img = image::load(data, image::ImageFormat::Png) .unwrap() .flipv() .to_rgba(); let (width, height) = img.dimensions(); let data = img.into_raw(); load_texture_from_bytes(factory, data.into_boxed_slice(), width, height) } /// /// Load bytes as texture into GPU /// /// # Arguments /// /// - `factory` - factory to generate commands for opengl command buffer /// - `data` - raw image data /// - `width` - width of the requested texture /// - `height` - height of the requested texture /// /// # Return /// /// Created Texture and shader RessourceView /// pub fn load_texture_from_bytes( factory: &mut gfx_device_gl::Factory, data: Box<[u8]>, width: u32, height: u32, ) -> Result< ( gfx::handle::Texture<Resources, RgbSurfaceFormat>, gfx::handle::ShaderResourceView<Resources, [f32; 4]>, ), String, > { let kind = texture::Kind::D2( width as texture::Size, height as texture::Size, texture::AaMode::Single, ); // inspired by https://github.com/PistonDevelopers/gfx_texture/blob/master/src/lib.rs#L157-L178 use gfx::memory::Typed; use gfx::memory::Usage; use gfx::{format, texture}; let surface = gfx::format::SurfaceType::R8_G8_B8_A8; let desc = texture::Info { kind, levels: 1 as texture::Level, format: surface, bind: gfx::memory::Bind::all(), usage: Usage::Dynamic, }; let cty = gfx::format::ChannelType::Unorm; let raw = factory .create_texture_raw( desc, Some(cty), Some((&[&data], gfx::texture::Mipmap::Allocated)), ) .unwrap(); let levels = (0, raw.get_info().levels - 1); let tex = Typed::new(raw); let view = factory .view_texture_as_shader_resource::<ColorFormat>(&tex, levels, format::Swizzle::new()) .unwrap(); Ok((tex, view)) } pub fn update_single_channel_texture( encoder: &mut gfx::Encoder<Resources, CommandBuffer>, texture: &gfx::handle::Texture<Resources, gfx::format::R8>, size: [u16; 2], offset: [u16; 2], raw_data: &[u8], ) { let img_info = gfx::texture::ImageInfoCommon { xoffset: offset[0], yoffset: offset[1], zoffset: 0, width: size[0], height: size[1], depth: 0, format: (), mipmap: 0, }; let data = gfx::memory::cast_slice(&raw_data); let _msg = encoder.update_texture::<gfx::format::R8, (gfx::format::R8, gfx::format::Unorm)>( texture, None, img_info, data, ); } pub fn load_single_channel_texture_from_bytes( factory: &mut gfx_device_gl::Factory, data: Box<[u8]>, width: u32, height: u32, ) -> Result< ( gfx::handle::Texture<Resources, gfx::format::R8>, gfx::handle::ShaderResourceView<Resources, f32>, ), String, > { let kind = texture::Kind::D2( width as texture::Size, height as texture::Size, texture::AaMode::Single, ); // inspired by https://github.com/PistonDevelopers/gfx_texture/blob/master/src/lib.rs#L157-L178 use gfx::memory::Typed; use gfx::memory::Usage; use gfx::{format, texture}; let surface = gfx::format::SurfaceType::R8; let desc = texture::Info { kind, levels: 1 as texture::Level, format: surface, bind: gfx::memory::Bind::all(), usage: Usage::Dynamic, }; let cty = gfx::format::ChannelType::Unorm; let raw = factory .create_texture_raw( desc, Some(cty), Some((&[&data], gfx::texture::Mipmap::Allocated)), ) .unwrap(); let levels = (0, raw.get_info().levels - 1); let tex = Typed::new(raw); let view = factory .view_texture_as_shader_resource::<(gfx::format::R8, gfx::format::Unorm)>( &tex, levels, format::Swizzle::new(), ) .unwrap(); Ok((tex, view)) } pub fn load_highres_normalmap( factory: &mut gfx_device_gl::Factory, data: Cursor<Vec<u8>>, ) -> Result< ( gfx::handle::Texture<Resources, gfx::format::R32_G32_B32_A32>, gfx::handle::ShaderResourceView<Resources, [f32; 4]>, ), String, > { let img = image::load(data, image::ImageFormat::Png) .unwrap() .flipv() .to_rgba(); let (width, height) = img.dimensions(); let data_raw = img.into_raw(); let mut data_float = Vec::new(); for i in 0..(data_raw.len() / 4) { let n = ((data_raw[i * 4 + 3] as u32) << 24) | ((data_raw[i * 4] as u32) << 16) | ((data_raw[i * 4 + 1] as u32) << 8) | (data_raw[i * 4 + 2] as u32); data_float.push((n as f32) / (<u32>::max_value() as f32)); } let data = unsafe { std::slice::from_raw_parts(data_float.as_mut_ptr() as *const u8, data_float.len() * 4) }; let kind = texture::Kind::D2( (width / 3) as texture::Size, height as texture::Size, texture::AaMode::Single, ); // inspired by https://github.com/PistonDevelopers/gfx_texture/blob/master/src/lib.rs#L157-L178 use gfx::memory::Typed; use gfx::memory::Usage; use gfx::{format, texture}; let surface = gfx::format::SurfaceType::R32_G32_B32; let desc = texture::Info { kind, levels: 1 as texture::Level, format: surface, bind: gfx::memory::Bind::all(), usage: Usage::Dynamic, }; let cty = gfx::format::ChannelType::Float; let raw = factory .create_texture_raw( desc, Some(cty), Some((&[data], gfx::texture::Mipmap::Allocated)), ) .unwrap(); let levels = (0, raw.get_info().levels - 1); let tex = Typed::new(raw); let view = factory .view_texture_as_shader_resource::<(gfx::format::R32_G32_B32_A32, gfx::format::Float)>( &tex, levels, format::Swizzle::new(), ) .unwrap(); Ok((tex, view)) }
use std::fs; fn read_input(f: &str) -> Vec<usize> { let input = fs::read_to_string(f).expect("can't read input file"); input.split(",").map(|x| x.parse().unwrap()).collect() } fn run(input: &[usize]) -> Vec<usize> { let mut mem: Vec<usize> = input.into(); let mut pointer = 0; while pointer < mem.len() { let op = mem[pointer]; match op { 1 | 2 => { let (x, y, z) = (mem[pointer + 1], mem[pointer + 2], mem[pointer + 3]); let (xv, yv) = (mem[x], mem[y]); if op == 1 { mem[z] = xv + yv } else if op == 2{ mem[z] = xv * yv } } 99 | _ => return mem } pointer += 4 } mem } fn solve(input: &[usize]) -> usize { let mut input: Vec<usize> = input.into(); input[1] = 12; input[2] = 2; run(&input)[0] } fn solve2(input: &[usize]) -> usize { let mut input: Vec<usize> = input.into(); for x in 0..100 { for y in 0..100 { input[1] = x; input[2] = y; if run(&input)[0] == 19690720 { return x * 100 + y } } } return 0 } fn main () { let input = read_input("input.txt"); println!("{:?}", solve(&input)); println!("{:?}", solve2(&input)); }
pub mod delete; pub mod get; pub mod leave; pub mod peers; pub mod search; pub mod serve; pub mod set;
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let a: Vec<char> = rd.get_chars(); let b: Vec<char> = rd.get_chars(); let n = a.len(); let diffs: Vec<usize> = (0..n).filter(|&i| a[i] != b[i]).collect(); if diffs.len() > 6 { println!("NO"); return; } let mut keep = Vec::new(); for c in b'a'..=b'z' { let c = c as char; if let Some(left) = a.iter().position(|&x| x == c) { let right = a.iter().rposition(|&x| x == c).unwrap(); if left != right { keep.push(left); keep.push(right); break; } } } keep.extend(diffs); keep.sort(); keep.dedup(); let a: Vec<char> = keep.iter().map(|&i| a[i]).collect(); let b: Vec<char> = keep.iter().map(|&i| b[i]).collect(); let n = a.len(); for i in 0..n { for j in 0..n { if i == j { continue; } for p in 0..n { for q in 0..n { if p == q { continue; } for x in 0..n { for y in 0..n { if x == y { continue; } let mut a = a.clone(); a.swap(i, j); a.swap(p, q); a.swap(x, y); if a == b { println!("YES"); return; } } } } } } } println!("NO"); } pub struct ProconReader<R> { r: R, l: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, l: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { self.skip_blanks(); assert!(self.i < self.l.len()); // remain some character assert_ne!(&self.l[self.i..=self.i], " "); let rest = &self.l[self.i..]; let len = rest.find(' ').unwrap_or_else(|| rest.len()); let val = rest[..len] .parse() .unwrap_or_else(|_| panic!("parse error `{}`", rest)); self.i += len; val } fn skip_blanks(&mut self) { loop { match self.l[self.i..].find(|ch| ch != ' ') { Some(j) => { self.i += j; break; } None => { self.l.clear(); self.i = 0; let num_bytes = self .r .read_line(&mut self.l) .unwrap_or_else(|_| panic!("invalid UTF-8")); assert!(num_bytes > 0, "reached EOF :("); self.l = self .l .trim_end_matches('\n') .trim_end_matches('\r') .to_string(); } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { (0..n).map(|_| self.get()).collect() } pub fn get_chars(&mut self) -> Vec<char> { self.get::<String>().chars().collect() } }
#[macro_use] extern crate serde_derive; extern crate mio; extern crate serde; extern crate serde_bencode; extern crate serde_bytes; extern crate sha1; pub mod metainfo; pub mod peermsg; use std::collections::HashMap; use std::error::Error; use std::io; use std::io::prelude::*; use std::net::SocketAddr; use mio::*; use mio::net::{TcpListener, TcpStream}; // Setup some tokens to allow us to identify which event is // for which socket. const LISTENER: Token = Token(0); enum State { New, Connected, } struct Piece; struct Torrent<'a> { metainfo: metainfo::MetaInfo<'a>, pieces: Vec<Piece>, peers: Vec<Peer>, } struct Peer { peer_id: Vec<u8>, choked: bool, interested: bool, bitfield: Vec<u8>, } pub fn serve<T: Into<SocketAddr>>(addr: T) -> Result<(), Box<Error>> { let addr = addr.into(); // Setup the server socket let listener = TcpListener::bind(&addr).unwrap(); // Create a poll instance let poll = Poll::new().unwrap(); // Start listening for incoming connections poll.register(&listener, LISTENER, Ready::readable(), PollOpt::edge()) .unwrap(); // Create storage for events let mut events = Events::with_capacity(1024); let mut next_token_index = 1; let mut sockets = HashMap::new(); let mut buf = [0; 1024]; loop { poll.poll(&mut events, None).unwrap(); for event in events.iter() { match event.token() { LISTENER => loop { match listener.accept() { Ok((socket, _)) => { let token = Token(next_token_index); poll.register(&socket, token, Ready::readable(), PollOpt::edge())?; next_token_index += 1; sockets.insert(token, socket); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { break; } err => panic!("err={:?}", err), } }, token => { // Loop to drain the event buffer, because we are edge polling loop { match sockets.get_mut(&token).unwrap().read(&mut buf) { Ok(0) => { // Socket is closed; remove it from the hashmap sockets.remove(&token); break; } Ok(n) => { if buf[n - 1] == b'\n' { println!("got a newline"); &buf[..(n - 1)].reverse(); } else { println!("got {}", buf[n - 1]); &buf[..n].reverse(); } sockets.get_mut(&token).unwrap().write(&buf[..n])?; // handle data } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { // Socket is no longer ready; stop reading break; } err => panic!("err={:?}", err), } } } } } } Ok(()) }
# ! [ doc = "Debug support" ] # [ doc = r" Register block" ] # [ repr ( C ) ] pub struct Dbgmcu { # [ doc = "0x00 - MCU Device ID Code Register" ] pub idcode: Idcode, # [ doc = "0x04 - Debug MCU Configuration Register" ] pub cr: Cr, # [ doc = "0x08 - APB Low Freeze Register" ] pub apblfz: Apblfz, # [ doc = "0x0c - APB High Freeze Register" ] pub apbhfz: Apbhfz, } # [ doc = "MCU Device ID Code Register" ] # [ repr ( C ) ] pub struct Idcode { register: ::volatile_register::RO<u32>, } # [ doc = "MCU Device ID Code Register" ] pub mod idcode { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } impl super::Idcode { # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } } # [ doc = "Value of the field DEV_ID" ] pub struct DevIdR { bits: u16, } impl DevIdR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u16 { self.bits } } # [ doc = "Value of the field DIV_ID" ] pub struct DivIdR { bits: u8, } impl DivIdR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field REV_ID" ] pub struct RevIdR { bits: u16, } impl RevIdR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u16 { self.bits } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _dev_id(&self) -> u16 { const MASK: u16 = 4095; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u16 } # [ doc = "Bits 0:11 - Device Identifier" ] pub fn dev_id(&self) -> DevIdR { DevIdR { bits: self._dev_id() } } fn _div_id(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 12:15 - Division Identifier" ] pub fn div_id(&self) -> DivIdR { DivIdR { bits: self._div_id() } } fn _rev_id(&self) -> u16 { const MASK: u16 = 65535; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u16 } # [ doc = "Bits 16:31 - Revision Identifier" ] pub fn rev_id(&self) -> RevIdR { RevIdR { bits: self._rev_id() } } } } # [ doc = "Debug MCU Configuration Register" ] # [ repr ( C ) ] pub struct Cr { register: ::volatile_register::RW<u32>, } # [ doc = "Debug MCU Configuration Register" ] pub mod cr { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Cr { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field DBG_STOP" ] pub struct DbgStopR { bits: u8, } impl DbgStopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_STANDBY" ] pub struct DbgStandbyR { bits: u8, } impl DbgStandbyR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _DbgStopW<'a> { register: &'a mut W, } impl<'a> _DbgStopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgStandbyW<'a> { register: &'a mut W, } impl<'a> _DbgStandbyW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _dbg_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 1 - Debug Stop Mode" ] pub fn dbg_stop(&self) -> DbgStopR { DbgStopR { bits: self._dbg_stop() } } fn _dbg_standby(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 2 - Debug Standby Mode" ] pub fn dbg_standby(&self) -> DbgStandbyR { DbgStandbyR { bits: self._dbg_standby() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 1 - Debug Stop Mode" ] pub fn dbg_stop(&mut self) -> _DbgStopW { _DbgStopW { register: self } } # [ doc = "Bit 2 - Debug Standby Mode" ] pub fn dbg_standby(&mut self) -> _DbgStandbyW { _DbgStandbyW { register: self } } } } # [ doc = "APB Low Freeze Register" ] # [ repr ( C ) ] pub struct Apblfz { register: ::volatile_register::RW<u32>, } # [ doc = "APB Low Freeze Register" ] pub mod apblfz { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Apblfz { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field DBG_TIMER2_STOP" ] pub struct DbgTimer2StopR { bits: u8, } impl DbgTimer2StopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_TIMER3_STOP" ] pub struct DbgTimer3StopR { bits: u8, } impl DbgTimer3StopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_TIMER6_STOP" ] pub struct DbgTimer6StopR { bits: u8, } impl DbgTimer6StopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_TIMER14_STOP" ] pub struct DbgTimer14StopR { bits: u8, } impl DbgTimer14StopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_RTC_STOP" ] pub struct DbgRtcStopR { bits: u8, } impl DbgRtcStopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_WWDG_STOP" ] pub struct DbgWwdgStopR { bits: u8, } impl DbgWwdgStopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_IWDG_STOP" ] pub struct DbgIwdgStopR { bits: u8, } impl DbgIwdgStopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field I2C1_SMBUS_TIMEOUT" ] pub struct I2c1SmbusTimeoutR { bits: u8, } impl I2c1SmbusTimeoutR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _DbgTimer2StopW<'a> { register: &'a mut W, } impl<'a> _DbgTimer2StopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgTimer3StopW<'a> { register: &'a mut W, } impl<'a> _DbgTimer3StopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgTimer6StopW<'a> { register: &'a mut W, } impl<'a> _DbgTimer6StopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgTimer14StopW<'a> { register: &'a mut W, } impl<'a> _DbgTimer14StopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgRtcStopW<'a> { register: &'a mut W, } impl<'a> _DbgRtcStopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgWwdgStopW<'a> { register: &'a mut W, } impl<'a> _DbgWwdgStopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgIwdgStopW<'a> { register: &'a mut W, } impl<'a> _DbgIwdgStopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _I2c1SmbusTimeoutW<'a> { register: &'a mut W, } impl<'a> _I2c1SmbusTimeoutW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 21; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _dbg_timer2_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 0 - Debug Timer 2 stopped when Core is halted" ] pub fn dbg_timer2_stop(&self) -> DbgTimer2StopR { DbgTimer2StopR { bits: self._dbg_timer2_stop() } } fn _dbg_timer3_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 1 - Debug Timer 3 stopped when Core is halted" ] pub fn dbg_timer3_stop(&self) -> DbgTimer3StopR { DbgTimer3StopR { bits: self._dbg_timer3_stop() } } fn _dbg_timer6_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 4 - Debug Timer 6 stopped when Core is halted" ] pub fn dbg_timer6_stop(&self) -> DbgTimer6StopR { DbgTimer6StopR { bits: self._dbg_timer6_stop() } } fn _dbg_timer14_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 8 - Debug Timer 14 stopped when Core is halted" ] pub fn dbg_timer14_stop(&self) -> DbgTimer14StopR { DbgTimer14StopR { bits: self._dbg_timer14_stop() } } fn _dbg_rtc_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 10 - Debug RTC stopped when Core is halted" ] pub fn dbg_rtc_stop(&self) -> DbgRtcStopR { DbgRtcStopR { bits: self._dbg_rtc_stop() } } fn _dbg_wwdg_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted" ] pub fn dbg_wwdg_stop(&self) -> DbgWwdgStopR { DbgWwdgStopR { bits: self._dbg_wwdg_stop() } } fn _dbg_iwdg_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted" ] pub fn dbg_iwdg_stop(&self) -> DbgIwdgStopR { DbgIwdgStopR { bits: self._dbg_iwdg_stop() } } fn _i2c1_smbus_timeout(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 21 - SMBUS timeout mode stopped when Core is halted" ] pub fn i2c1_smbus_timeout(&self) -> I2c1SmbusTimeoutR { I2c1SmbusTimeoutR { bits: self._i2c1_smbus_timeout() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 0 - Debug Timer 2 stopped when Core is halted" ] pub fn dbg_timer2_stop(&mut self) -> _DbgTimer2StopW { _DbgTimer2StopW { register: self } } # [ doc = "Bit 1 - Debug Timer 3 stopped when Core is halted" ] pub fn dbg_timer3_stop(&mut self) -> _DbgTimer3StopW { _DbgTimer3StopW { register: self } } # [ doc = "Bit 4 - Debug Timer 6 stopped when Core is halted" ] pub fn dbg_timer6_stop(&mut self) -> _DbgTimer6StopW { _DbgTimer6StopW { register: self } } # [ doc = "Bit 8 - Debug Timer 14 stopped when Core is halted" ] pub fn dbg_timer14_stop(&mut self) -> _DbgTimer14StopW { _DbgTimer14StopW { register: self } } # [ doc = "Bit 10 - Debug RTC stopped when Core is halted" ] pub fn dbg_rtc_stop(&mut self) -> _DbgRtcStopW { _DbgRtcStopW { register: self } } # [ doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted" ] pub fn dbg_wwdg_stop(&mut self) -> _DbgWwdgStopW { _DbgWwdgStopW { register: self } } # [ doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted" ] pub fn dbg_iwdg_stop(&mut self) -> _DbgIwdgStopW { _DbgIwdgStopW { register: self } } # [ doc = "Bit 21 - SMBUS timeout mode stopped when Core is halted" ] pub fn i2c1_smbus_timeout(&mut self) -> _I2c1SmbusTimeoutW { _I2c1SmbusTimeoutW { register: self } } } } # [ doc = "APB High Freeze Register" ] # [ repr ( C ) ] pub struct Apbhfz { register: ::volatile_register::RW<u32>, } # [ doc = "APB High Freeze Register" ] pub mod apbhfz { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Apbhfz { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field DBG_TIMER1_STOP" ] pub struct DbgTimer1StopR { bits: u8, } impl DbgTimer1StopR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_TIMER15_STO" ] pub struct DbgTimer15StoR { bits: u8, } impl DbgTimer15StoR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_TIMER16_STO" ] pub struct DbgTimer16StoR { bits: u8, } impl DbgTimer16StoR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field DBG_TIMER17_STO" ] pub struct DbgTimer17StoR { bits: u8, } impl DbgTimer17StoR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _DbgTimer1StopW<'a> { register: &'a mut W, } impl<'a> _DbgTimer1StopW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgTimer15StoW<'a> { register: &'a mut W, } impl<'a> _DbgTimer15StoW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgTimer16StoW<'a> { register: &'a mut W, } impl<'a> _DbgTimer16StoW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 17; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _DbgTimer17StoW<'a> { register: &'a mut W, } impl<'a> _DbgTimer17StoW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 18; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _dbg_timer1_stop(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 11 - Debug Timer 1 stopped when Core is halted" ] pub fn dbg_timer1_stop(&self) -> DbgTimer1StopR { DbgTimer1StopR { bits: self._dbg_timer1_stop() } } fn _dbg_timer15_sto(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 16 - Debug Timer 15 stopped when Core is halted" ] pub fn dbg_timer15_sto(&self) -> DbgTimer15StoR { DbgTimer15StoR { bits: self._dbg_timer15_sto() } } fn _dbg_timer16_sto(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 17 - Debug Timer 16 stopped when Core is halted" ] pub fn dbg_timer16_sto(&self) -> DbgTimer16StoR { DbgTimer16StoR { bits: self._dbg_timer16_sto() } } fn _dbg_timer17_sto(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 18 - Debug Timer 17 stopped when Core is halted" ] pub fn dbg_timer17_sto(&self) -> DbgTimer17StoR { DbgTimer17StoR { bits: self._dbg_timer17_sto() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 11 - Debug Timer 1 stopped when Core is halted" ] pub fn dbg_timer1_stop(&mut self) -> _DbgTimer1StopW { _DbgTimer1StopW { register: self } } # [ doc = "Bit 16 - Debug Timer 15 stopped when Core is halted" ] pub fn dbg_timer15_sto(&mut self) -> _DbgTimer15StoW { _DbgTimer15StoW { register: self } } # [ doc = "Bit 17 - Debug Timer 16 stopped when Core is halted" ] pub fn dbg_timer16_sto(&mut self) -> _DbgTimer16StoW { _DbgTimer16StoW { register: self } } # [ doc = "Bit 18 - Debug Timer 17 stopped when Core is halted" ] pub fn dbg_timer17_sto(&mut self) -> _DbgTimer17StoW { _DbgTimer17StoW { register: self } } } }
use std::ops::{Deref, DerefMut}; use controlled::Controlled; use lens::LensWrap; use crate::{ controllers::TypedController, lens::Lens, math::{Size, Vector2}, Backend, BoxConstraints, }; use self::styled::Styled; pub mod controlled; pub mod lens; pub mod pod; pub mod styled; pub trait CoreExt<T, B: Backend>: TypedWidget<T, B> + Sized + 'static { fn boxed(self) -> Box<Self> { Box::new(self) } fn controlled<C: TypedController<T, Self, B>>( self, controller: C, ) -> Controlled<T, Self, C, B> { Controlled::new(self, controller) } fn lens<U, L: Lens<T, U>>(self, lens: L) -> LensWrap<T, U, L, Self, B> where Self: TypedWidget<U, B>, { LensWrap::new(self, lens) } fn styled<U: Clone, W: TypedWidget<T, B>, L: Lens<T, U>, LW: Lens<W, U>>( self, lens: L, lens_widget: LW, ) -> Styled<U, L, LW, W, Self, B> where Self: Deref<Target = W> + DerefMut, { Styled::new(self, lens, lens_widget) } } impl<T, B: Backend, W: TypedWidget<T, B> + 'static> CoreExt<T, B> for W {} pub trait Widget<T> { type Primitive; type Context; type Event; type Reaction; fn draw(&self, origin: Vector2, size: Size, data: &T) -> Self::Primitive; fn event( &mut self, _origin: Vector2, _size: Size, _data: &mut T, _event: Self::Event, ) -> Option<Self::Reaction> { None } fn layout(&mut self, bc: &BoxConstraints, context: &Self::Context, data: &T) -> Size; } impl<T> Widget<T> for () { type Primitive = (); type Context = (); type Event = (); type Reaction = (); fn layout(&mut self, _bc: &BoxConstraints, _context: &Self::Context, _data: &T) -> Size { Size { width: 0., height: 0., } } fn draw(&self, _origin: Vector2, _size: Size, _data: &T) -> Self::Primitive {} } impl<T, W: Widget<T>> Widget<T> for Box<W> { type Primitive = W::Primitive; type Context = W::Context; type Event = W::Event; type Reaction = W::Reaction; fn layout(&mut self, bc: &BoxConstraints, context: &Self::Context, data: &T) -> Size { self.as_mut().layout(bc, context, data) } fn event( &mut self, origin: Vector2, size: Size, data: &mut T, event: Self::Event, ) -> Option<Self::Reaction> { self.as_mut().event(origin, size, data, event) } fn draw(&self, origin: Vector2, size: Size, data: &T) -> Self::Primitive { self.as_ref().draw(origin, size, data) } } pub trait TypedWidget<T, B: Backend>: sealed::InnerTypedWidget<T, B> { fn draw(&self, origin: Vector2, size: Size, data: &T) -> B::Primitive; fn event( &mut self, origin: Vector2, size: Size, data: &mut T, event: B::Event, ) -> Option<B::EventReaction>; fn layout(&mut self, bc: &BoxConstraints, backend: &B, data: &T) -> Size; } impl<T, B: Backend, TW> TypedWidget<T, B> for TW where TW: sealed::InnerTypedWidget<T, B>, { fn layout(&mut self, bc: &BoxConstraints, backend: &B, data: &T) -> Size { <Self as sealed::InnerTypedWidget<T, B>>::layout(self, bc, backend, data) } fn event( &mut self, origin: Vector2, size: Size, data: &mut T, event: B::Event, ) -> Option<B::EventReaction> { <Self as sealed::InnerTypedWidget<T, B>>::event(self, origin, size, data, event) } fn draw(&self, bounds: Vector2, size: Size, data: &T) -> B::Primitive { <Self as sealed::InnerTypedWidget<T, B>>::draw(self, bounds, size, data) } } mod sealed { use super::Widget; use crate::{ contexts::ContextProvider, controllers::TransformEvent, math::Vector2, Backend, BoxConstraints, Size, }; pub trait InnerTypedWidget<T, B: Backend> { fn draw(&self, bounds: Vector2, size: Size, data: &T) -> B::Primitive; fn event( &mut self, origin: Vector2, size: Size, data: &mut T, event: B::Event, ) -> Option<B::EventReaction>; fn layout(&mut self, bc: &BoxConstraints, backend: &B, data: &T) -> Size; } impl<T, W, P, C, B: Backend> InnerTypedWidget<T, B> for W where W: Widget<T, Primitive = P, Context = C>, B::Primitive: From<P>, B: ContextProvider<C>, B::Event: TransformEvent<W::Event>, B::EventReaction: From<W::Reaction>, { fn layout(&mut self, bc: &BoxConstraints, backend: &B, data: &T) -> Size { let context = backend.provide(); <Self as Widget<T>>::layout(self, bc, context, data) } fn event( &mut self, origin: Vector2, size: Size, data: &mut T, event: B::Event, ) -> Option<B::EventReaction> { event.transform_event().and_then(|event| { <Self as Widget<T>>::event(self, origin, size, data, event) .map(|reaction| reaction.into()) }) } fn draw(&self, bounds: Vector2, size: Size, data: &T) -> B::Primitive { <Self as Widget<T>>::draw(self, bounds, size, data).into() } } }
use crate::{builtins::PyBaseExceptionRef, convert::ToPyException, VirtualMachine}; #[cfg(feature = "rustpython-codegen")] pub use rustpython_codegen::CompileOpts; #[cfg(feature = "rustpython-compiler")] pub use rustpython_compiler::*; #[cfg(not(feature = "rustpython-compiler"))] pub use rustpython_compiler_core as core; #[cfg(all(not(feature = "rustpython-compiler"), feature = "rustpython-parser"))] pub use rustpython_parser_core as parser; #[cfg(not(feature = "rustpython-compiler"))] mod error { #[cfg(all(feature = "rustpython-parser", feature = "rustpython-codegen"))] panic!("Use --features=compiler to enable both parser and codegen"); #[derive(Debug, thiserror::Error)] pub enum CompileErrorType { #[cfg(feature = "rustpython-codegen")] #[error(transparent)] Codegen(#[from] rustpython_codegen::error::CodegenErrorType), #[cfg(feature = "rustpython-parser")] #[error(transparent)] Parse(#[from] rustpython_parser::error::ParseErrorType), } pub type CompileError = rustpython_compiler_core::CompileError<CompileErrorType>; } #[cfg(not(feature = "rustpython-compiler"))] pub use error::{CompileError, CompileErrorType}; impl ToPyException for (CompileError, Option<&str>) { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_syntax_error(&self.0, self.1) } }
// Copyright 2016 PingCAP, 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use rocksdb::{DB, Writable, WriteBatch}; use kvproto::raft_serverpb::{StoreIdent, RegionLocalState}; use kvproto::metapb; use raftstore::Result; use super::keys; use super::engine::{Iterable, Mutable}; use super::peer_storage::write_initial_state; use util::rocksdb; use storage::{CF_DEFAULT, CF_RAFT}; const INIT_EPOCH_VER: u64 = 1; const INIT_EPOCH_CONF_VER: u64 = 1; // check no any data in range [start_key, end_key) fn is_range_empty(engine: &DB, cf: &str, start_key: &[u8], end_key: &[u8]) -> Result<bool> { let mut count: u32 = 0; try!(engine.scan_cf(cf, start_key, end_key, false, &mut |_, _| { count += 1; Ok(false) })); Ok(count == 0) } // Bootstrap the store, the DB for this store must be empty and has no data. pub fn bootstrap_store(engine: &DB, cluster_id: u64, store_id: u64) -> Result<()> { let mut ident = StoreIdent::new(); if !try!(is_range_empty(engine, CF_DEFAULT, keys::MIN_KEY, keys::MAX_KEY)) { return Err(box_err!("store is not empty and has already had data.")); } let ident_key = keys::store_ident_key(); ident.set_cluster_id(cluster_id); ident.set_store_id(store_id); engine.put_msg(&ident_key, &ident) } // Write first region meta and prepare state. pub fn write_prepare_bootstrap(engine: &DB, region: &metapb::Region) -> Result<()> { let mut state = RegionLocalState::new(); state.set_region(region.clone()); let wb = WriteBatch::new(); try!(wb.put_msg(&keys::region_state_key(region.get_id()), &state)); try!(write_initial_state(engine, &wb, region.get_id())); try!(wb.put_msg(&keys::prepare_bootstrap_key(), region)); try!(engine.write(wb)); Ok(()) } // Clear first region meta and prepare state. pub fn clear_prepare_bootstrap(engine: &DB, region_id: u64) -> Result<()> { let wb = WriteBatch::new(); try!(wb.delete(&keys::region_state_key(region_id))); try!(wb.delete(&keys::prepare_bootstrap_key())); // should clear raft initial state too. let raft_cf = try!(rocksdb::get_cf_handle(engine, CF_RAFT)); try!(wb.delete_cf(raft_cf, &keys::raft_state_key(region_id))); try!(wb.delete_cf(raft_cf, &keys::apply_state_key(region_id))); try!(engine.write(wb)); Ok(()) } // Clear prepare state pub fn clear_prepare_bootstrap_state(engine: &DB) -> Result<()> { try!(engine.delete(&keys::prepare_bootstrap_key())); Ok(()) } // Prepare bootstrap. pub fn prepare_bootstrap(engine: &DB, store_id: u64, region_id: u64, peer_id: u64) -> Result<metapb::Region> { let mut region = metapb::Region::new(); region.set_id(region_id); region.set_start_key(keys::EMPTY_KEY.to_vec()); region.set_end_key(keys::EMPTY_KEY.to_vec()); region.mut_region_epoch().set_version(INIT_EPOCH_VER); region.mut_region_epoch().set_conf_ver(INIT_EPOCH_CONF_VER); let mut peer = metapb::Peer::new(); peer.set_store_id(store_id); peer.set_id(peer_id); region.mut_peers().push(peer); try!(write_prepare_bootstrap(engine, &region)); Ok(region) } #[cfg(test)] mod tests { use tempdir::TempDir; use super::*; use util::rocksdb; use raftstore::store::engine::Peekable; use raftstore::store::keys; use storage::{CF_DEFAULT, CF_RAFT}; #[test] fn test_bootstrap() { let path = TempDir::new("var").unwrap(); let engine = rocksdb::new_engine(path.path().to_str().unwrap(), &[CF_RAFT]).unwrap(); assert!(bootstrap_store(&engine, 1, 1).is_ok()); assert!(bootstrap_store(&engine, 1, 1).is_err()); assert!(prepare_bootstrap(&engine, 1, 1, 1).is_ok()); assert!(engine.get_value(&keys::region_state_key(1)).unwrap().is_some()); assert!(engine.get_value(&keys::prepare_bootstrap_key()).unwrap().is_some()); assert!(engine.get_value_cf(CF_RAFT, &keys::raft_state_key(1)).unwrap().is_some()); assert!(engine.get_value_cf(CF_RAFT, &keys::apply_state_key(1)).unwrap().is_some()); assert!(clear_prepare_bootstrap_state(&engine).is_ok()); assert!(clear_prepare_bootstrap(&engine, 1).is_ok()); assert!(is_range_empty(&engine, CF_DEFAULT, &keys::region_meta_prefix(1), &keys::region_meta_prefix(2)) .unwrap()); assert!(is_range_empty(&engine, CF_RAFT, &keys::region_raft_prefix(1), &keys::region_raft_prefix(2)) .unwrap()); } }
use std::{cell::RefCell, collections::HashMap, fmt::Debug, ops::Deref, rc::Rc}; use crate::ast::{Expression, FunctionDefinition, LValue, Program, Statement, Type}; #[derive(Debug, Clone)] pub enum SemanticError<'a> { AlreadyDeclared, MustBePreviouslyDeclared, MustBeAFunction, TypeOfParametersIncorrect, BreakMustBeInsideOfFor, ReturnMustBeInsideOfFunction, TypesMustBeTheSame(Type<'a>, Type<'a>), AllocationOnlyForArray, OperationOnlyForNumeric, } #[derive(Clone)] pub struct Link<T>(Rc<RefCell<T>>); impl<T> Link<T> { pub fn new(data: T) -> Self { Self(Rc::new(RefCell::new(data))) } } impl<T> Deref for Link<T> { type Target = RefCell<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: std::fmt::Debug> Debug for Link<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.deref().borrow()) } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum ScopeKind { Function, For, Block, Global, } #[derive(Clone)] pub struct Scope<'a> { pub symbol_table: HashMap<&'a str, Type<'a>>, pub child_scopes: Vec<Link<Scope<'a>>>, pub parent_scope: Option<Link<Scope<'a>>>, pub kind: ScopeKind, level: usize, } impl<'a> Scope<'a> { fn new(parent_scope: Link<Scope<'a>>, kind: ScopeKind) -> Scope<'a> { let level = parent_scope.deref().borrow().level; Scope { symbol_table: HashMap::new(), child_scopes: Vec::new(), parent_scope: Some(parent_scope), kind, level, } } pub fn new_global() -> Link<Scope<'a>> { Link::new(Scope { symbol_table: HashMap::new(), child_scopes: Vec::new(), parent_scope: None, kind: ScopeKind::Global, level: 0, }) } fn create_child_scope(&mut self, kind: ScopeKind) -> Link<Scope<'a>> { let child = Link::new(Scope::new(Link::new(self.clone()), kind)); self.child_scopes.push(Link::clone(&child)); child } fn add_symbol(&mut self, name: &'a str, ty: Type<'a>) -> Result<(), SemanticError<'a>> { // let mut me = self.clone(); let was_empty = self.symbol_table.insert(name, ty).is_none(); if !was_empty { return Err(SemanticError::AlreadyDeclared); } Ok(()) } fn lookup_symbol(&self, name: &str) -> Result<Type<'a>, SemanticError<'a>> { if let Some(ty) = self.symbol_table.get(name) { Ok(ty.clone()) } else { match &self.parent_scope { None => Err(SemanticError::MustBePreviouslyDeclared), Some(scope) => (*scope.clone()).borrow().lookup_symbol(name), } } } fn is_inside(&self, kind: ScopeKind) -> bool { if self.kind == kind { true } else { match &self.parent_scope { None => false, Some(scope) => (*scope.clone()).borrow().is_inside(kind), } } } } impl Debug for Scope<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Scope") .field("kind", &self.kind) .field("symbol_table", &self.symbol_table) .field("child_scopes", &format_args!("{:#?}", self.child_scopes)) .finish() } } pub(crate) trait TypeCheckable { fn type_check<'a>( &'a self, scope: Link<Scope<'a>>, ) -> Result<(Link<Scope<'a>>, Type<'a>), SemanticError<'a>>; } impl<'a> TypeCheckable for Program<'a> { fn type_check<'b>( &'b self, scope: Link<Scope<'b>>, ) -> Result<(Link<Scope<'b>>, Type<'b>), SemanticError<'b>> { match self { Program::FuncList(funcs) => funcs .into_iter() .try_fold((scope, Type::Void), |(scope, _), f| f.type_check(scope)), Program::Statement(stmt) => stmt.type_check(scope), } } } impl<'a> TypeCheckable for FunctionDefinition<'a> { fn type_check<'b>( &'b self, scope: Link<Scope<'b>>, ) -> Result<(Link<Scope<'b>>, Type<'b>), SemanticError<'b>> { let f_scope = scope .deref() .borrow_mut() .create_child_scope(ScopeKind::Function); // add function parameters into child scope self.clone().parameters.into_iter().try_fold( f_scope.clone(), |scope, (p_ty, p_name)| { scope .clone() .deref() .borrow_mut() .add_symbol(p_name, p_ty) .map(|_| scope) }, )?; // lower all statements of the function self.body .iter() .try_fold((f_scope.clone(), Type::Void), |(scope, _), stmt| { stmt.type_check(scope) })?; // add function to current scope let f_type = Type::Function { params_types: self .clone() .parameters .into_iter() .map(|(ty, _)| ty) .collect(), return_type: Box::new( self.body .last() .and_then(|stmt| stmt.type_check(f_scope).map(|(_sc, ty)| ty).ok()) .unwrap_or(Type::Void), ), }; scope .clone() .deref() .borrow_mut() .add_symbol(self.name, f_type.clone()) .map(|_| (scope, f_type)) } } impl<'a> TypeCheckable for Expression<'a> { fn type_check<'b>( &'b self, scope: Link<Scope<'b>>, ) -> Result<(Link<Scope<'b>>, Type<'b>), SemanticError<'b>> { match self { Expression::Binary(rhs, _op, lhs) => { rhs.type_check(scope).and_then(|(scope, rhs_ty)| { lhs.type_check(scope.clone()).and_then(|(_, lhs_ty)| { if !rhs_ty.can_be_casted_to(&lhs_ty) { Err(SemanticError::TypesMustBeTheSame(rhs_ty, lhs_ty)) } else { Ok((scope, rhs_ty)) } }) }) } Expression::Unary(_op, expr) => expr.type_check(scope).and_then(|(scope, ty)| { if !ty.is_numeric() { Err(SemanticError::OperationOnlyForNumeric) } else { Ok((scope, ty)) } }), Expression::IntLiteral(_) => Ok((scope, Type::Int)), Expression::FloatLiteral(_) => Ok((scope, Type::Float)), Expression::StringLiteral(_) => Ok((scope, Type::String)), Expression::Null => Ok((scope, Type::Null)), Expression::LValue(lval) => lval.type_check(scope), Expression::FunctionCall(f, params) => { let f_type = scope.deref().borrow().lookup_symbol(f)?; match f_type { Type::Function { params_types, return_type, } => { let supplied_params_types = params .into_iter() .map(|p| scope.deref().borrow().lookup_symbol(p)) .collect::<Result<Vec<Type>, _>>()?; let params_correct = supplied_params_types .iter() .zip(params_types) .all(|(a, b)| *a == b); if !params_correct { Err(SemanticError::TypeOfParametersIncorrect) } else { Ok((scope, *return_type)) } } _ => Err(SemanticError::MustBeAFunction), } } Expression::Alloc(alloc_ty) => match alloc_ty { Type::Array(_ty, expr) => { expr.type_check(scope.clone()) .and_then(|(scope, ty)| match ty.is_numeric() { true => Ok((scope, alloc_ty.clone())), false => Err(SemanticError::OperationOnlyForNumeric), }) } _ => Err(SemanticError::AllocationOnlyForArray), }, } } } impl<'a> TypeCheckable for Statement<'a> { fn type_check<'b>( &'b self, scope: Link<Scope<'b>>, ) -> Result<(Link<Scope<'b>>, Type<'b>), SemanticError<'b>> { match self { Statement::VariableDeclaration(ty, name) => scope .clone() .deref() .borrow_mut() .add_symbol(name, ty.clone()) .map(|_| (scope, Type::Void)), Statement::StatementList(stmts) => { let mut child = scope .deref() .borrow_mut() .create_child_scope(ScopeKind::Block); let mut ty = Type::Void; for stmt in stmts { let rst = stmt.type_check(child)?; child = rst.0; ty = rst.1; } Ok((scope, ty)) } Statement::If { condition, true_path, // TODO: false_path: _, } => { condition .type_check(scope.clone()) .and(true_path.type_check(scope.clone())) // false_path.map(|stmt| { // stmt.lower(scope); // }); } Statement::Read(lval) => lval.type_check(scope), Statement::Print(stmt) => stmt.type_check(scope), Statement::Return => match scope .clone() .deref() .borrow() .is_inside(ScopeKind::Function) { true => Ok((scope, Type::Void)), false => Err(SemanticError::ReturnMustBeInsideOfFunction), }, Statement::Break => match scope.clone().deref().borrow().is_inside(ScopeKind::For) { true => Ok((scope, Type::Void)), false => Err(SemanticError::BreakMustBeInsideOfFor), }, Statement::Assignment(lval, expr) => { let (scope, l_ty) = lval.type_check(scope.clone())?; let (scope, expr_ty) = expr.type_check(scope)?; if !l_ty.can_be_casted_to(&expr_ty) { Err(SemanticError::TypesMustBeTheSame(l_ty, expr_ty)) } else { Ok((scope, l_ty)) } } Statement::For { initial_assignment, condition, post_assignment, body, } => initial_assignment .type_check(scope.clone()) .and(condition.type_check(scope.clone())) .and(post_assignment.type_check(scope.clone())) .and_then(|_| { let for_scope = scope .deref() .borrow_mut() .create_child_scope(ScopeKind::For); body.type_check(for_scope).map(|_| (scope, Type::Void)) }), } } } impl<'a> TypeCheckable for LValue<'a> { fn type_check<'b>( &'b self, scope: Link<Scope<'b>>, ) -> Result<(Link<Scope<'b>>, Type<'b>), SemanticError<'b>> { match &self { LValue::NameReference(name) => (*scope.clone()) .borrow() .lookup_symbol(name) .map(|ty| (scope, ty)), LValue::ArrayAccess(lval, expr) => { lval.as_ref() .type_check(scope) .and_then(|(scope, lval_ty)| { expr.type_check(scope) .and_then(|(scope, ty)| match ty.is_numeric() { true => Ok((scope, { match lval_ty { Type::Array(base_ty, _) => base_ty.deref().clone(), x => panic!("must be array type, got: {:?}", x), } })), false => Err(SemanticError::OperationOnlyForNumeric), }) }) } } } }
use config::Config; use errors::*; use clap::{App, Arg, ArgMatches, SubCommand}; pub fn setup<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("auth") .about("Authorizes a user to update a domain") .arg( Arg::with_name("USER") .help("Specifies the user") .required(true) .index(1) ) .arg( Arg::with_name("DOMAIN") .help("Specifies the domain name") .required(true) .index(2) ) } pub fn call(args: &ArgMatches) -> Result<()> { // Load the config let config_file = args.value_of("config").unwrap(); let mut config = Config::load(config_file)?; { // Find the user let user_str = args.value_of("USER").unwrap(); let user = match config.user_mut(user_str) { Some(user) => user, None => bail!(format!("A user named '{}' does not exist", user_str)), // TODO Use proper error! }; // Decode the domain let domain_str = args.value_of("DOMAIN").unwrap(); let domain = domain_str.parse()?; // Authorize the user for the domain if !user.domains.add(domain) { bail!(format!( "The user '{}' is already authorized for the domain '{}'", user_str, domain_str, )); // TODO Use proper error! } } // Store the config config.store(config_file)?; Ok(()) }
use std::fs; fn get_adjacent_seats (x: i32, y: i32, map: &Vec<Vec<char>>) -> Vec<char> { let mut seats: Vec<char> = vec![]; for i in -1..2 { if i + x < 0 || x + i >= map.len() as i32 { continue; } let line = &map[(x + i) as usize]; for j in -1..2 { if j + y < 0 || y + j >= line.len() as i32{ continue; } if i == 0 && j == 0 { continue } let char = line[(y+j) as usize]; if char != '.' { seats.push(char) } } } seats } fn is_outside (x: i32, y: i32, map: &Vec<Vec<char>>) -> bool { if x < 0 || x >= map.len() as i32 { return true; } if y < 0 || y >= map[x as usize].len() as i32 { return true; } return false; } fn find_direction (map: &Vec<Vec<char>>, start_x: i32, start_y: i32, inc_x: i32, inc_y: i32) -> Option<char> { let mut try_x = start_x; let mut try_y = start_y; return loop { try_x = try_x + inc_x; try_y = try_y + inc_y; if is_outside(try_x, try_y, map) { break None; } if map[try_x as usize][try_y as usize] != '.' { break Some(map[try_x as usize][try_y as usize]); } }; } fn get_visible_seats (x: i32, y: i32, map: &Vec<Vec<char>>) -> Vec<char> { let mut seats: Vec<char> = vec![]; // O..n = y // . // n = x // TOP let val = find_direction(map, x, y, -1, 0); if val.is_some() { seats.push(val.unwrap()) } // TOP RIGHT let val = find_direction(map, x, y, -1, 1); if val.is_some() { seats.push(val.unwrap()); } // RIGHT let val = find_direction(map, x, y, 0, 1); if val.is_some() { seats.push(val.unwrap()); } // BOTTOM RIGHT let val = find_direction(map, x, y, 1, 1); if val.is_some() { seats.push(val.unwrap()); } // BOTTOM let val = find_direction(map, x, y, 1, 0); if val.is_some() { seats.push(val.unwrap()); } // BOTTOM LEFT let val = find_direction(map, x, y, 1, -1); if val.is_some() { seats.push(val.unwrap()); } // LEFT let val = find_direction(map, x, y, 0, -1); if val.is_some() { seats.push(val.unwrap()); } // TOP_LEFT let val = find_direction(map, x, y, -1, -1); if val.is_some() { seats.push(val.unwrap()); } seats } fn compute(map: &Vec<Vec<char>>, find_seat: fn(i32, i32, &Vec<Vec<char>>) -> Vec<char>) -> Vec<Vec<char>> { let mut next = map.clone(); for i in 0..map.len() { for j in 0..map[i].len() { let item = &map[i][j]; let adjacent_seats = find_seat(i as i32, j as i32, map); match item { 'L' => { let nb_free = adjacent_seats.clone().into_iter().filter(|i| i.clone() =='L').count(); if nb_free == adjacent_seats.len() { next[i][j] = '#'; } }, '#' => { let nb_occupied = adjacent_seats.clone().into_iter().filter(|i| i.clone() =='#').count(); if nb_occupied >= 5 { next[i][j] = 'L'; } }, _ => () } } } next } fn as_str (input: &Vec<Vec<char>>) -> String { input.into_iter().map(|chars| chars.iter().cloned().collect::<String>()).collect::<Vec<String>>().join("\n") } fn run (map: &Vec<Vec<char>>, find_seat: fn(i32, i32, &Vec<Vec<char>>) -> Vec<char>) { let mut base = map.clone(); let mut _i = 0; loop { _i += 1; println!("\n### {} ###\n", _i); let next = compute(&base, find_seat); println!("{}", as_str(&next)); if as_str(&next) == as_str(&base) { base = next; break; } else { base = next } } let mut nb_occupied_seats = 0; for i in 0..base.len() { let line = &base[i]; for j in 0..line.len() { let char = line[j]; if char == '#' { nb_occupied_seats += 1; } } } println!("\n\nResult: {}", nb_occupied_seats); } fn main() { let file_path = "src/input.txt"; let lines: Vec<Vec<char>> = fs::read_to_string(file_path).expect("Cannot open file!").lines().map(|l| l.chars().collect()).collect(); run(&lines, get_visible_seats); //let result = get_visible_seats(4, 3, &lines); //println!("{:?}", result); }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. This file may not be copied, modified, or distributed // except according to those terms. // Test that we select between traits A and B. To do that, we must // consider the `Sized` bound. // pretty-expanded FIXME #23616 trait A { fn foo(self); } trait B { fn foo(self); } impl<T: Sized> A for *const T { fn foo(self) {} } impl<T> B for *const [T] { fn foo(self) {} } fn main() { let x: [isize; 4] = [1,2,3,4]; let xptr = &x[..] as *const [isize]; xptr.foo(); }
//! Models that manage data and logic used by the application service. /// The database connection pool mod connection_pool; /// A list of Events that are received from the Matirx homeserver. mod events; /// A Rocket.Chat channel or group mod rocketchat_room; /// `RocketchatServer` entry mod rocketchat_server; /// `Room` entry mod room; /// The database schema mod schema; /// `UserOnRocketchatServer` entry mod user_on_rocketchat_server; /// A virtual user on the Matrix homeserver that represents a Rocket.Chat user. mod virtual_user; pub use self::connection_pool::ConnectionPool; pub use self::events::Events; pub use self::rocketchat_room::RocketchatRoom; pub use self::rocketchat_server::{Credentials, NewRocketchatServer, RocketchatServer}; pub use self::room::Room; pub use self::user_on_rocketchat_server::{NewUserOnRocketchatServer, UserOnRocketchatServer}; pub use self::virtual_user::VirtualUser;
#[doc = "Reader of register ACRIS"] pub type R = crate::R<u32, super::ACRIS>; #[doc = "Reader of field `IN0`"] pub type IN0_R = crate::R<bool, bool>; #[doc = "Reader of field `IN1`"] pub type IN1_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Comparator 0 Interrupt Status"] #[inline(always)] pub fn in0(&self) -> IN0_R { IN0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Comparator 1 Interrupt Status"] #[inline(always)] pub fn in1(&self) -> IN1_R { IN1_R::new(((self.bits >> 1) & 0x01) != 0) } }
#![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate wasm_bindgen; mod board; use wasm_bindgen::prelude::*; use board::Board; #[wasm_bindgen] extern { fn alert(s: &str); #[wasm_bindgen(js_namespace = console)] fn log(s: &str); #[wasm_bindgen(js_namespace = console, js_name = log)] fn log_u32(a: u32); #[wasm_bindgen(js_namespace = console, js_name = log)] fn log_many(a: &str, b: &str); } //wasm calculate the next move //only accept string of board #[wasm_bindgen] pub fn next_move(board: &str) -> String { //log(&format!("Hello, {}!", board)); format!("{}", guess(board)) } fn guess(board: &str) -> String { let tiles = convert_board(board); let mut board = Board::new(tiles); log(&board.log()); let result = board.guess(); log(&format!("peek the board => {:?}", board)); result } fn convert_board(string_board: &str) -> Vec<u32> { let numbers: Vec<u32> = string_board.split(',') .map(|s| s.parse().unwrap()) .collect(); numbers } #[cfg(test)] mod tests { use super::{guess, convert_board}; #[test] fn it_can_guess() { // 1 0 0 // 0 0 0 // 0 0 0 assert_eq!(guess("0,0,0,0,0,0,0,0"), "0"); // 1-1 0 // 1 0 0 // 0 0 0 assert_eq!(guess("1,2,0,1,0,0,0,0"), "7"); // 1 0-1 // 1 1 0 //-1 0 0 assert_eq!(guess("1,0,2,1,0,2,0,0"), "6"); // 1 0 0 // 1 1 0 //-1 0-1 assert_eq!(guess("1,0,0,1,1,0,0,0"), "6"); // 1-1 0 // 1 1-1 //-1 0 0 assert_eq!(guess("1,2,0,1,1,2,2,0,0"), "9"); } #[test] fn it_can_convert_board() { let result = convert_board("0,0,0,1,0,1"); assert_eq!(result, [0, 0, 0, 1, 0, 1]); } }
extern crate regex; mod ast; mod evaluator; mod lexer; mod parser; mod token; mod utils; use evaluator::Evaluator; use lexer::Lexer; use parser::Parser; use std::env; use std::fs; use std::process; use utils::EvalError; fn main() { let args: Vec<String> = env::args().collect(); let file_path = match args.get(1) { Some(path) => path, None => "", }; let file = match fs::read_to_string(file_path) { Ok(file) => file, _ => { eprintln!("File {} not found!", file_path); process::exit(1); } }; match interpret(file) { Ok(_) => { println!("\nSuccess!"); process::exit(0); } Err(err) => { eprintln!("\n{}", err); process::exit(1); } } } fn interpret(file: String) -> Result<(), EvalError> { let lexer = Lexer::new(file); let mut parser = Parser::new(lexer); let program = parser.parse_program(); let syntax_errors = parser.get_errors(); match syntax_errors.is_empty() { false => { for err in syntax_errors { eprintln!("{}", err); } Err(EvalError::SyntaxError) } _ => { let mut evaluator = Evaluator::new(program); evaluator.evaluate_program() } } }
// 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. #[macro_use] extern crate zerocopy; fn main() {} #[derive(FromBytes)] union Foo {} #[derive(Unaligned)] union Bar {}
#[cfg(feature = "sgx")] use std::prelude::v1::*; use std::sync::Arc; use crate::page_cache::{PageEntry, PageEntryInner}; use crate::util::lru_list::{LruEntry, LruList}; pub struct PageLruList { inner: LruList<PageEntryInner>, } impl PageLruList { pub fn new() -> Self { let inner = LruList::new(); Self { inner } } pub fn insert(&mut self, entry: PageEntry) { let entry_inner = entry.unwrap(); self.inner.insert(entry_inner) } pub fn touch(&mut self, entry: &PageEntry) { self.inner.touch(entry.inner()) } pub fn remove(&mut self, entry: &PageEntry) { self.inner.remove(entry.inner()) } pub fn evict(&mut self) -> Option<PageEntry> { self.inner.evict().map(|inner| PageEntry::wrap(inner)) } pub fn evict_nr(&mut self, max_count: usize) -> Vec<PageEntry> { let evicted: Vec<Arc<LruEntry<PageEntryInner>>> = self.inner.evict_nr(max_count); unsafe { // This transmute is ok beceause PageEntry has the same memory layout as // Arc<LruEntry<PageEntryInner>>. std::mem::transmute(evicted) } } pub fn evict_nr_with( &mut self, max_count: usize, cond: impl FnMut(&PageEntryInner) -> bool, ) -> Vec<PageEntry> { let evicted: Vec<Arc<LruEntry<PageEntryInner>>> = self.inner.evict_nr_with(max_count, cond); unsafe { // This transmute is ok beceause PageEntry has the same memory layout as // Arc<LruEntry<PageEntryInner>>. std::mem::transmute(evicted) } } pub fn len(&self) -> usize { self.inner.len() } } impl Default for PageLruList { fn default() -> Self { Self::new() } } impl std::fmt::Debug for PageLruList { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_list() .entries(self.inner.iter().map(|lru_entry| lru_entry.inner())) .finish() } }
use crate::integer::Integer; use core::ops::AddAssign; // AddAssign The addition assignment operator +=. // ['Integer', 'Integer', 'Integer::add_assign', 'no', [], ['ref']] impl AddAssign<Integer> for Integer { fn add_assign(&mut self, rhs: Integer) { Integer::add_assign(self, &rhs) } } // ['Integer', '&Integer', 'Integer::add_assign', 'no', [], []] impl AddAssign<&Integer> for Integer { fn add_assign(&mut self, rhs: &Integer) { Integer::add_assign(self, rhs) } } // ['Integer', 'i8', 'Integer::add_c_long_assign', 'no', [], []] impl AddAssign<i8> for Integer { fn add_assign(&mut self, rhs: i8) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&i8', 'Integer::add_c_long_assign', 'no', [], ['deref']] impl AddAssign<&i8> for Integer { fn add_assign(&mut self, rhs: &i8) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'u8', 'Integer::add_c_long_assign', 'no', [], []] impl AddAssign<u8> for Integer { fn add_assign(&mut self, rhs: u8) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&u8', 'Integer::add_c_long_assign', 'no', [], ['deref']] impl AddAssign<&u8> for Integer { fn add_assign(&mut self, rhs: &u8) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'i16', 'Integer::add_c_long_assign', 'no', [], []] impl AddAssign<i16> for Integer { fn add_assign(&mut self, rhs: i16) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&i16', 'Integer::add_c_long_assign', 'no', [], ['deref']] impl AddAssign<&i16> for Integer { fn add_assign(&mut self, rhs: &i16) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'u16', 'Integer::add_c_long_assign', 'no', [], []] impl AddAssign<u16> for Integer { fn add_assign(&mut self, rhs: u16) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&u16', 'Integer::add_c_long_assign', 'no', [], ['deref']] impl AddAssign<&u16> for Integer { fn add_assign(&mut self, rhs: &u16) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'i32', 'Integer::add_c_long_assign', 'no', [], []] impl AddAssign<i32> for Integer { fn add_assign(&mut self, rhs: i32) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&i32', 'Integer::add_c_long_assign', 'no', [], ['deref']] impl AddAssign<&i32> for Integer { fn add_assign(&mut self, rhs: &i32) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'u32', 'Integer::add_c_long_assign', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl AddAssign<u32> for Integer { fn add_assign(&mut self, rhs: u32) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&u32', 'Integer::add_c_long_assign', 'no', [], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl AddAssign<&u32> for Integer { fn add_assign(&mut self, rhs: &u32) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'i64', 'Integer::add_c_long_assign', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl AddAssign<i64> for Integer { fn add_assign(&mut self, rhs: i64) { Integer::add_c_long_assign(self, rhs) } } // ['Integer', '&i64', 'Integer::add_c_long_assign', 'no', [], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl AddAssign<&i64> for Integer { fn add_assign(&mut self, rhs: &i64) { Integer::add_c_long_assign(self, *rhs) } } // ['Integer', 'u32', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl AddAssign<u32> for Integer { fn add_assign(&mut self, rhs: u32) { Integer::add_assign(self, &Integer::from(rhs)) } } // ['Integer', '&u32', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl AddAssign<&u32> for Integer { fn add_assign(&mut self, rhs: &u32) { Integer::add_assign(self, &Integer::from(*rhs)) } } // ['Integer', 'i64', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl AddAssign<i64> for Integer { fn add_assign(&mut self, rhs: i64) { Integer::add_assign(self, &Integer::from(rhs)) } } // ['Integer', '&i64', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl AddAssign<&i64> for Integer { fn add_assign(&mut self, rhs: &i64) { Integer::add_assign(self, &Integer::from(*rhs)) } } // ['Integer', 'u64', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] impl AddAssign<u64> for Integer { fn add_assign(&mut self, rhs: u64) { Integer::add_assign(self, &Integer::from(rhs)) } } // ['Integer', '&u64', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}, 'deref']] impl AddAssign<&u64> for Integer { fn add_assign(&mut self, rhs: &u64) { Integer::add_assign(self, &Integer::from(*rhs)) } } // ['Integer', 'i128', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] impl AddAssign<i128> for Integer { fn add_assign(&mut self, rhs: i128) { Integer::add_assign(self, &Integer::from(rhs)) } } // ['Integer', '&i128', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}, 'deref']] impl AddAssign<&i128> for Integer { fn add_assign(&mut self, rhs: &i128) { Integer::add_assign(self, &Integer::from(*rhs)) } } // ['Integer', 'u128', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] impl AddAssign<u128> for Integer { fn add_assign(&mut self, rhs: u128) { Integer::add_assign(self, &Integer::from(rhs)) } } // ['Integer', '&u128', 'Integer::add_assign', 'no', [], ['ref', {'convert': // 'Integer'}, 'deref']] impl AddAssign<&u128> for Integer { fn add_assign(&mut self, rhs: &u128) { Integer::add_assign(self, &Integer::from(*rhs)) } }
#[doc = "Reader of register MIS"] pub type R = crate::R<u32, super::MIS>; #[doc = "Reader of field `WDTMIS`"] pub type WDTMIS_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Watchdog Masked Interrupt Status"] #[inline(always)] pub fn wdtmis(&self) -> WDTMIS_R { WDTMIS_R::new((self.bits & 0x01) != 0) } }
#![feature(proc_macro_diagnostic)] #![feature(proc_macro_def_site)] #![feature(box_syntax)] #![feature(box_patterns)] extern crate proc_macro; mod bif; mod option_group; mod utils; use proc_macro::TokenStream; use syn::parse_macro_input; use syn::AttributeArgs; use self::option_group::{OptionGroupConfig, OptionGroupStruct}; /// Defines an option group which can be added to a `clap::App` as an argument #[proc_macro_attribute] pub fn option_group(attr: TokenStream, item: TokenStream) -> TokenStream { let option_group_config_args = parse_macro_input!(attr as AttributeArgs); let option_group_config = match OptionGroupConfig::from_args(option_group_config_args) { Ok(config) => config, Err(err) => return err.to_compile_error().into(), }; let option_group = parse_macro_input!(item as OptionGroupStruct); self::option_group::generate_option_group(option_group_config, option_group) } #[proc_macro] pub fn bif(input: TokenStream) -> TokenStream { use self::bif::BifSpec; let spec = parse_macro_input!(input as BifSpec); self::bif::define_bif(spec) } #[proc_macro] pub fn guard_bif(input: TokenStream) -> TokenStream { use self::bif::BifSpec; let spec = parse_macro_input!(input as BifSpec); self::bif::define_guard_bif(spec) }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::{bail, Result}; use starcoin_executor::TransactionExecutor; use starcoin_state_api::AccountStateReader; use starcoin_types::account_address::AccountAddress; use starcoin_types::transaction::authenticator::AuthenticationKey; use starcoin_types::transaction::RawUserTransaction; use starcoin_wallet_api::WalletAccount; pub struct MockTxnGenerator { receiver_address: AccountAddress, receiver_auth_key_prefix: Vec<u8>, account: WalletAccount, } impl MockTxnGenerator { pub fn new( account: WalletAccount, receiver_address: AccountAddress, receiver_auth_key_prefix: Vec<u8>, ) -> Self { // let (prikey, pubkey) = Self::gen_key_pair(); // let (b_pri, b_pub) = Self::gen_key_pair(); MockTxnGenerator { receiver_address, receiver_auth_key_prefix, account, } } pub fn generate_mock_txn<E>(&self, state_db: &AccountStateReader) -> Result<RawUserTransaction> where E: TransactionExecutor + Sync + Send, { let account_resource = state_db.get_account_resource(self.account.address())?; if account_resource.is_none() { bail!( "account {} not exists, please faucet it", self.account.address() ); } let account_resource = account_resource.unwrap(); // TODO: make it configurable let amount_to_transfer = 1000; let balance_resource = state_db.get_balance(self.account.address())?; if balance_resource.is_none() || (balance_resource.unwrap() <= amount_to_transfer) { bail!("not enough balance, skip gen mock txn, please faucet it first"); } let transfer_txn = <E as TransactionExecutor>::build_transfer_txn( self.account.address, AuthenticationKey::ed25519(&self.account.public_key).to_vec(), self.receiver_address, self.receiver_auth_key_prefix.clone(), account_resource.sequence_number(), amount_to_transfer, ); Ok(transfer_txn) } }
//! Utility functions for masking data frame payload data use rand; use std::io::Write; use std::io::Result as IoResult; use std::mem; #[cfg(feature = "nightly")] extern crate packed_simd as simd; /// Struct to pipe data into another writer, /// while masking the data being written pub struct Masker<'w> { key: [u8; 4], pos: usize, end: &'w mut Write, } impl<'w> Masker<'w> { /// Create a new Masker with the key and the endpoint /// to be writer to. pub fn new(key: [u8; 4], endpoint: &'w mut Write) -> Self { Masker { key: key, pos: 0, end: endpoint, } } } impl<'w> Write for Masker<'w> { fn write(&mut self, data: &[u8]) -> IoResult<usize> { let buf = mask_data(self.key, &data); self.end.write(&buf) } fn flush(&mut self) -> IoResult<()> { self.end.flush() } } /// Generates a random masking key pub fn gen_mask() -> [u8; 4] { // Faster than just calling random() many times unsafe { mem::transmute(rand::random::<u32>()) } } /// Masks data to send to a server and writes #[cfg(not(feature = "nightly"))] pub fn mask_data(mask: [u8; 4], data: &[u8]) -> Vec<u8> { let mut out = Vec::with_capacity(data.len()); unsafe { out.set_len(data.len()) }; let zip_iter = data.iter().zip(mask.iter().cycle()); for (i, (&buf_item, &key_item)) in zip_iter.enumerate() { out[i] = buf_item ^ key_item; } out } /// Masks data to send to a server and writes /// With the experimental SIMD support in stdsimd #[cfg(feature = "nightly")] pub fn mask_data(mask: [u8; 4], data: &[u8]) -> Vec<u8> { let simd_vector_size = 32; let original_len = data.len(); let mut aligned_len = simd_vector_size * (original_len / simd_vector_size); if aligned_len < original_len { aligned_len += simd_vector_size; } let mut out = Vec::with_capacity(aligned_len); unsafe { out.set_len(aligned_len) }; //let mask_vec = simd::u8x32::load_unaligned( let mask_vec = simd::u8x32::from_slice_unaligned( &mask.iter().cycle().take(simd_vector_size).cloned().collect::<Vec<u8>>()); for (i, slice) in data.chunks(simd_vector_size).enumerate() { let vec2 = { if (slice.len() == simd_vector_size) { //simd::u8x32::load_unaligned(&slice) simd::u8x32::from_slice_unaligned(&slice) } else { slice.iter().enumerate().fold(simd::u8x32::splat(0), |v, (i, &u)| v.replace(i, u)) } }; let vec3 = mask_vec ^ vec2; let start = simd_vector_size * i; let end = start + simd_vector_size; //vec3.store_unaligned(&mut out[start..end]); vec3.write_to_slice_unaligned(&mut out[start..end]); } unsafe { out.set_len(original_len) }; out } #[cfg(all(feature = "nightly", test))] mod tests { use super::*; use test; #[test] fn test_mask_data() { let key = [1u8, 2u8, 3u8, 4u8]; let original = vec![10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 17u8]; let expected = vec![11u8, 9u8, 15u8, 9u8, 15u8, 13u8, 19u8, 21u8]; let obtained = mask_data(key, &original[..]); let reversed = mask_data(key, &obtained[..]); assert_eq!(original, reversed); assert_eq!(obtained, expected); } #[bench] fn bench_mask_data(b: &mut test::Bencher) { let buffer = b"The quick brown fox jumps over the lazy dog"; let key = gen_mask(); b.iter(|| { let mut output = mask_data(key, buffer); test::black_box(&mut output); }); } #[bench] fn bench_gen_mask(b: &mut test::Bencher) { b.iter(|| { let mut key = gen_mask(); test::black_box(&mut key); }); } }
#[doc = "Writer for register BRR"] pub type W = crate::W<u32, super::BRR>; #[doc = "Register BRR `reset()`'s with value 0"] impl crate::ResetValue for super::BRR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Port Reset bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BR0_AW { #[doc = "0: No action on the corresponding ODx bit"] NOACTION = 0, #[doc = "1: Reset the ODx bit"] RESET = 1, } impl From<BR0_AW> for bool { #[inline(always)] fn from(variant: BR0_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `BR0`"] pub struct BR0_W<'a> { w: &'a mut W, } impl<'a> BR0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR0_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Port Reset bit"] pub type BR1_AW = BR0_AW; #[doc = "Write proxy for field `BR1`"] pub struct BR1_W<'a> { w: &'a mut W, } impl<'a> BR1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR1_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Port Reset bit"] pub type BR2_AW = BR0_AW; #[doc = "Write proxy for field `BR2`"] pub struct BR2_W<'a> { w: &'a mut W, } impl<'a> BR2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR2_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Port Reset bit"] pub type BR3_AW = BR0_AW; #[doc = "Write proxy for field `BR3`"] pub struct BR3_W<'a> { w: &'a mut W, } impl<'a> BR3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR3_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Port Reset bit"] pub type BR4_AW = BR0_AW; #[doc = "Write proxy for field `BR4`"] pub struct BR4_W<'a> { w: &'a mut W, } impl<'a> BR4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR4_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Port Reset bit"] pub type BR5_AW = BR0_AW; #[doc = "Write proxy for field `BR5`"] pub struct BR5_W<'a> { w: &'a mut W, } impl<'a> BR5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR5_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Port Reset bit"] pub type BR6_AW = BR0_AW; #[doc = "Write proxy for field `BR6`"] pub struct BR6_W<'a> { w: &'a mut W, } impl<'a> BR6_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR6_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Port Reset bit"] pub type BR7_AW = BR0_AW; #[doc = "Write proxy for field `BR7`"] pub struct BR7_W<'a> { w: &'a mut W, } impl<'a> BR7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR7_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Port Reset bit"] pub type BR8_AW = BR0_AW; #[doc = "Write proxy for field `BR8`"] pub struct BR8_W<'a> { w: &'a mut W, } impl<'a> BR8_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR8_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Port Reset bit"] pub type BR9_AW = BR0_AW; #[doc = "Write proxy for field `BR9`"] pub struct BR9_W<'a> { w: &'a mut W, } impl<'a> BR9_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR9_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR0_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR0_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Port Reset bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BR10_AW { #[doc = "0: No action on the corresponding ODx bit"] NOACTION = 0, #[doc = "1: Reset the ODx bit"] RESET = 1, } impl From<BR10_AW> for bool { #[inline(always)] fn from(variant: BR10_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `BR10`"] pub struct BR10_W<'a> { w: &'a mut W, } impl<'a> BR10_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR10_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR10_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR10_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Port Reset bit"] pub type BR11_AW = BR10_AW; #[doc = "Write proxy for field `BR11`"] pub struct BR11_W<'a> { w: &'a mut W, } impl<'a> BR11_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR11_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR10_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR10_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Port Reset bit"] pub type BR12_AW = BR10_AW; #[doc = "Write proxy for field `BR12`"] pub struct BR12_W<'a> { w: &'a mut W, } impl<'a> BR12_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR12_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR10_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR10_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Port Reset bit"] pub type BR13_AW = BR10_AW; #[doc = "Write proxy for field `BR13`"] pub struct BR13_W<'a> { w: &'a mut W, } impl<'a> BR13_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR13_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR10_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR10_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Port Reset bit"] pub type BR14_AW = BR10_AW; #[doc = "Write proxy for field `BR14`"] pub struct BR14_W<'a> { w: &'a mut W, } impl<'a> BR14_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR14_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR10_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR10_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Port Reset bit"] pub type BR15_AW = BR10_AW; #[doc = "Write proxy for field `BR15`"] pub struct BR15_W<'a> { w: &'a mut W, } impl<'a> BR15_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BR15_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action on the corresponding ODx bit"] #[inline(always)] pub fn no_action(self) -> &'a mut W { self.variant(BR10_AW::NOACTION) } #[doc = "Reset the ODx bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(BR10_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } impl W { #[doc = "Bit 0 - Port Reset bit"] #[inline(always)] pub fn br0(&mut self) -> BR0_W { BR0_W { w: self } } #[doc = "Bit 1 - Port Reset bit"] #[inline(always)] pub fn br1(&mut self) -> BR1_W { BR1_W { w: self } } #[doc = "Bit 2 - Port Reset bit"] #[inline(always)] pub fn br2(&mut self) -> BR2_W { BR2_W { w: self } } #[doc = "Bit 3 - Port Reset bit"] #[inline(always)] pub fn br3(&mut self) -> BR3_W { BR3_W { w: self } } #[doc = "Bit 4 - Port Reset bit"] #[inline(always)] pub fn br4(&mut self) -> BR4_W { BR4_W { w: self } } #[doc = "Bit 5 - Port Reset bit"] #[inline(always)] pub fn br5(&mut self) -> BR5_W { BR5_W { w: self } } #[doc = "Bit 6 - Port Reset bit"] #[inline(always)] pub fn br6(&mut self) -> BR6_W { BR6_W { w: self } } #[doc = "Bit 7 - Port Reset bit"] #[inline(always)] pub fn br7(&mut self) -> BR7_W { BR7_W { w: self } } #[doc = "Bit 8 - Port Reset bit"] #[inline(always)] pub fn br8(&mut self) -> BR8_W { BR8_W { w: self } } #[doc = "Bit 9 - Port Reset bit"] #[inline(always)] pub fn br9(&mut self) -> BR9_W { BR9_W { w: self } } #[doc = "Bit 10 - Port Reset bit"] #[inline(always)] pub fn br10(&mut self) -> BR10_W { BR10_W { w: self } } #[doc = "Bit 11 - Port Reset bit"] #[inline(always)] pub fn br11(&mut self) -> BR11_W { BR11_W { w: self } } #[doc = "Bit 12 - Port Reset bit"] #[inline(always)] pub fn br12(&mut self) -> BR12_W { BR12_W { w: self } } #[doc = "Bit 13 - Port Reset bit"] #[inline(always)] pub fn br13(&mut self) -> BR13_W { BR13_W { w: self } } #[doc = "Bit 14 - Port Reset bit"] #[inline(always)] pub fn br14(&mut self) -> BR14_W { BR14_W { w: self } } #[doc = "Bit 15 - Port Reset bit"] #[inline(always)] pub fn br15(&mut self) -> BR15_W { BR15_W { w: self } } }
use byteorder::WriteBytesExt; use naia_shared::{ActorType, Event, EventPacketWriter, EventType, ManagerType, Manifest}; /// Handles writing of Event & Actor data into an outgoing packet pub struct ServerPacketWriter { event_writer: EventPacketWriter, /// bytes representing outgoing Actor messages / updates pub actor_working_bytes: Vec<u8>, /// number of Actor messages to be written pub actor_message_count: u8, } impl ServerPacketWriter { /// Construct a new instance of `PacketReader`, the given `buffer` will be /// used to read information from. pub fn new() -> ServerPacketWriter { ServerPacketWriter { event_writer: EventPacketWriter::new(), actor_working_bytes: Vec::<u8>::new(), actor_message_count: 0, } } /// Returns whether the writer has bytes to write into the outgoing packet pub fn has_bytes(&self) -> bool { return self.event_writer.has_bytes() || self.actor_message_count != 0; } /// Gets the bytes to write into an outgoing packet pub fn get_bytes(&mut self) -> Box<[u8]> { let mut out_bytes = Vec::<u8>::new(); self.event_writer.get_bytes(&mut out_bytes); //Write manager "header" (manager type & actor count) if self.actor_message_count != 0 { out_bytes.write_u8(ManagerType::Actor as u8).unwrap(); // write // manager // type out_bytes.write_u8(self.actor_message_count).unwrap(); // write number of messages out_bytes.append(&mut self.actor_working_bytes); // write event payload self.actor_message_count = 0; } out_bytes.into_boxed_slice() } /// Get the number of bytes which is ready to be written into an outgoing /// packet pub fn bytes_number(&self) -> usize { return self.event_writer.bytes_number() + self.actor_working_bytes.len(); } /// Writes an Event into the Writer's internal buffer, which will eventually /// be put into the outgoing packet pub fn write_event<T: EventType, U: ActorType>( &mut self, manifest: &Manifest<T, U>, event: &Box<dyn Event<T>>, ) -> bool { return self.event_writer.write_event(manifest, event); } }
#[doc = "Reader of register DEN"] pub type R = crate::R<u32, super::DEN>; #[doc = "Writer for register DEN"] pub type W = crate::W<u32, super::DEN>; #[doc = "Register DEN `reset()`'s with value 0"] impl crate::ResetValue for super::DEN { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } impl R {} impl W {}
use ggez::{self, error::GameResult, graphics}; use std::clone::Clone; use std::marker::PhantomData; pub trait Gui { fn update(&mut self, mouse_x: f32, mouse_y: f32) -> GameResult<()>; fn draw(&mut self, ctx: &mut ggez::Context, font: &graphics::Font, mouse_x: f32, mouse_y: f32) -> GameResult<()>; fn mouse_pressed(&mut self, mouse_x: f32, mouse_y: f32); fn mouse_released(&mut self, mouse_x: f32, mouse_y: f32); } pub trait ButtonType<S: GuiState>: Clone { fn perform(&self, state: &mut S); } pub trait GuiState: Clone {} pub struct GuiComponents<S: GuiState, T: ButtonType<S>> { _phantom: PhantomData<S>, buttons: Vec<Button<S, T>>, } impl<S: GuiState, T: ButtonType<S>> GuiComponents<S, T> { pub fn new(buttons: Vec<Button<S, T>>) -> Self { GuiComponents { _phantom: PhantomData, buttons, } } pub fn draw( &self, ctx: &mut ggez::Context, mouse_x: f32, mouse_y: f32, ) -> GameResult<()> { for button in self.buttons.iter() { button.draw(ctx, mouse_x, mouse_y)?; } Ok(()) } pub fn mouse_pressed(&self, state: &mut S, mouse_x: f32, mouse_y: f32) { let button_types: Vec<Box<T>> = self.buttons .iter() .filter(|button| button.is_selected(mouse_x, mouse_y)) .map(|button| button.button_type.clone()) .collect(); for button_type in button_types { button_type.perform(state); } } } pub struct Button<S: GuiState, T: ButtonType<S>> { _phantom: PhantomData<S>, button_type: Box<T>, pub pos: graphics::Point2, pub size: graphics::Point2, icon: Option<graphics::Image>, fill_color: graphics::Color, hover_color: graphics::Color, } impl<S: GuiState, T: ButtonType<S>> Button<S, T> { pub fn new( button_type: T, pos: graphics::Point2, size: graphics::Point2, icon: Option<graphics::Image>, fill_color: graphics::Color, hover_color: graphics::Color, ) -> Self { Button { _phantom: PhantomData, button_type: Box::new(button_type), pos, size, icon, fill_color, hover_color, } } pub fn draw(&self, ctx: &mut ggez::Context, mouse_x: f32, mouse_y: f32) -> GameResult<()> { draw_rectangle( ctx, self.pos, self.size, if self.is_selected(mouse_x, mouse_y) { self.hover_color } else { self.fill_color }, )?; if let Some(icon) = self.icon.as_ref() { draw_texture( ctx, icon, graphics::Point2::new( self.pos.x + (self.size.x - icon.width() as f32) / 2.0, self.pos.y + (self.size.y - icon.height() as f32) / 2.0, ), )?; } Ok(()) } pub fn is_selected(&self, mouse_x: f32, mouse_y: f32) -> bool { mouse_x >= self.pos.x && mouse_y >= self.pos.y && mouse_x < self.pos.x + self.size.x && mouse_y < self.pos.y + self.size.y } } pub fn draw_rectangle( ctx: &mut ggez::Context, pos: graphics::Point2, size: graphics::Point2, color: graphics::Color, ) -> GameResult<()> { graphics::set_color(ctx, color)?; graphics::rectangle( ctx, graphics::DrawMode::Fill, graphics::Rect::new( pos.x * ::GLOBAL_SCALE, pos.y * ::GLOBAL_SCALE, size.x * ::GLOBAL_SCALE, size.y * ::GLOBAL_SCALE, ), )?; graphics::set_color(ctx, graphics::Color::new(1.0, 1.0, 1.0, 1.0))?; Ok(()) } pub fn draw_texture( ctx: &mut ggez::Context, icon: &graphics::Image, pos: graphics::Point2, ) -> GameResult<()> { graphics::draw_ex( ctx, icon, graphics::DrawParam { src: graphics::Rect::one(), dest: graphics::Point2::new(pos.x * ::GLOBAL_SCALE, pos.y * ::GLOBAL_SCALE), rotation: 0.0, scale: graphics::Point2::new(::GLOBAL_SCALE, ::GLOBAL_SCALE), offset: graphics::Point2::new(0.0, 0.0), shear: graphics::Point2::new(0.0, 0.0), color: None, }, ) }
use cipher::{cbc::AES_128_CBC, Cipher}; use std::collections::HashMap; const ZERO_IV: [u8; 16] = *b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; pub struct Server { key: Vec<u8>, } impl Server { pub fn new(key: &[u8]) -> Server { Server { key: key.to_vec() } } pub fn verify(&self, msg: &[u8], iv: &[u8], mac: &[u8]) -> bool { let cbc_cipher = AES_128_CBC::from_iv(&iv); let ct = cbc_cipher.encrypt(&self.key, &msg); let tag = ct.rchunks(16).next().unwrap(); tag == mac } pub fn fixed_iv_verify(&self, msg: &[u8], mac: &[u8]) -> bool { self.verify(&msg, &ZERO_IV, &mac) } } pub struct Client { uid: String, key: Vec<u8>, } impl Client { /// instantiate a new client pub fn new(uid: &str, key: &[u8]) -> Client { Client { uid: uid.to_string(), key: key.to_vec(), } } pub fn sign(&self, msg: &[u8]) -> Option<Vec<u8>> { // query string validaity check is commented out, since tx_list is not standard format // just ignoring the incoming msg's validity for now // let tx = Tx::from_query_str(&msg); // if tx.is_none() { // return None; // } let cbc_cipher = AES_128_CBC::from_iv(&ZERO_IV); let ct = cbc_cipher.encrypt(&self.key, &msg); Some(ct.rchunks(16).next().unwrap().to_vec()) } } #[derive(Debug, PartialEq)] struct Tx { pub from: String, pub to: String, pub amount: u32, } impl Tx { pub fn new(from: &str, to: &str, amount: u32) -> Tx { Tx { from: from.to_string(), to: to.to_string(), amount, } } /// parsing a query string into a Tx if valid pub fn from_query_str(query: &str) -> Option<Tx> { if let Ok(pairs) = serde_urlencoded::from_str::<HashMap<String, String>>(&query) { let from = pairs.get("from"); let to = pairs.get("to"); let amount = pairs.get("amount"); if from == None || to == None || amount == None { None } else { Some(Tx { from: from.unwrap().to_owned(), to: to.unwrap().to_owned(), amount: amount.unwrap().parse().unwrap(), }) } } else { None } } } #[cfg(test)] mod tests { use super::super::random_bytes; use super::*; #[test] fn query_str_parsing() { let query = String::from("from=alice&to=bob&amount=99"); assert_eq!( Tx::from_query_str(&query).unwrap(), Tx::new(&String::from("alice"), &String::from("bob"), 99) ); let q1 = String::from("to=bob&amount=99"); assert_eq!(Tx::from_query_str(&q1), None); } #[test] fn server_verify_correctness() { let msg = b"from=alice&to=bob&amount=99".to_vec(); let key = random_bytes(16); let client = Client::new("alice", &key); let server = Server::new(&key); let mac = client.sign(&msg).unwrap(); assert!(server.verify(&msg, &ZERO_IV, &mac)); } }
pub mod pb { tonic::include_proto!("grpc.examples.echo"); } use futures::Stream; use pb::{EchoRequest, EchoResponse}; use std::pin::Pin; use tonic::{body::BoxBody, transport::Server, Request, Response, Status, Streaming}; use tower::Service; type EchoResult<T> = Result<Response<T>, Status>; type ResponseStream = Pin<Box<dyn Stream<Item = Result<EchoResponse, Status>> + Send + Sync>>; #[derive(Default)] pub struct EchoServer; #[tonic::async_trait] impl pb::echo_server::Echo for EchoServer { async fn unary_echo(&self, request: Request<EchoRequest>) -> EchoResult<EchoResponse> { let message = request.into_inner().message; Ok(Response::new(EchoResponse { message })) } type ServerStreamingEchoStream = ResponseStream; async fn server_streaming_echo( &self, _: Request<EchoRequest>, ) -> EchoResult<Self::ServerStreamingEchoStream> { Err(Status::unimplemented("not implemented")) } async fn client_streaming_echo( &self, _: Request<Streaming<EchoRequest>>, ) -> EchoResult<EchoResponse> { Err(Status::unimplemented("not implemented")) } type BidirectionalStreamingEchoStream = ResponseStream; async fn bidirectional_streaming_echo( &self, _: Request<Streaming<EchoRequest>>, ) -> EchoResult<Self::BidirectionalStreamingEchoStream> { Err(Status::unimplemented("not implemented")) } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let addr = "[::1]:50051".parse().unwrap(); let server = EchoServer::default(); Server::builder() .interceptor_fn(move |svc, req| { let auth_header = req.headers().get("authorization").clone(); let authed = if let Some(auth_header) = auth_header { auth_header == "Bearer some-secret-token" } else { false }; let fut = svc.call(req); async move { if authed { fut.await } else { // Cancel the inner future since we never await it // the IO never gets registered. drop(fut); let res = http::Response::builder() .header("grpc-status", "16") .body(BoxBody::empty()) .unwrap(); Ok(res) } } }) .add_service(pb::echo_server::EchoServer::new(server)) .serve(addr) .await?; Ok(()) }
#[doc = "Reader of register EPINFO"] pub type R = crate::R<u8, super::EPINFO>; #[doc = "Reader of field `TXEP`"] pub type TXEP_R = crate::R<u8, u8>; #[doc = "Reader of field `RXEP`"] pub type RXEP_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:3 - TX Endpoints"] #[inline(always)] pub fn txep(&self) -> TXEP_R { TXEP_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - RX Endpoints"] #[inline(always)] pub fn rxep(&self) -> RXEP_R { RXEP_R::new(((self.bits >> 4) & 0x0f) as u8) } }
use super::{CelestialBody, Node, Vessel}; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteEnum, RemoteObject}; remote_type!( /// Controls the game’s camera. Obtained by calling `SpaceCenter::camera()`. object SpaceCenter.Camera { properties: { { Mode { /// Returns the current mode of the camera. /// /// **Game Scenes**: Flight get: mode -> CameraMode, /// Sets the current mode of the camera. /// /// **Game Scenes**: Flight set: set_mode(CameraMode) } } { Pitch { /// Returns the pitch of the camera, in degrees. /// /// **Game Scenes**: Flight get: pitch -> f32, /// Sets the pitch of the camera, in degrees. A value between /// `Camera::min_pitch()` and `Camera::max_pitch()`. /// /// **Game Scenes**: Flight set: set_pitch(f32) } } { Heading { /// Returns the heading of the camera, in degrees. /// /// **Game Scenes**: Flight get: heading -> f32, /// Sets the heading of the camera, in degrees. /// /// **Game Scenes**: Flight set: set_heading(f32) } } { Distance { /// Returns the distance from the camera to the subject, in meters. /// /// **Game Scenes**: Flight get: distance -> f32, /// Sets the distance from the camera to the subject, in meters. A value between /// `Camera::min_distance()` and `Camera::max_distance()`. /// /// **Game Scenes**: Flight set: set_distance(f32) } } { MinPitch { /// Returns the minimum pitch of the camera. /// /// **Game Scenes**: Flight get: min_pitch -> f32 } } { MaxPitch { /// Returns the maximum pitch of the camera. /// /// **Game Scenes**: Flight get: max_pitch -> f32 } } { MinDistance { /// Returns the minimum distance from the camera to the subject, in meters. /// /// **Game Scenes**: Flight get: min_distance -> f32 } } { MaxDistance { /// Returns the maximum distance from the camera to the subject, in meters. /// /// **Game Scenes**: Flight get: max_distance -> f32 } } { DefaultDistance { /// Returns the default distance from the camera to the subject, in meters. /// /// **Game Scenes**: Flight get: default_distance -> f32 } } { FocussedBody { /// In map mode, returns the celestial body that the camera is focussed on. /// Returns `None` if the camera is not focussed on a celestial body. /// Returns an error if the camera is not in map mode. /// /// **Game Scenes**: Flight get: focussed_body -> Option<CelestialBody>, /// Sets the celestial body that the camera is focussed on. Returns an error if /// the camera is not in map mode. /// /// **Game Scenes**: Flight set: set_focussed_body(&CelestialBody) } } { FocussedVessel { /// In map mode, returns the vessel that the camera is focussed on. /// Returns `None` if the camera is not focussed on a vessel. /// Returns an error if the camera is not in map mode. /// /// **Game Scenes**: Flight get: focussed_vessel -> Option<Vessel>, /// Sets the vessel that the camera is focussed on. Returns an error if /// the camera is not in map mode. /// /// **Game Scenes**: Flight set: set_focussed_vessel(&Vessel) } } { FocussedNode { /// In map mode, returns the maneuver node that the camera is focussed on. /// Returns `None` if the camera is not focussed on a maneuver node. /// Returns an error if the camera is not in map mode. /// /// **Game Scenes**: Flight get: focussed_node -> Option<Node>, /// Sets the maneuver node that the camera is focussed on. Returns an error if /// the camera is not in map mode. /// /// **Game Scenes**: Flight set: set_focussed_node(&Node) } } } }); remote_type!( /// See `Camera::mode()`. enum CameraMode { /// The camera is showing the active vessel, in "auto" mode. Automatic = 0, /// The camera is showing the active vessel, in "free" mode. Free = 1, /// The camera is showing the active vessel, in "chase" mode. Chase = 2, /// The camera is showing the active vessel, in "locked" mode. Locked = 3, /// The camera is showing the active vessel, in "orbital" mode. Orbital = 4, /// The Intra-Vehicular Activity view is being shown. IVA = 5, /// The map view is being shown. Map = 6, } );
// Copyright 2022 Datafuse Labs. // // 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_meta_kvapi::kvapi; use common_meta_kvapi::kvapi::UpsertKVReq; use common_meta_types::KVMeta; use common_meta_types::MetaError; use common_meta_types::SeqV; use common_meta_types::With; use databend_meta::configs::Config; pub enum KvApiCommand { Get(String), Upsert(UpsertKVReq), MGet(Vec<String>), List(String), } impl KvApiCommand { pub fn from_config(config: &Config, op: &str) -> Result<Self, String> { let api = match op { "upsert" => { if config.key.len() != 1 { return Err("The number of keys must be 1".to_string()); } let req = UpsertKVReq::update(config.key[0].as_str(), config.value.as_bytes()); let req = if let Some(expire_after) = config.expire_after { req.with(KVMeta { expire_at: Some(SeqV::<()>::now_ms() / 1000 + expire_after), }) } else { req }; Self::Upsert(req) } "delete" => { if config.key.len() != 1 { return Err("The number of keys must be 1".to_string()); } Self::Upsert(UpsertKVReq::delete(&config.key[0])) } "get" => { if config.key.len() != 1 { return Err("The number of keys must be 1".to_string()); } Self::Get(config.key[0].clone()) } "mget" => Self::MGet(config.key.clone()), "list" => Self::List(config.prefix.clone()), _ => { return Err(format!("Unknown kv api command: {}", op)); } }; Ok(api) } pub async fn execute( &self, client: Arc<dyn kvapi::KVApi<Error = MetaError>>, ) -> anyhow::Result<String> { let res_str = match self { KvApiCommand::Get(key) => { let res = client.get_kv(key.as_str()).await?; serde_json::to_string_pretty(&res)? } KvApiCommand::Upsert(req) => { let res = client.upsert_kv(req.clone()).await?; serde_json::to_string_pretty(&res)? } KvApiCommand::MGet(keys) => { let res = client.mget_kv(keys.as_slice()).await?; serde_json::to_string_pretty(&res)? } KvApiCommand::List(prefix) => { let res = client.prefix_list_kv(prefix.as_str()).await?; serde_json::to_string_pretty(&res)? } }; Ok(res_str) } }
use crate::analysis::{fixed_point, LocationSet}; use crate::il; use crate::Error; use std::collections::HashMap; /// Compute reaching definitions for the given function. pub fn reaching_definitions( function: &il::Function, ) -> Result<HashMap<il::ProgramLocation, LocationSet>, Error> { let rda = ReachingDefinitionsAnalysis { function }; fixed_point::fixed_point_forward(rda, function) } // We require a struct to implement methods for our analysis over. struct ReachingDefinitionsAnalysis<'r> { function: &'r il::Function, } impl<'r> fixed_point::FixedPointAnalysis<'r, LocationSet> for ReachingDefinitionsAnalysis<'r> { fn trans( &self, location: il::RefProgramLocation<'r>, state: Option<LocationSet>, ) -> Result<LocationSet, Error> { let mut state = match state { Some(state) => state, None => LocationSet::new(), }; match *location.function_location() { il::RefFunctionLocation::Instruction(_, instruction) => { instruction .operation() .scalars_written() .into_iter() .for_each(|scalar_written| { let kill: Vec<il::ProgramLocation> = state .locations() .iter() .filter(|location| { location .function_location() .apply(self.function) .unwrap() .instruction() .unwrap() .operation() .scalars_written() .into_iter() .any(|scalar| scalar == scalar_written) }) .cloned() .collect(); kill.iter().for_each(|location| state.remove(location)); state.insert(location.clone().into()); }); } il::RefFunctionLocation::EmptyBlock(_) | il::RefFunctionLocation::Edge(_) => {} } Ok(state) } fn join(&self, mut state0: LocationSet, state1: &LocationSet) -> Result<LocationSet, Error> { state1 .locations() .iter() .for_each(|location| state0.insert(location.clone())); Ok(state0) } } #[test] fn reaching_definitions_test() { /* a = in b = 4 if a < 10 { c = a [0xdeadbeef] = c } else { c = b } b = c c = [0xdeadbeef] */ let mut control_flow_graph = il::ControlFlowGraph::new(); let head_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("a", 32), il::expr_scalar("in", 32)); block.assign(il::scalar("b", 32), il::expr_const(4, 32)); block.index() }; let gt_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("c", 32), il::expr_scalar("b", 32)); block.index() }; let lt_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("c", 32), il::expr_scalar("a", 32)); block.store(il::expr_const(0xdeadbeef, 32), il::expr_scalar("c", 32)); block.index() }; let tail_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("b", 32), il::expr_scalar("c", 32)); block.load(il::scalar("c", 32), il::expr_const(0xdeadbeef, 32)); block.index() }; let condition = il::Expression::cmpltu(il::expr_scalar("a", 32), il::expr_const(10, 32)).unwrap(); control_flow_graph .conditional_edge(head_index, lt_index, condition.clone()) .unwrap(); control_flow_graph .conditional_edge( head_index, gt_index, il::Expression::cmpeq(condition, il::expr_const(0, 1)).unwrap(), ) .unwrap(); control_flow_graph .unconditional_edge(lt_index, tail_index) .unwrap(); control_flow_graph .unconditional_edge(gt_index, tail_index) .unwrap(); control_flow_graph.set_entry(head_index).unwrap(); let function = il::Function::new(0, control_flow_graph); let rd = reaching_definitions(&function).unwrap(); // for r in rd.iter() { // println!("{}", r.0); // for d in r.1 { // println!(" {}", d); // } // } let block = function.control_flow_graph().block(3).unwrap(); let instruction = block.instruction(0).unwrap(); let function_location = il::RefFunctionLocation::Instruction(block, instruction); let program_location = il::RefProgramLocation::new(&function, function_location); let r = &rd[&program_location.into()]; let block = function.control_flow_graph().block(0).unwrap(); assert!(r.contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into() )); let block = function.control_flow_graph().block(1).unwrap(); assert!(r.contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into() )); let block = function.control_flow_graph().block(2).unwrap(); assert!(r.contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into() )); let block = function.control_flow_graph().block(3).unwrap(); assert!(r.contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into() )); let block = function.control_flow_graph().block(0).unwrap(); assert!(!r.contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(1).unwrap()) ) .into() )); }
//! Implementations of OpenAPI `oneOf` and `anyOf` types, assuming rules are just types #[cfg(feature = "conversion")] use frunk_enum_derive::LabelledGenericEnum; use serde::{ de::Error, Deserialize, Deserializer, Serialize, Serializer, __private::de::{Content, ContentRefDeserializer}, }; use std::str::FromStr; use std::string::ToString; // Define a macro to define the common parts between `OneOf` and `AnyOf` enums for a specific // number of inner types. macro_rules! common_one_any_of { ( $schema:ident, $t:ident, $($i:ident),* ) => { #[doc = concat!("`", stringify!($t), "` type.\n\nThis allows modelling of ", stringify!($schema), " JSON schemas.")] #[cfg_attr(feature = "conversion", derive(LabelledGenericEnum))] #[derive(Debug, PartialEq, Clone)] pub enum $t<$($i),*> where $($i: PartialEq,)* { $( #[doc = concat!("`", stringify!($i), "` variant of `", stringify!($t), "`")] $i($i) ),* } impl<$($i),*> Serialize for $t<$($i),*> where $($i: PartialEq + Serialize,)* { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { match self { $(Self::$i(inner) => inner.serialize(serializer)),* } } } impl<$($i),*> ToString for $t<$($i),*> where $($i: PartialEq + ToString,)* { fn to_string(&self) -> String { match self { $(Self::$i(inner) => inner.to_string()),* } } } } } // Define a macro to define the `OneOf` enum for a specific number of inner types. macro_rules! one_of { ( $t:ident, $($i:ident),* ) => { common_one_any_of!(oneOf, $t, $($i),*); impl<'b, $($i),*> Deserialize<'b> for $t<$($i),*> where $($i: PartialEq + for<'a> Deserialize<'a>,)* { fn deserialize<De: Deserializer<'b>>(deserializer: De) -> Result<Self, De::Error> { let content = Content::deserialize(deserializer)?; let mut result = Err(De::Error::custom("data did not match any within oneOf")); $( if let Ok(inner) = $i::deserialize(ContentRefDeserializer::<De::Error>::new(&content)) { if result.is_err() { result = Ok(Self::$i(inner)); } else { return Err(De::Error::custom("data matched multiple within oneOf")) } } )* result } } impl<$($i),*> FromStr for $t<$($i),*> where $($i: PartialEq + FromStr,)* { type Err = &'static str; fn from_str(x: &str) -> Result<Self, Self::Err> { let mut result = Err("data did not match any within oneOf"); $( if let Ok(inner) = $i::from_str(x) { if result.is_err() { result = Ok(Self::$i(inner)); } else { return Err("data matched multiple within oneOf") } } )* result } } } } // Use the `one_of!` macro to define the `OneOf` enum for 1-16 inner types. one_of!(OneOf1, A); one_of!(OneOf2, A, B); one_of!(OneOf3, A, B, C); one_of!(OneOf4, A, B, C, D); one_of!(OneOf5, A, B, C, D, E); one_of!(OneOf6, A, B, C, D, E, F); one_of!(OneOf7, A, B, C, D, E, F, G); one_of!(OneOf8, A, B, C, D, E, F, G, H); one_of!(OneOf9, A, B, C, D, E, F, G, H, I); one_of!(OneOf10, A, B, C, D, E, F, G, H, I, J); one_of!(OneOf11, A, B, C, D, E, F, G, H, I, J, K); one_of!(OneOf12, A, B, C, D, E, F, G, H, I, J, K, L); one_of!(OneOf13, A, B, C, D, E, F, G, H, I, J, K, L, M); one_of!(OneOf14, A, B, C, D, E, F, G, H, I, J, K, L, M, N); one_of!(OneOf15, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O); one_of!(OneOf16, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); // Define a macro to define the `AnyOf` enum for a specific number of inner types. macro_rules! any_of { ( $t:ident, $($i:ident),* ) => { common_one_any_of!(anyOf, $t, $($i),*); impl<'b, $($i),*> Deserialize<'b> for $t<$($i),*> where $($i: PartialEq + for<'a> Deserialize<'a>,)* { fn deserialize<De: Deserializer<'b>>(deserializer: De) -> Result<Self, De::Error> { let content = Content::deserialize(deserializer)?; $( if let Ok(inner) = $i::deserialize(ContentRefDeserializer::<De::Error>::new(&content)) { return Ok(Self::$i(inner)); } )* Err(De::Error::custom("data did not match any within anyOf")) } } impl<$($i),*> FromStr for $t<$($i),*> where $($i: PartialEq + FromStr,)* { type Err = &'static str; fn from_str(x: &str) -> Result<Self, Self::Err> { $( if let Ok(inner) = $i::from_str(x) { return Ok(Self::$i(inner)); } )* Err("data did not match any within anyOf") } } } } // Use the `any_of!` macro to define the `AnyOf` enum for 1-16 inner types. any_of!(AnyOf1, A); any_of!(AnyOf2, A, B); any_of!(AnyOf3, A, B, C); any_of!(AnyOf4, A, B, C, D); any_of!(AnyOf5, A, B, C, D, E); any_of!(AnyOf6, A, B, C, D, E, F); any_of!(AnyOf7, A, B, C, D, E, F, G); any_of!(AnyOf8, A, B, C, D, E, F, G, H); any_of!(AnyOf9, A, B, C, D, E, F, G, H, I); any_of!(AnyOf10, A, B, C, D, E, F, G, H, I, J); any_of!(AnyOf11, A, B, C, D, E, F, G, H, I, J, K); any_of!(AnyOf12, A, B, C, D, E, F, G, H, I, J, K, L); any_of!(AnyOf13, A, B, C, D, E, F, G, H, I, J, K, L, M); any_of!(AnyOf14, A, B, C, D, E, F, G, H, I, J, K, L, M, N); any_of!(AnyOf15, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O); any_of!(AnyOf16, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
static SONG:[&str; 12] = [ "On the PLACEHOLDER day of Christmas my true love sent to me A partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Four calling birds, three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Five gold rings, four calling birds, three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Six geese a laying, five gold rings, four calling birds Three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Seven swans a swimming, six geese a laying, five gold rings Four calling birds, three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Eight maids a milking, seven swans a swimming, six geese a laying Five gold rings, four calling birds, three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Nine drummers drumming", "On the PLACEHOLDER day of Christmas my true love sent to me Ten pipers piping Nine drummers drumming, ten pipers piping Drumming, piping, drumming, piping Eight maids a milking, seven swans a swimming, six geese a laying Five gold rings, four calling birds, three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Eleven ladies dancing, ten pipers piping, nine drummers drumming Eight maids a milking, seven swans a swimming, six geese a laying Five gold rings, four calling birds, three French hens, two turtle doves And a partridge in a pear tree", "On the PLACEHOLDER day of Christmas my true love sent to me Twelve Lords a leaping, eleven ladies dancing, ten pipers piping Nine, drummers drumming, eight maids a milking Seven swans a swimming, six geese a laying And five gold rings, four calling birds, three French hens, two turtle doves And a partridge in a pear tree, and a partridge in a pear tree" ]; fn get_day(day_index: i32) -> &'static str { match day_index { 1 => "first", 2 => "second", 3 => "third", 4 => "forth", 5 => "fifth", 6 => "sixth", 7 => "seventh", 8 => "eighth", 9 => "ninth", 10 => "tenth", 11 => "eleventh", 12 => "twelfth", _ => "X" } } fn main() { println!("============================"); println!("The Twelve Days of Christmas"); println!("============================"); println!(); for i in 0..12 { let day_index = i + 1; let day = get_day(day_index); let turn = SONG[i as usize]; let turn = turn.replace("PLACEHOLDER", day); println!("{}\n", turn); } }
extern crate byteorder; use std::error::Error; use std::fmt; use std::fmt::{Debug, Display, Formatter}; use crate::tftp::shared::ack_packet::AckPacket; use crate::tftp::shared::data_packet::DataPacket; use crate::tftp::shared::err_packet::ErrorPacket; use crate::tftp::shared::request_packet::*; use self::byteorder::{ByteOrder, NetworkEndian}; pub mod ack_packet; pub mod data_channel; pub mod data_packet; pub mod err_packet; pub mod request_packet; const OP_LEN: usize = 2; /// Stride size for reading / writing files. pub const STRIDE_SIZE: usize = 512; /// Op code for Data packet const OP_DATA: u16 = 0x003; /// Op code for Read Request const OP_RRQ: u16 = 0x001; /// Op code for Write Request const OP_WRQ: u16 = 0x002; /// Op code for Error packet const OP_ERR: u16 = 0x005; /// Op code for ACK packet const OP_ACK: u16 = 0x004; #[derive(Debug, Eq, PartialEq)] pub enum TFTPPacket { RRQ(ReadRequestPacket), WRQ(WriteRequestPacket), ACK(AckPacket), ERR(ErrorPacket), DATA(DataPacket), } impl Display for TFTPPacket { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let desc = match self { TFTPPacket::RRQ(p) => format!("RRQ [{}] [{}]", p.filename(), p.mode()), TFTPPacket::WRQ(p) => format!("WRQ [{}] [{}]", p.filename(), p.mode()), TFTPPacket::ACK(p) => format!("ACK [{}]", p.blk()), TFTPPacket::ERR(p) => format!("ERR [{}]: {}", p.code(), p.err()), TFTPPacket::DATA(p) => format!("DATA [{}]", p.blk()), }; write!(f, "{}", desc) } } pub trait Serializable { fn box_serialize(self: Box<Self>) -> Vec<u8>; fn serialize(self) -> Vec<u8>; } pub trait Deserializable { fn deserialize(buf: &[u8]) -> Result<TFTPPacket, TFTPParseError>; } pub fn parse_udp_packet(buf: &[u8]) -> TFTPPacket { let p = match NetworkEndian::read_u16(buf) { OP_RRQ => ReadRequestPacket::deserialize(buf), OP_WRQ => WriteRequestPacket::deserialize(buf), OP_ACK => AckPacket::deserialize(buf), OP_ERR => ErrorPacket::deserialize(buf), OP_DATA => DataPacket::deserialize(buf), val => panic!(format!("Invalid opcode [{}]", val)), }; p.unwrap() } #[derive(Debug, Eq, PartialEq)] pub struct TFTPParseError { details: String, } impl Error for TFTPParseError { fn description(&self) -> &str { &self.details } } impl TFTPParseError { fn new(msg: &str) -> TFTPParseError { TFTPParseError { details: msg.to_string(), } } } impl fmt::Display for TFTPParseError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "Failed to parse packet: {}", self.details) } }
pub fn main() { let mut hello = String::from("안녕하세요"); hello.push_str(" world"); hello.push('!'); println!("{}", hello); for c in hello.chars() { print!("{},", c); } println!(); for b in hello.bytes() { print!("{},", b); } println!(); let s1 = String::from("Hello, "); let s2 = String::from("world!"); // &String is coerced to &str let s3 = s1 + &s2; println!("s2: {}, s3: {}", s2, s3); // println!("{}", s1); // doesn't work let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); // equivalent to creating an empty String and appending let tic_tac_toe = format!("{}-{}-{}", s1, s2, s3); println!("Let's play {}!", tic_tac_toe); }
//! Type wrappers and convenience functions for 2D collision detection pub use collision::algorithm::minkowski::GJK2; pub use collision::primitive::{Circle, ConvexPolygon, Particle2, Rectangle}; pub use core::collide2d::*; pub use core::{CollisionMode, CollisionStrategy}; use cgmath::Point2; use collision::dbvt::{DynamicBoundingVolumeTree, TreeValueWrapped}; use collision::primitive::Primitive2; use collision::Aabb2; use specs::prelude::Entity; use collide::{BasicCollisionSystem, SpatialCollisionSystem, SpatialSortingSystem}; use core::ContactEvent; /// Contact event for 2D /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) pub type ContactEvent2<S> = ContactEvent<Entity, Point2<S>>; /// Basic collision system for 2D, see /// [`BasicCollisionSystem`](../collide/ecs/struct.BasicCollisionSystem.html) for more information. /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform /// - `Y`: Collider type, see `Collider` for more information pub type BasicCollisionSystem2<S, T, Y = ()> = BasicCollisionSystem<Primitive2<S>, T, TreeValueWrapped<Entity, Aabb2<S>>, Aabb2<S>, Y>; /// Spatial sorting system for 2D, see /// [`SpatialSortingSystem`](../collide/ecs/struct.SpatialSortingSystem.html) for more information. /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform /// - `Y`: Collider type, see `Collider` for more information pub type SpatialSortingSystem2<S, T, Y = ()> = SpatialSortingSystem<Primitive2<S>, T, TreeValueWrapped<Entity, Aabb2<S>>, Aabb2<S>, Y>; /// Spatial collision system for 2D, see /// [`SpatialCollisionSystem`](../collide/ecs/struct.SpatialCollisionSystem.html) for more /// information. /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform /// - `Y`: Collider type, see `Collider` for more information pub type SpatialCollisionSystem2<S, T, Y = ()> = SpatialCollisionSystem< Primitive2<S>, T, (usize, TreeValueWrapped<Entity, Aabb2<S>>), Aabb2<S>, Y, >; /// Dynamic bounding volume tree for 2D /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) pub type DynamicBoundingVolumeTree2<S> = DynamicBoundingVolumeTree<TreeValueWrapped<Entity, Aabb2<S>>>;
use crate::ray::Ray; use crate::vec3::{Vec3, Color, random_unit_vector, reflect, refract}; use crate::hittable::{HitRecord}; use rand::prelude::*; #[derive(Copy, Clone)] pub enum Material { Lambertian { albedo: Color }, Metal { albedo: Color, fuzz: f32 }, Dielectric { ref_idx: f32 }, } #[derive(Copy, Clone)] pub struct Lambertian { pub albedo: Color, } impl Lambertian { pub fn lambertian(albedo: &Color) -> Self { Lambertian { albedo: *albedo, } } } #[derive(Copy, Clone)] pub struct Metal { pub albedo: Color, pub fuzz: f32, } impl Metal { pub fn metal(albedo: &Color, f: f32) -> Self { Metal { albedo: *albedo, fuzz: if f < 1.0 { f } else { 1.0 }, } } } #[derive(Copy, Clone)] pub struct Dielectric { ref_idx: f32 } impl Dielectric { pub fn dielectric(ref_idx: f32) -> Self { Dielectric { ref_idx } } } pub fn scatter(material: &Material, r_in: &Ray, rec: &HitRecord, attenuation: &mut Color, scattered: &mut Ray) -> bool { match material { &Material::Lambertian { albedo } => { let scatter_direction = rec.normal + random_unit_vector(); *scattered = Ray::ray(rec.hit_point, scatter_direction); *attenuation = albedo; return true; } &Material::Metal { albedo, fuzz } => { let reflected = reflect(r_in.direction().unit_vector(), rec.normal); *scattered = Ray::ray(rec.hit_point, reflected + random_unit_vector()*fuzz); *attenuation = albedo; return scattered.direction().dot(rec.normal) > 0.0; } &Material::Dielectric { ref_idx } => { *attenuation = Color::new(1.0, 1.0, 1.0); let etai_over_etat = if rec.front_face { 1.0 / ref_idx } else { ref_idx }; let unit_direction = r_in.direction().unit_vector(); let cos_theta = f32::min(Vec3::dot(&-unit_direction, rec.normal), 1.0); let sin_theta = (1.0 - cos_theta*cos_theta).sqrt(); if (etai_over_etat * sin_theta) > 1.0 { let reflected = reflect(unit_direction,rec.normal); *scattered = Ray::ray(rec.hit_point, reflected); return true; } let reflect_prob = schlick(cos_theta, etai_over_etat); let mut rng = rand::thread_rng(); if rng.gen::<f32>() < reflect_prob { let reflected = reflect(unit_direction, rec.normal); *scattered = Ray::ray(rec.hit_point, reflected); return true; } let refracted = refract(unit_direction, rec.normal, etai_over_etat); *scattered = Ray::ray(rec.hit_point, refracted); return true; } } } pub fn schlick(cosine: f32, ref_idx: f32)-> f32 { let mut r0 = (1.0-ref_idx) / (1.0+ref_idx); r0 = r0*r0; r0 + (1.0-r0) * (1.0-cosine).powf(5.0) }
// revisions: full min #![cfg_attr(full, feature(const_generics))] #![feature(const_generics_defaults)] #![allow(incomplete_features)] struct Foo<const N: usize, const M: usize = { N + 1 }>; //[full]~^ ERROR constant expression depends on a generic parameter //[min]~^^ ERROR generic parameters may not be used in const operations struct Bar<T, const TYPE_SIZE: usize = { std::mem::size_of::<T>() }>(T); //[full]~^ ERROR constant expression depends on a generic parameter //[min]~^^ ERROR generic parameters may not be used in const operations fn main() {}
use ethabi::{ParamType, Token}; use hex::ToHex; use bridge_common::prover::{EthAddress, EthEvent, EthEventParams}; /// Data that was emitted by the Ethereum Locked event. #[derive(Debug, Eq, PartialEq)] pub struct TokenMetadataEvent { pub metadata_connector: EthAddress, pub token: String, pub name: String, pub symbol: String, pub decimals: u8, pub timestamp: u64, } impl TokenMetadataEvent { fn event_params() -> EthEventParams { vec![ ("token".to_string(), ParamType::Address, true), ("name".to_string(), ParamType::String, false), ("symbol".to_string(), ParamType::String, false), ("decimals".to_string(), ParamType::Uint(8), false), ("timestamp".to_string(), ParamType::Uint(64), false), ] } /// Parse raw log entry data. pub fn from_log_entry_data(data: &[u8]) -> Self { let event = EthEvent::from_log_entry_data("Log", TokenMetadataEvent::event_params(), data); let token = event.log.params[0].value.clone().to_address().unwrap().0; let token = (&token).encode_hex::<String>(); let name = event.log.params[1].value.clone().to_string().unwrap(); let symbol = event.log.params[2].value.clone().to_string().unwrap(); let decimals = event.log.params[3] .value .clone() .to_uint() .unwrap() .as_usize() as u8; let timestamp = event.log.params[4] .value .clone() .to_uint() .unwrap() .as_usize() as u64; Self { metadata_connector: event.locker_address, token, name, symbol, decimals, timestamp, } } pub fn to_log_entry_data(&self) -> Vec<u8> { EthEvent::to_log_entry_data( "Log", TokenMetadataEvent::event_params(), self.metadata_connector, vec![hex::decode(self.token.clone()).unwrap()], vec![ Token::String(self.name.clone()), Token::String(self.symbol.clone()), Token::Uint(self.decimals.into()), Token::Uint(self.timestamp.into()), ], ) } } impl std::fmt::Display for TokenMetadataEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "token: {}; name: {}; symbol: {}; decimals: {}", self.token, self.name, self.symbol, self.decimals ) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_event_metadata_data() { let event_data = TokenMetadataEvent { metadata_connector: [0u8; 20], token: "6b175474e89094c44da98b954eedeac495271d0f".to_string(), name: "TEST".to_string(), symbol: "TST".to_string(), decimals: 18, timestamp: 13042194, }; let data = event_data.to_log_entry_data(); let result = TokenMetadataEvent::from_log_entry_data(&data); assert_eq!(result, event_data); } }
/* * @lc app=leetcode.cn id=9 lang=rust * * [9] 回文数 * * https://leetcode-cn.com/problems/palindrome-number/description/ * * algorithms * Easy (56.68%) * Likes: 904 * Dislikes: 0 * Total Accepted: 234.8K * Total Submissions: 412.3K * Testcase Example: '121' * * 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 * * 示例 1: * * 输入: 121 * 输出: true * * * 示例 2: * * 输入: -121 * 输出: false * 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 * * * 示例 3: * * 输入: 10 * 输出: false * 解释: 从右向左读, 为 01 。因此它不是一个回文数。 * * * 进阶: * * 你能不将整数转为字符串来解决这个问题吗? * */ // @lc code=start impl Solution { pub fn is_palindrome(x: i32) -> bool { return x == x.signum().abs() * x.abs() .to_string() .chars() .rev() .collect::<String>() .parse::<i32>() .unwrap_or(0); } } // @lc code=end
use super::{InterLink, LinkId}; use rust_src::{a_star_search, dijkstra_search, Cost, Dir, Materials, Path, Point}; use std::collections::HashMap; pub const CHUNK_SIZE: usize = 8; #[derive(Debug)] pub struct Chunk { pub pos: Point, pub links: Vec<LinkId>, } impl Chunk { pub fn new( pos: Point, materials: &Materials, neighbors: [Option<&Chunk>; 4], all_links: &mut HashMap<LinkId, InterLink>, next_id: &mut LinkId, ) -> Chunk { let mut links = vec![]; for dir in 0..4 { let opp_dir = (dir + 2) % 4; if let Some(other) = neighbors[dir] { let opposites = other .links .iter() .filter(|id| all_links[id].sides[opp_dir]) .collect::<Vec<&LinkId>>(); for opposite in opposites { let point = all_links[opposite].pos.get_in_dir(opp_dir.into()).unwrap(); let mut found_corner = false; for corner in links.iter() { if all_links[corner].pos != point { continue; } all_links .get_mut(corner) .unwrap() .add_neighbor(dir, *opposite); all_links .get_mut(opposite) .unwrap() .add_neighbor(opp_dir, *corner); found_corner = true; break; } if found_corner { continue; } let mut link = { let mut sides = [false; 4]; let mut neighbors = [None; 4]; sides[dir] = true; neighbors[dir] = Some(*opposite); let walk_cost = materials[point.x][point.y].walk_cost(); InterLink::new(*next_id, point, walk_cost, sides, neighbors) }; *next_id += 1; link.add_neighbor(dir, *opposite); all_links .get_mut(opposite) .unwrap() .add_neighbor(opp_dir, link.id); links.push(link.id); all_links.insert(link.id, link); } continue; } let next = ((dir + 1) % 4).into(); let point = Point::from(match dir.into() { Dir::UP => (pos.x, pos.y), Dir::RIGHT => (pos.x + CHUNK_SIZE - 1, pos.y), Dir::DOWN => (pos.x + CHUNK_SIZE - 1, pos.y + CHUNK_SIZE - 1), Dir::LEFT => (pos.x, pos.y + CHUNK_SIZE - 1), _ => unreachable!(), }); if point.get_in_dir(dir.into()).is_none() { continue; } let mut entrance = false; let mut entrance_start = 0; let mut entrance_end = 0; for i in 0..CHUNK_SIZE { let current = point.jump_in_dir(next, i).unwrap(); let opposite = current.get_in_dir(dir.into()).unwrap(); let mut finish_entrance = false; if !materials[current.x][current.y].is_solid() && !materials[opposite.x][opposite.y].is_solid() { if !entrance { entrance = true; entrance_start = i; } if i == CHUNK_SIZE - 1 { finish_entrance = true; entrance_end = i + 1; } } else { finish_entrance = true; entrance_end = i; } if finish_entrance && entrance { entrance = false; let points: Vec<(Point, Point)> = (entrance_start..entrance_end) .map(|i| point.jump_in_dir(next, i).unwrap()) .map(|p| (p, p.get_in_dir(dir.into()).unwrap())) .collect(); let entrances = match points.len() { 0 => unreachable!(), 1 => points, 2...4 => { let mut min = points[points.len() / 2]; let mut min_cost = materials[min.0.x][min.0.y].walk_cost() + materials[min.1.x][min.1.y].walk_cost(); for &p in points.iter() { let cost = materials[p.0.x][p.0.y].walk_cost() + materials[p.1.x][p.1.y].walk_cost(); if cost < min_cost { min = p; min_cost = cost; } } vec![min] } _ => { let mut min = points[points.len() / 2]; let mut min_cost = materials[min.0.x][min.0.y].walk_cost() + materials[min.1.x][min.1.y].walk_cost(); for &p in points[2..points.len() - 2].iter() { let cost = materials[p.0.x][p.0.y].walk_cost() + materials[p.1.x][p.1.y].walk_cost(); if cost < min_cost { min = p; min_cost = cost; } } vec![points[0], min, points[points.len() - 1]] } }; for (point, _) in entrances { if let Some(corner) = links.iter().filter(|id| all_links[id].pos == point).next() { all_links.get_mut(corner).unwrap().sides[dir] = true; continue; } let link = { let mut sides = [false; 4]; sides[dir] = true; let walk_cost = materials[point.x][point.y].walk_cost(); InterLink::new(*next_id, point, walk_cost, sides, [None; 4]) }; *next_id += 1; links.push(link.id); all_links.insert(link.id, link); } } } } let my_link_ids: Vec<LinkId> = links.iter().map(|&id| id).collect(); if !my_link_ids.is_empty() { let my_links: Vec<Point> = my_link_ids.iter().map(|id| all_links[id].pos).collect(); for i in 0..(my_link_ids.len() - 1) { let current_id = my_link_ids[i]; let current_pos = my_links[i]; let mut paths = Chunk::dijkstra(current_pos, &my_links[(i + 1)..], pos, materials); for j in (i + 1)..my_link_ids.len() { let other_pos = my_links[j]; if let Some(path) = paths.remove(&other_pos) { let other_id = my_link_ids[j]; let mut other_path = path.clone(); other_path.path.reverse(); other_path.cost += materials[other_pos.x][other_pos.y].walk_cost(); other_path.cost -= materials[current_pos.x][current_pos.y].walk_cost(); all_links .get_mut(&current_id) .unwrap() .edges .insert(other_id, path); all_links .get_mut(&other_id) .unwrap() .edges .insert(current_id, other_path); } } } } Chunk { pos, links } } pub fn dijkstra( start: Point, goals: &[Point], offset: Point, materials: &Materials, ) -> HashMap<Point, Path<Point>> { let left = offset.x; let top = offset.y; let right = left + CHUNK_SIZE; let bottom = top + CHUNK_SIZE; let get_all_neighbors = |p: Point| { p.neighbors() .filter(|o| o.x >= left && o.y >= top && o.x < right && o.y < bottom) }; let get_cost = |p: Point, _: Point| materials[p.x][p.y].walk_cost(); let is_walkable = |p: Point| !materials[p.x][p.y].is_solid(); dijkstra_search(get_all_neighbors, get_cost, is_walkable, start, goals) } pub fn a_star(&self, start: Point, end: Point, materials: &Materials) -> Option<Path<Point>> { let left = self.pos.x; let top = self.pos.y; let right = left + CHUNK_SIZE; let bottom = top + CHUNK_SIZE; let get_all_neighbors = |p: Point| { p.neighbors() .filter(|o| o.x >= left && o.y >= top && o.x < right && o.y < bottom) }; let get_cost = |p: Point, _: Point| materials[p.x][p.y].walk_cost(); let is_walkable = |p: Point| !materials[p.x][p.y].is_solid(); a_star_search(get_all_neighbors, get_cost, is_walkable, start, end, |p| { p.dist(&end) as Cost }) } }
use std::io::{stdin, self, Write}; fn main() { let mut s = String::new(); let mut s2 = String::new(); let mut country = String::new(); let mut country_int: u8 = 0; while country_int != 1 && country_int != 2 { print!("Enter 1 for US or 2 for UK: "); io::stdout().flush().unwrap(); country_int = 0; country.clear(); stdin().read_line(&mut country) .expect("Did not enter a correct string"); match country.trim().parse::<u8>() { Ok(_s) => country_int = country.trim().parse().unwrap(), Err(_err) => println!("Please enter 1 or 2") } } if country_int == 1 { println!("You chose US") } else if country_int == 2 { println!("You chose UK") } else { println!("You chose wrong. Using default, US") } print!("Enter the discount percent: "); io::stdout().flush().unwrap(); loop { s.clear(); stdin().read_line(&mut s) .expect("Did not enter a correct string"); match s.trim().parse::<f64>() { Ok(_s) => break, Err(_err) => println!("Please enter a number") } } println!("Discount percent: {}", s); const ONE_HUNDRED: f64 = 100.; let discount_percent: f64 = s.trim().parse().unwrap(); print!("Enter the original price: "); io::stdout().flush().unwrap(); stdin().read_line(&mut s2) .expect("Did not enter a correct string"); println!("Original price: {}", s2); let original_price: f64 = s2.trim().parse().unwrap(); fn calc_discount(o: f64, d: f64) -> f64 { // calculates the price after applying discount let dollars_off = o * d / ONE_HUNDRED; let price = o - dollars_off; return price; } let price = calc_discount(original_price, discount_percent); if country_int == 2 { println!("Sale price is £{:?}", price) } else { println!("Sale price is ${:?}", price) } let discount_percents = [10., 15., 20., 25., 30., 40., 50., 60., 75.]; println!(""); for i in discount_percents.iter() { print!("If {}% discount,", *i); println!("then sale price is ${:?}", calc_discount(original_price, *i)) } }
#[doc = "Reader of register ADCCTRL"] pub type R = crate::R<u32, super::ADCCTRL>; #[doc = "Writer for register ADCCTRL"] pub type W = crate::W<u32, super::ADCCTRL>; #[doc = "Register ADCCTRL `reset()`'s with value 0"] impl crate::ResetValue for super::ADCCTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "ADC0 Clock Select\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum ADC0CLKSEL_A { #[doc = "0: ADC0 is not clocked"] DISABLED = 0, #[doc = "1: AUXHFRCO is clocking ADC0"] AUXHFRCO = 1, #[doc = "2: HFXO is clocking ADC0"] HFXO = 2, #[doc = "3: HFSRCCLK is clocking ADC0"] HFSRCCLK = 3, } impl From<ADC0CLKSEL_A> for u8 { #[inline(always)] fn from(variant: ADC0CLKSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `ADC0CLKSEL`"] pub type ADC0CLKSEL_R = crate::R<u8, ADC0CLKSEL_A>; impl ADC0CLKSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADC0CLKSEL_A { match self.bits { 0 => ADC0CLKSEL_A::DISABLED, 1 => ADC0CLKSEL_A::AUXHFRCO, 2 => ADC0CLKSEL_A::HFXO, 3 => ADC0CLKSEL_A::HFSRCCLK, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == ADC0CLKSEL_A::DISABLED } #[doc = "Checks if the value of the field is `AUXHFRCO`"] #[inline(always)] pub fn is_auxhfrco(&self) -> bool { *self == ADC0CLKSEL_A::AUXHFRCO } #[doc = "Checks if the value of the field is `HFXO`"] #[inline(always)] pub fn is_hfxo(&self) -> bool { *self == ADC0CLKSEL_A::HFXO } #[doc = "Checks if the value of the field is `HFSRCCLK`"] #[inline(always)] pub fn is_hfsrcclk(&self) -> bool { *self == ADC0CLKSEL_A::HFSRCCLK } } #[doc = "Write proxy for field `ADC0CLKSEL`"] pub struct ADC0CLKSEL_W<'a> { w: &'a mut W, } impl<'a> ADC0CLKSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADC0CLKSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "ADC0 is not clocked"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(ADC0CLKSEL_A::DISABLED) } #[doc = "AUXHFRCO is clocking ADC0"] #[inline(always)] pub fn auxhfrco(self) -> &'a mut W { self.variant(ADC0CLKSEL_A::AUXHFRCO) } #[doc = "HFXO is clocking ADC0"] #[inline(always)] pub fn hfxo(self) -> &'a mut W { self.variant(ADC0CLKSEL_A::HFXO) } #[doc = "HFSRCCLK is clocking ADC0"] #[inline(always)] pub fn hfsrcclk(self) -> &'a mut W { self.variant(ADC0CLKSEL_A::HFSRCCLK) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `ADC0CLKINV`"] pub type ADC0CLKINV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ADC0CLKINV`"] pub struct ADC0CLKINV_W<'a> { w: &'a mut W, } impl<'a> ADC0CLKINV_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } impl R { #[doc = "Bits 4:5 - ADC0 Clock Select"] #[inline(always)] pub fn adc0clksel(&self) -> ADC0CLKSEL_R { ADC0CLKSEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bit 8 - Invert Clock Selected By ADC0CLKSEL"] #[inline(always)] pub fn adc0clkinv(&self) -> ADC0CLKINV_R { ADC0CLKINV_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bits 4:5 - ADC0 Clock Select"] #[inline(always)] pub fn adc0clksel(&mut self) -> ADC0CLKSEL_W { ADC0CLKSEL_W { w: self } } #[doc = "Bit 8 - Invert Clock Selected By ADC0CLKSEL"] #[inline(always)] pub fn adc0clkinv(&mut self) -> ADC0CLKINV_W { ADC0CLKINV_W { w: self } } }
mod actions; mod collections; mod config; mod exts; mod mqtt; mod nlu; mod queries; mod signals; mod skills; mod stt; #[cfg(test)] mod tests; mod tts; mod vars; // Standard library use std::rc::Rc; // This crate use crate::config::Config; use crate::exts::LockIt; use crate::signals::SIG_REG; use crate::skills::load_skills; // Other crates use anyhow::Result; use futures::future::join_all; use lily_common::other::init_log; use lily_common::vars::set_app_name; use unic_langid::LanguageIdentifier; fn get_locale_default() -> String { for (tag, val) in locale_config::Locale::user_default().tags() { if tag.is_none() { return format!("{}", val); } } "".to_string() } #[tokio::main(flavor = "current_thread")] pub async fn main() -> Result<()> { // Set explicit handle for Ctrl-C signal ctrlc::set_handler(move || { std::process::exit(0); }) .expect("Error setting Ctrl-C handler"); set_app_name("lily"); init_log(); // Set config on global let config = Config::load().unwrap_or_default(); crate::config::GLOBAL_CONF.with(|c| c.replace(Rc::new(config.clone()))); // Show config on debug log::debug!("{:?}", config); // let curr_langs: Vec<LanguageIdentifier> = { let as_str = if let Some(ref lang) = config.language { lang.clone() } else { vec![get_locale_default()] }; as_str .into_iter() .filter(|i| !i.is_empty()) .map(|i| { i.parse() .unwrap_or_else(|_| panic!("Locale parsing of \"{}\" failed", &i)) }) .collect() }; let mut loaders = load_skills(&curr_langs)?; let loader_handles = loaders .iter_mut() .map(|loader| loader.run_loader()) .collect::<Vec<_>>(); let loader_handles = join_all(loader_handles); let mut sig_reg_grd = SIG_REG.lock_it(); //TODO!: This can very well be problematic since we access it later too. tokio::select!( _ = sig_reg_grd.call_loops(&config, &curr_langs) => {} _ = loader_handles => {} ); Ok(()) }
#[cfg(test)] mod tests { #[test] fn it_works() { } } use std::fmt; #[derive(Debug, Copy, Clone)] pub enum Token { OpenParen, CloseParen, Var(u32), Abs(u32), Compose } pub fn string_to_tokens<I: IntoIterator<Item=char>>(s: I, names: &mut Vec<String>) -> Vec<Token> { //TODO: make errors recoverable let mut tokens: Vec<Token> = Vec::new(); let mut iter = s.into_iter(); 'outer: while let Some(c) = iter.next() { if c.is_whitespace() { continue; } match c { '(' => tokens.push(Token::OpenParen), ')' => tokens.push(Token::CloseParen), '\\' => { let mut string = String::new(); while let Some(next) = iter.next() { if next.is_whitespace() { if string.len() == 0 { panic!("the backslash must be immediately followed by a variable name") } else { panic!("abstraction parameters must be immediately followed by a dot") } } match next { '(' | ')' | '\\' => { if string.len() == 0 { panic!("the backslash must be immediately followed by a variable name") } else { panic!("abstraction parameters must be immediately followed by a dot") } }, '∀' => panic!("forall not allowed in a parameter name!"), '.' => { if string.len() == 0 { panic!("variable names cannot be empty") } else { tokens.push(Token::Abs(lookup_string(string, names))); continue 'outer } }, _ => { string.push(next) } } } if string.len() == 0 { panic!("the backslash must be immediately followed by a variable name") } else { panic!("abstraction parameters must be immediately followed by a dot") } }, '∀' => { let mut string = String::new(); while let Some(next) = iter.next() { if next.is_whitespace() { if string.len() == 0 { tokens.push(Token::Var(lookup_string(String::from("∀"), names))); continue 'outer } else { panic!("abstraction parameters must be immediately followed by a dot") } } match next { '(' => { if string.len() == 0 { tokens.push(Token::Var(lookup_string(String::from("∀"), names))); tokens.push(Token::OpenParen); continue 'outer } else { panic!("abstraction parameters must be immediately followed by a dot") } }, ')' => { if string.len() == 0 { tokens.push(Token::Var(lookup_string(String::from("∀"), names))); tokens.push(Token::CloseParen); continue 'outer } else { panic!("abstraction parameters must be immediately followed by a dot") } }, '\\' => panic!("backslash not allowed here!"), '∀' => panic!("forall not allowed in a parameter name!"), '.' => { if string.len() == 0 { panic!("variable names cannot be empty") } else { tokens.push(Token::Compose); tokens.push(Token::Var(lookup_string(String::from("∀"), names))); tokens.push(Token::Abs(lookup_string(string, names))); continue 'outer } }, _ => string.push(next) } } tokens.push(Token::Var(lookup_string(string, names))); }, '.' => panic!("dot not allowed here!"), _ => { let mut string: String = c.to_string(); while let Some(next) = iter.next() { if next.is_whitespace() { tokens.push(Token::Var(lookup_string(string, names))); continue 'outer } match next { '(' => { tokens.push(Token::Var(lookup_string(string, names))); tokens.push(Token::OpenParen); continue 'outer }, ')' => { tokens.push(Token::Var(lookup_string(string, names))); tokens.push(Token::CloseParen); continue 'outer }, '\\' => panic!("backslash not allowed here!"), '.' => { if string.len() == 0 { panic!("variable names cannot be empty") } else { tokens.push(Token::Abs(lookup_string(string, names))); continue 'outer } }, '∀' => panic!("variables that contain forall symbols must contain no more than one character"), _ => string.push(next) } } tokens.push(Token::Var(lookup_string(string, names))); } } } tokens } fn lookup_string(s: String, strings: &mut Vec<String>) -> u32 { if let Some(i) = strings.iter().position(|t| *t == s) { i as u32 } else { let size = strings.len() as u32; strings.push(s); size } } const ABSTRACTION_FLAG: u32 = 0b01000000_00000000_00000000_00000000; const APPLICATION_FLAG: u32 = 0b10000000_00000000_00000000_00000000; const MATCH_FLAG: u32 = APPLICATION_FLAG | ABSTRACTION_FLAG; const CLEAR_FLAGS: u32 = !MATCH_FLAG; const CLEAR_APPLICATION_FLAG: u32 = !APPLICATION_FLAG; pub fn parse_str(string: &str, string_table: &mut Vec<String>) -> Vec<u32> { let tokens = string_to_tokens(string.chars(), string_table); parse(&tokens) } pub fn parse<'a, I: IntoIterator<Item=&'a Token>>(t: I) -> Vec<u32> { //TODO: make errors recoverable let mut firsts: Vec<Vec<u32>> = vec![Vec::new()]; let mut seconds: Vec<Vec<u32>> = vec![Vec::new()]; for token in t { match token { &Token::OpenParen => { firsts.push(Vec::new()); seconds.push(Vec::new()); }, &Token::CloseParen => { let mut x = firsts.pop().expect("uh oh 0"); let mut y = seconds.pop().expect("uh oh 1"); let s = seconds.last_mut().expect("uh oh 3"); let slen = s.len(); if slen != 0 { //seconds is not empty s.insert(0, slen as u32 | APPLICATION_FLAG); } s.append(&mut x); s.append(&mut y); }, &Token::Var(x) => { let s = seconds.last_mut().expect("uh oh 5"); let slen = s.len(); if slen != 0 { //seconds is not empty s.insert(0, slen as u32 | APPLICATION_FLAG); } s.push(x); }, &Token::Abs(x) => { let f = firsts.last_mut().expect("uh oh 6"); let s = seconds.last_mut().expect("uh oh 7"); let slen = s.len(); if slen != 0 { //seconds is not empty f.push(slen as u32 | APPLICATION_FLAG); f.append(s); } f.push(x | ABSTRACTION_FLAG); }, &Token::Compose => { let s = seconds.last_mut().expect("uh oh 8"); let slen = s.len(); if slen != 0 { //seconds is not empty let f = firsts.last_mut().expect("uh oh 9"); f.push(slen as u32 | APPLICATION_FLAG); f.append(s); } } } } let mut f: Vec<u32> = firsts.pop().expect("uh oh 10"); if firsts.len() != 0 { panic!("uh oh 11"); } f.append(&mut seconds[0]); f } fn contains(additional_vars: &[u32], lambda: &[u32], start: usize, var: u32) -> bool { if let Some(_) = additional_vars.iter().position(|i| *i == var) { return true; } enum T { Applicand, Argument, Body } let var_as_param = var | ABSTRACTION_FLAG; if var_as_param == var { panic!("invalid variable {}", var); } let mut vec: Vec<T> = Vec::new(); let mut index = start; loop { let next = lambda[index]; match next & MATCH_FLAG { 0 => { //variable if var == next { return true; } loop { if let Some(b) = vec.pop() { if let T::Applicand = b { vec.push(T::Argument); break; } } else { return false; } } }, ABSTRACTION_FLAG => {//abstraction if var_as_param == next { return true; } vec.push(T::Body); }, _ => { //application vec.push(T::Applicand); } } index += 1; } } fn replace_var_unsafe(lambda: &mut [u32], start: usize, var: u32, replacement: u32) { enum T { Applicand, Argument, Body(bool) } let var_as_param = var | ABSTRACTION_FLAG; let mut vec: Vec<T> = Vec::new(); let mut index = start; let mut var_is_bound = false; loop { let next = lambda[index]; match next & MATCH_FLAG { 0 => { //variable if next == replacement { panic!("lambda contains variable {}", replacement); } loop { if let Some(b) = vec.pop() { if let T::Applicand = b { vec.push(T::Argument); break; } } else { if !var_is_bound && next == var { lambda[index] = replacement; } return; } } if var_is_bound { var_is_bound = false; for t in vec.iter() { if let &T::Body(true) = t { var_is_bound = true; break; } } } else if next == var { lambda[index] = replacement; } }, ABSTRACTION_FLAG => { //abstraction let binds_var = next == var_as_param; vec.push(T::Body(binds_var)); var_is_bound |= binds_var; }, _ => { //application vec.push(T::Applicand); } } index += 1; } } pub fn beta_reduce(lambda: &mut Vec<u32>, string_table: &mut Vec<String>, verbose: bool) { let mut count = 0; let mut max_memory = 0; 'outer: loop { for i in 0..lambda.len() { let next = lambda[i]; match next & MATCH_FLAG { 0 => {}, ABSTRACTION_FLAG => {}, _ => { //application let abs_from = i + 1; let param = lambda[abs_from]; if (param & MATCH_FLAG) == ABSTRACTION_FLAG { if verbose { let string_table_copy = string_table.clone(); println!("{}", to_simplified_string(lambda.iter(), |i| &string_table_copy[i as usize])); } let body_from = abs_from + 1; let body_to = abs_from + ((next & CLEAR_APPLICATION_FLAG) as usize); let argument_to = lambda_to(lambda, i); let mut suffix = Vec::from(&lambda[argument_to..]); let replaced = { let body = &lambda[body_from..body_to]; let argument = &lambda[body_to..argument_to]; replace(body, param & CLEAR_FLAGS, argument, string_table) }; lambda.drain(i..); lambda.extend(replaced); lambda.append(&mut suffix); size_applicands(lambda); count += 1; if lambda.len() > max_memory { max_memory = lambda.len(); } continue 'outer; } } } } println!("required {} beta-reductions", count); println!("max memory used for the result of a single beta-reduction step: {} bytes", max_memory * 4); return; } } // pub fn beta_reduce(lambda: &mut Vec<u32>, string_table: &mut Vec<String>) { // loop { // match lambda[0] & MATCH_FLAG { // 0 => { //variable // return // }, // ABSTRACTION_FLAG => { // return // }, // _ => { //application // let mut last_application_size = lambda.len(); // let mut last_application: usize = 0; // let mut applicand_size = (lambda[last_application] & CLEAR_APPLICATION_FLAG) as usize; // let mut next_ind = last_application + 1; // loop { // { // let string_table_copy = string_table.clone(); // println!("{}", to_simplified_string(lambda.iter(), |i| &string_table_copy[i as usize])); // } // let next = lambda[next_ind]; // match next & MATCH_FLAG { // 0 => { // return // }, // ABSTRACTION_FLAG => { // let body_from = next_ind + 1; // let body_to = next_ind + applicand_size; // let argument_to = last_application + last_application_size; // let var = lambda[next_ind] & CLEAR_FLAGS; // let mut suffix = Vec::from(&lambda[argument_to..]); // let replaced = { // let body = &lambda[body_from..body_to]; // let argument = &lambda[body_to..argument_to]; // replace(body, var, argument, string_table) // }; // lambda.drain(last_application..); // lambda.extend(replaced); // lambda.append(&mut suffix); // size_applicands(lambda); // break; // }, // _ => { //application // last_application_size = applicand_size; // last_application = next_ind; // applicand_size = (lambda[last_application] & CLEAR_APPLICATION_FLAG) as usize; // next_ind += 1; // } // } // } // } // } // //1. find first non-application (will be an applicand) // //2. apply applicand to its argument, put back // } // } pub fn replace_strs(lambda: &[u32], var: &str, expression: &str, string_table: &mut Vec<String>) -> Vec<u32> { let expression = parse_str(expression, string_table); replace_str(lambda, var, &expression, string_table) } pub fn replace_str(lambda: &[u32], var: &str, expression: &[u32], string_table: &mut Vec<String>) -> Vec<u32> { let var = lookup_string(String::from(var), string_table); replace(lambda, var, expression, string_table) } fn size_applicands(lambda: &mut [u32]) { for i in 0..lambda.len() { let next = lambda[i]; match next & MATCH_FLAG { 0 => {}, ABSTRACTION_FLAG => {}, _ => { let from = i + 1; let to = lambda_to(lambda, from); let size = to - from; lambda[i] = size as u32 | APPLICATION_FLAG; } } } } fn lambda_to(lambda: &[u32], start: usize) -> usize { enum T { Applicand, Argument, Body } let mut vec: Vec<T> = Vec::new(); let mut index = start; loop { let next = lambda[index]; index += 1; match next & MATCH_FLAG { 0 => { //variable loop { if let Some(b) = vec.pop() { if let T::Applicand = b { vec.push(T::Argument); break; } } else { return index; } } }, ABSTRACTION_FLAG => { //abstraction vec.push(T::Body); }, _ => { //application vec.push(T::Applicand); } } } } pub fn replace(lambda: &[u32], var: u32, expression: &[u32], string_table: &mut Vec<String>) -> Vec<u32> { let free_vars = free_variables(expression, (0..(string_table.len() as u32))); let mut lambda = Vec::from(lambda); prepare_for_replace(var, &free_vars, &mut lambda, string_table); let mut output: Vec<u32> = Vec::new(); enum T { Applicand, Argument, Body(bool) } let var_as_param = var | ABSTRACTION_FLAG; let mut vec: Vec<T> = Vec::new(); let mut index = 0; let mut var_is_bound = false; loop { let next = lambda[index]; match next & MATCH_FLAG { 0 => { //variable loop { if let Some(b) = vec.pop() { if let T::Applicand = b { vec.push(T::Argument); break; } } else { if !var_is_bound && next == var { output.extend(expression.iter()); } else { output.push(next); } size_applicands(&mut output); return output; } } if var_is_bound { var_is_bound = false; for t in vec.iter() { if let &T::Body(true) = t { var_is_bound = true; break; } } output.push(next); } else if next == var { output.extend(expression.iter()); } else { output.push(next); } }, ABSTRACTION_FLAG => { //abstraction let binds_var = next == var_as_param; vec.push(T::Body(binds_var)); var_is_bound |= binds_var; output.push(next); }, _ => { //application vec.push(T::Applicand); output.push(next); } } index += 1; } } fn prepare_for_replace(variable_to_replace: u32, free_vars: &[u32], lambda: &mut [u32], string_table: &mut Vec<String>) { let mut indexes_to_check: Vec<usize> = vec![0]; while let Some(index) = indexes_to_check.pop() { let next = lambda[index]; match next & MATCH_FLAG { 0 => { //variable //do nothing }, ABSTRACTION_FLAG => { //abstraction let var = next & CLEAR_FLAGS; if var == variable_to_replace { //do nothing } else if !is_free(variable_to_replace, lambda, index + 1) { //do nothing } else if let Some(_) = free_vars.iter().position(|i| *i == var) { let next_index = index + 1; let mut new_name = string_table[var as usize].clone(); new_name.push('\''); let mut new_var = lookup_string(new_name, string_table); while contains(free_vars, lambda, next_index, new_var) { new_name = string_table[new_var as usize].clone(); new_name.push('\''); new_var = lookup_string(new_name, string_table); } lambda[index] = new_var | ABSTRACTION_FLAG; replace_var_unsafe(lambda, next_index, var, new_var); indexes_to_check.push(next_index); } else { indexes_to_check.push(index + 1); //do nothing } }, _ => { //application let applicand_index = index + 1; let argument_index = applicand_index + ((next & CLEAR_APPLICATION_FLAG) as usize); if argument_index <= applicand_index { panic!("invalid application"); } indexes_to_check.push(applicand_index); indexes_to_check.push(argument_index); } } } } // pub fn do_something(var: u32, free_vars: &[u32], lambda: &mut [u32]) { // enum T { // Applicand, // Argument, // CheckedBody, // UncheckedBody(usize) // } // let mut vec: Vec<T> = Vec::new(); // for (i, next) in lambda.iter().enumerate() { // match next & MATCH_FLAG { // 0 => { //variable // if next == var { // //1. get all unchecked bodies // //2. if needs change of variables, change variables // //3. replace with checkedbody // for (j, next_token) in vec.iter().enumerate() { // if let T::UncheckedBody(index) = next_token { // let param = lambda[index] & CLEAR_FLAGS; // if free_vars.iter().contains(param) { // let param2 = new_param_that_is_not_contained_inside_abstraction_nor_free_vars; // lambda[index] = param2 | ABSTRACTION_FLAG; // replace_var_unsafe(lambda, index + 1, param, param2); // } // vec[j] = T::CheckedBody; // } // } // } // loop { // if let Some(b) = vec.pop() { // if let T::Applicand = b { // vec.push(T::Argument); // break; // } // } else { // return; // } // } // }, // ABSTRACTION_FLAG => { //abstraction // vec.push(T::UncheckedBody(i)); // }, // _ => { //application // vec.push(T::Applicand); // } // } // } // } pub fn to_canonical_string<'a, S: fmt::Display, F: Fn(u32) -> S, I: IntoIterator<Item=&'a u32>>(lambda: I, string_table: F) -> String { let mut string = String::new(); let mut vec: Vec<bool> = Vec::new(); for next in lambda { match next & MATCH_FLAG { 0 => { //variable string.push_str(&format!("{}", string_table(*next))); loop { if let Some(b) = vec.pop() { if b { vec.push(false); string.push_str(" "); break; } else { string.push_str(")"); } } else { return string; } } }, ABSTRACTION_FLAG => { //abstraction vec.push(false); string.push_str(&format!("(λ{}.", string_table(next & CLEAR_FLAGS))) }, _ => { //application vec.push(true); string.push_str("(") } } } panic!("iterator terminated too early"); } #[derive(Debug)] enum Tok { AppAsBody, AppAsApplicand, AppAsArgument, AbsAsBody, AbsAsApplicand, AbsAsArgument, FinishedApplicand } pub fn to_simplified_string<'a, S: fmt::Display, F: Fn(u32) -> S, I: IntoIterator<Item=&'a u32>>(lambda: I, string_table: F) -> String { let mut iter = lambda.into_iter(); let next = *iter.next().expect("iterator ended too soon"); let (mut vec, mut string) = match next & MATCH_FLAG { 0 => return format!("{}", string_table(next)), ABSTRACTION_FLAG => (vec![Tok::AbsAsBody], format!("λ{}.", string_table(next & CLEAR_FLAGS))), _ => (vec![Tok::AppAsBody], String::new()) }; loop { let next = *iter.next().expect(&format!("iterator ended too soon; stopped with {}", string)); let tok = vec.pop().expect("uh oh"); match next & MATCH_FLAG { 0 => { if let Tok::FinishedApplicand = tok { string.push_str(" "); } string.push_str(&format!("{}", string_table(next))); match tok { Tok::FinishedApplicand | Tok::AbsAsBody | Tok::AbsAsArgument => { if let Tok::AbsAsArgument = tok { string.push_str(")"); } loop { if let Some(tok) = vec.pop() { match tok { Tok::AppAsArgument | Tok::AbsAsArgument => string.push_str(")"), Tok::AppAsBody | Tok::AbsAsBody => (), Tok::AppAsApplicand => { vec.push(Tok::FinishedApplicand); break }, Tok::AbsAsApplicand => { vec.push(Tok::FinishedApplicand); string.push_str(")"); break }, Tok::FinishedApplicand => panic!("weird") } } else { // string = string.replace("λf.(λx.f (x x)) (λx.f (x x))", "Y"); // string = string.replace("(Y)", "Y"); // string = string.replace("λn.λf.λx.f (n f x)", "S"); // string = string.replace("(S)", "S"); // string = string.replace("λf.λx.x", "0"); // string = string.replace("(0)", "0"); // string = string.replace("λT.λF.F", "false"); // string = string.replace("(false)", "false"); // string = string.replace("λT.λF.T", "true"); // string = string.replace("(true)", "true"); // string = string.replace("λn.n (λx.false) true", "is_zero"); // string = string.replace("(is_zero)", "is_zero"); // string = string.replace("λn.n (λg.λk.is_zero (g (S 0)) k ((λn.λm.n S m) (g k) (S 0))) (λv.0) 0", "P"); // string = string.replace("(P)", "P"); // string = string.replace("λr.λn.is_zero n 0 (S (r r (P n)))", "G"); // string = string.replace("(G)", "G"); return string; } } }, Tok::AbsAsApplicand => { string.push_str(")"); vec.push(Tok::FinishedApplicand); }, Tok::AppAsBody | Tok::AppAsApplicand | Tok::AppAsArgument => { vec.push(tok); vec.push(Tok::FinishedApplicand); } } }, ABSTRACTION_FLAG => { match tok { Tok::FinishedApplicand => { string.push_str(&format!(" (λ{}.", string_table(next & CLEAR_FLAGS))); vec.push(Tok::AbsAsArgument); }, Tok::AppAsBody | Tok::AppAsApplicand => { string.push_str(&format!("(λ{}.", string_table(next & CLEAR_FLAGS))); vec.push(tok); vec.push(Tok::AbsAsApplicand); }, Tok::AppAsArgument => { string.push_str(&format!("(λ{}.", string_table(next & CLEAR_FLAGS))); vec.push(tok); vec.push(Tok::AbsAsApplicand); }, Tok::AbsAsArgument | Tok::AbsAsApplicand | Tok::AbsAsBody => { string.push_str(&format!("λ{}.", string_table(next & CLEAR_FLAGS))); vec.push(tok); vec.push(Tok::AbsAsBody); } } }, _ => { match tok { Tok::AbsAsArgument | Tok::AbsAsApplicand | Tok::AbsAsBody => { vec.push(tok); vec.push(Tok::AppAsBody); }, Tok::AppAsArgument | Tok::AppAsBody | Tok::AppAsApplicand => { vec.push(tok); vec.push(Tok::AppAsApplicand); }, Tok::FinishedApplicand => { string.push_str(" ("); vec.push(Tok::AppAsArgument); } } } } } } pub fn is_free(var: u32, lambda: &[u32], start: usize) -> bool { let mut indexes_to_check: Vec<usize> = vec![start]; let param = var | ABSTRACTION_FLAG; if param == var { panic!("invalid variable {}", var); } while let Some(next_ind) = indexes_to_check.pop() { let next = lambda[next_ind]; match next & MATCH_FLAG { 0 => { //variable if next == var { return true; } }, ABSTRACTION_FLAG => { //abstraction if next != param { indexes_to_check.push(next_ind + 1); } }, _ => { //application let applicand_index = next_ind + 1; let argument_index = applicand_index + ((next & CLEAR_APPLICATION_FLAG) as usize); if argument_index <= applicand_index { panic!("invalid application"); } indexes_to_check.push(applicand_index); indexes_to_check.push(argument_index); } } } false } pub fn free_variables<I: Iterator<Item=u32>> (lambda: &[u32], variables: I) -> Vec<u32> { let mut fvs: Vec<u32> = Vec::new(); for var in variables { if is_free(var, lambda, 0) { fvs.push(var); } } fvs } pub fn to_hex_string(src: &[u32]) -> String { let mut src: Vec<u32> = src.iter().map(|i| i.to_be()).collect(); let src: &mut [u32] = &mut src; let bytes: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u8, src.len() * 4) }; let mut string = String::new(); for byte in bytes { let mut format = format!("{:x}", byte); if format.len() == 1 { format.insert(0, '0'); } string.push_str(&format); } string } pub fn print_info(lambda: &str) { let mut string_table: Vec<String> = Vec::new(); let tokens: Vec<Token> = string_to_tokens(lambda.chars(), &mut string_table); let bytecode: Vec<u32> = parse(&tokens); println!(""); println!("input string: {}", lambda); println!("syntax tokens: {:?}", tokens); println!("string table: {:?}", string_table); println!("hex output: {}", u32s_to_hex(&bytecode)); println!("canonical output: {}", to_canonical_string(&bytecode, |i| &string_table[i as usize])); println!("simplified output: {}", to_simplified_string(&bytecode, |i| &string_table[i as usize])); let r = replace_strs(&bytecode, "x", "j", &mut string_table); println!("[x := j] {}", to_simplified_string(&r, |i| &string_table[i as usize])); let r = replace_strs(&bytecode, "y", "x", &mut string_table); println!("[y := x] {}", to_simplified_string(&r, |i| &string_table[i as usize])); let r = replace_strs(&bytecode, "x", "b e d", &mut string_table); println!("[x := b e d] {}", to_simplified_string(&r, |i| &string_table[i as usize])); println!(""); } pub fn run(program: &str) { let mut string_table: Vec<String> = Vec::new(); println!("\n\nparsing program...\n"); println!("simplified program string: "); let mut program = parse_str(program, &mut string_table); println!("{}", to_simplified_string(&program, |i| &string_table[i as usize])); println!("\n\nbeta-reducing program...\n"); beta_reduce(&mut program, &mut string_table, false); println!("beta-reduced program output:\n"); println!("{}\n\n", to_simplified_string(&program, |i| &string_table[i as usize])); } pub fn run_verbose(program: &str) { let mut string_table: Vec<String> = Vec::new(); println!("\n\nparsing program...\n"); println!("simplified program string: "); let mut program = parse_str(program, &mut string_table); println!("{}", to_simplified_string(&program, |i| &string_table[i as usize])); println!("\n\nbeta-reducing program...\n"); println!("beta-reduction steps:\n"); beta_reduce(&mut program, &mut string_table, true); println!("{}\n\n", to_simplified_string(&program, |i| &string_table[i as usize])); } /////////////////////////////////////////////////////////////////////// //DEPRECATED RECURSIVE STRUCTURES /////////////////////////////////////////////////////////////////////// pub enum Expression { App(Box<Application>), Abs(Box<Abstraction>), Var(Variable) //todo: change to Var(usize) } pub struct Abstraction { pub param: Variable, pub body: Expression } pub struct Application { pub applicand: Expression, pub argument: Expression } pub struct Variable { name: String } pub trait Expressive { fn expression(self) -> Expression; } impl Expressive for Expression { fn expression(self) -> Expression { self } } impl Expressive for Abstraction { fn expression(self) -> Expression { Expression::Abs(Box::new(self)) } } impl Expressive for Application { fn expression(self) -> Expression { Expression::App(Box::new(self)) } } impl Expressive for Variable { fn expression(self) -> Expression { Expression::Var(self) } } pub fn var(name: String) -> Variable { Variable::new(name) } impl Abstraction { pub fn new<E: Expressive>(param: Variable, body: E) -> Abstraction { Abstraction { param, body: body.expression() } } } impl Application { pub fn new<E: Expressive, F: Expressive>(applicand: E, argument: F) -> Application { return Application { applicand: applicand.expression(), argument: argument.expression() } } } impl Variable { pub fn new(name: String) -> Variable { Variable { name } } } impl fmt::Display for Expression { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Expression::App(ref x) => x.fmt(f), &Expression::Abs(ref x) => x.fmt(f), &Expression::Var(ref x) => x.fmt(f) } } } impl fmt::Display for Abstraction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.body { Expression::Abs(ref x) => write!(f, "λ{}.{}", self.param, x), Expression::App(ref x) => write!(f, "λ{}. {}", self.param, x), Expression::Var(ref x) => write!(f, "λ{}. {}", self.param, x) } } } impl fmt::Display for Application { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.applicand { Expression::Abs(ref x) => match self.argument { Expression::Abs(ref y) => write!(f, "({}) ({})", x, y), Expression::App(ref y) => write!(f, "({}) ({})", x, y), Expression::Var(ref y) => write!(f, "({}) {}", x, y) }, Expression::App(ref x) => match self.argument { Expression::Abs(ref y) => write!(f, "{} ({})", x, y), Expression::App(ref y) => write!(f, "{} ({})", x, y), Expression::Var(ref y) => write!(f, "{} {}", x, y) }, Expression::Var(ref x) => match self.argument { Expression::Abs(ref y) => write!(f, "{} ({})", x, y), Expression::App(ref y) => write!(f, "{} ({})", x, y), Expression::Var(ref y) => write!(f, "{} {}", x, y) } } } } impl fmt::Display for Variable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.name) //write!(f, "{}", self.name) } } pub fn u32_to_hex(u: &u32) -> String { let mut f = format!("{:x}", u); while f.len() < 8 { f.insert(0, '0'); } f } pub fn u32s_to_hex(u: &[u32]) -> String { let v: Vec<String> = u.iter().map(|i| u32_to_hex(i)).collect(); v.join(" ") } //TODO: parser takes in (1) regular expression matching lambda symbol, //and (2) a string matching lambda symbols that actually become applicands //whose argument is the abstraction. //1st case: \x.y -> Abstraction(x, y) //2nd case: ∀x.y -> Application(∀, Abstraction(x, y)) //Should we get rid of the recursive parsing? Could cause a stack overflow if too big. //TODO: variable should just store an int; (expression changes meaning in context of list of variable names) //that would take up less space
use data::avatar::Avatar; use std::rc::Rc; use std::cell::RefCell; use rustc_serialize::json::{ToJson, Json}; pub struct User { pub id: u64, name: String, avatar: Option<Rc<RefCell<Avatar>>> } impl User { pub fn new(name: &str) -> User{ User{id: 0, name: name.to_string(), avatar: Option::None} } pub fn _new_with_avatar(name: & str, avatar: Rc<RefCell<Avatar>>) -> User{ User{id: 0, name: name.to_string(), avatar: Option::Some(avatar)} } pub fn from_json(data: &Json)->User{ let mut id =0u64; let mut name="".to_string(); let mut avatar: Option<Rc<RefCell<Avatar>>>=None; match data.as_object(){ Some(obj) =>{ match obj.get("id") { Some(&Json::U64(v)) => {id=v; ()}, _=>() }; match obj.get("name") { Some(v) => match v.clone(){ Json::String(v)=>{name=v; ()}, _ => () }, _=>() }; match obj.get("avatar") { Some(v) => {avatar=Some(Rc::new(RefCell::new(Avatar::from_json(v)))); ()}, _=>() }; }, None =>() }; User{id: id, name: name, avatar: avatar} } pub fn get_name(&self) -> & str{ &self.name } pub fn set_name(&mut self, name: String){ self.name=name; } pub fn set_avatar(&mut self, avatar: Rc<RefCell<Avatar>>){ self.avatar=Some(avatar); } pub fn get_avatar(&self) -> Option<Rc<RefCell<Avatar>>>{ match self.avatar.clone() { Some(avatar) => Some(avatar), None => None } } pub fn to_json(&self) -> Json { match self.avatar.clone(){ Some(avatar) => match avatar.borrow().to_json(){ Json::String(avatar_value)=>Json::String(format!("{{\"id\": {}, \"name\": \"{}\", \"avatar\": {}}}", self.id, self.name, avatar_value)), _ => Json::String(format!("{{\"id\": {}, \"name\": \"{}\"}}", self.id, self.name)) }, _ => Json::String(format!("{{\"id\": {}, \"name\": \"{}\"}}", self.id, self.name)) } } } impl ToJson for User { fn to_json(&self) -> Json { self.to_json() } }
use std::{ path::PathBuf, fmt::{self, Formatter, Display}, fs::{self, File}, collections::{hash_map, HashMap}, io::{self, Read, Seek, SeekFrom, BufReader, BufWriter}, time }; use structopt::StructOpt; use rand::{ prelude::*, distributions::Alphanumeric }; use serde::{Serializer, ser::SerializeSeq}; use either::Either; use failure::{self, format_err, bail, Fallible}; use log::{warn, debug}; use fsoperation::{FSOperation, SeekMode, SeekPos, NUM_FS_OPERATIONS}; #[derive(Debug, StructOpt)] struct GrindArguments { #[structopt(short = "l", long, parse(from_os_str))] /// Specifies the path the log file shall be written to. If not specified, output to stdout. log_output: Option<PathBuf>, #[structopt(parse(from_os_str))] /// Path to the file system that shall be assessed. test_path: PathBuf, #[structopt(parse(from_os_str))] /// Path that shall serve as the reference file system (i.e. a mature file system that can /// be trusted). reference_path: PathBuf, #[structopt(short = "t", long, required_unless = "rounds")] /// Time in seconds the grinding shall be executed. /// /// At least one of 'timeout' or 'rounds' must be specified. timeout: Option<usize>, #[structopt(short = "r", long, required_unless = "timeout")] /// Number of operations the grinding shall execute. /// /// At least one of 'timeout' or 'rounds' must be specified. rounds: Option<usize>, #[structopt(long)] /// Maximum number of open files at the same time. /// /// If this number is reached, no additional files will be opened. If files are closed /// again, opening will also be resumed until the maximum number is reached again. max_open_files: Option<usize>, #[structopt(long)] /// Maximum number of files that are to be created during the grind oepration. /// /// If this number is reached, no new files will be created for the duration of the /// assessment. max_created_files: Option<usize>, #[structopt(long, default_value = "1024")] /// Maximum size of one write. /// /// fsgrinder will randomly write between 1 and max_write_size bytes per write operation. max_write_size: usize, } #[derive(Debug, StructOpt)] #[structopt(name = "fsgrinder")] /// Randomly executes file system operations on two paths and compares whether the files and /// content are the same. /// /// At certain points during the execution (e.g. when reading from files), the file systems are /// checked for consistency. If they're inconsistent, the evaluation ends and it's possible to /// investigate both trees for reasons for the inconsistency. /// /// The tool supports random grinding as well as reprocessing a recorded log from previous random /// grinds. See the subcommand documentation for further details. enum Arguments { /// Randomly execute commands from a set of supported file operations on two file systems. /// /// The log can optionally be recorded to act as an input for later replay runs. Grind(GrindArguments), /// Replay a previously recorded (or hand crafted) file system action log. /// /// Replay ends when the first inconsistency or operation failure is detected. Replay { #[structopt(parse(from_os_str))] /// Log to replay on the given file systems. log_path: PathBuf, #[structopt(parse(from_os_str))] /// Path to the file system that shall be assessed. test_path: PathBuf, #[structopt(parse(from_os_str))] /// Path that shall serve as the reference file system (i.e. a mature file system that can /// be trusted). reference_path: PathBuf } } enum GrindDurationKeeper { Timeout { start: time::Instant, timeout: time::Duration }, Rounds { elapsed: usize, max: usize } } impl GrindDurationKeeper { fn with_rounds(rounds: usize) -> Self { GrindDurationKeeper::Rounds { max: rounds, elapsed: 0 } } fn with_timeout(timeout: usize) -> Self { GrindDurationKeeper::Timeout { start: time::Instant::now(), timeout: time::Duration::from_secs(timeout as u64) } } fn elapsed(&mut self) -> bool { match self { GrindDurationKeeper::Timeout { timeout, start } => time::Instant::now() - *start > *timeout, GrindDurationKeeper::Rounds { elapsed, max } => { *elapsed += 1; max < elapsed } } } } struct RandomReader<R: Rng>(R); impl<R: Rng> Read for RandomReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.fill_bytes(buf); Ok(buf.len()) } } #[derive(Debug, Clone)] struct FileDescriptor { path: PathBuf } #[derive(Debug, Clone)] struct OpenFileDescriptor { file_desc: FileDescriptor } struct RandFSOpGenerator<R: Rng> { rng: R, max_open_files: Option<usize>, max_created_files: Option<usize>, open_files: Vec<OpenFileDescriptor>, existing_files: Vec<FileDescriptor>, max_write_size: usize, } trait RemoveRandomEntry { type Item; fn remove_random<R: Rng>(&mut self, rng: &mut R) -> Option<Self::Item>; } impl<T> RemoveRandomEntry for Vec<T> { type Item = T; fn remove_random<R: Rng>(&mut self, rng: &mut R) -> Option<Self::Item> { if self.len() > 0 { let random_index = rng.gen_range(0, self.len()); Some(self.remove(random_index)) } else { None } } } impl<R: Rng> Iterator for RandFSOpGenerator<R> { type Item = FSOperation; fn next(&mut self) -> Option<Self::Item> { let operation = loop { let operation_index = self.rng.gen_range(0, NUM_FS_OPERATIONS); match operation_index { 0 => if let Some(OpenFileDescriptor { file_desc: closed_file }) = self.open_files.remove_random(&mut self.rng) { let result = FSOperation::CloseFile { file_path: closed_file.path.clone() }; self.existing_files.push(closed_file); break result; }, 1 => if !self.max_created_files_reached() { let name_len = self.rng.gen_range(6, 32); let name = (&mut self.rng).sample_iter(Alphanumeric).take(name_len).collect::<String>(); let path = PathBuf::from(name); self.open_files.push(OpenFileDescriptor { file_desc: FileDescriptor { path: path.clone(), } }); break FSOperation::CreateFile { file_path: path }; }, 2 => if !self.max_open_files_reached() { if let Some(open_file) = self.existing_files.remove_random(&mut self.rng) { let result = FSOperation::OpenFile { file_path: open_file.path.clone() }; self.open_files.push(OpenFileDescriptor { file_desc: open_file }); break result; } }, 3 => if let Some(file) = self.open_files.choose_mut(&mut self.rng) { let seek_mode = match self.rng.gen_range(0, 3) { 0 => SeekMode::Start, 1 => SeekMode::Current, 2 => SeekMode::End, _ => unreachable!() }; let rel_seek_pos = self.rng.gen_range(0u32, 2 * 1048576) as f32 / 1048576.0; break FSOperation::SeekOpenFile { file_path: file.file_desc.path.clone(), seek_pos: SeekPos { seek_mode, rel_seek_pos } }; }, 4 => if let Some(file) = self.open_files.choose_mut(&mut self.rng) { let written_size = self.rng.gen_range(1, self.max_write_size) as u64; break FSOperation::WriteRandomData { file_path: file.file_desc.path.clone(), written_size, }; }, 5 => if let Some(file) = self.open_files.choose_mut(&mut self.rng) { let read_size = self.rng.gen_range(1, 2048); break FSOperation::ReadData { read_size, file_path: file.file_desc.path.clone() }; } _ => panic!("NUM_FS_OPERATIONS larger than number of FSOperarion variants") } }; Some(operation) } } impl<R: Rng> RandFSOpGenerator<R> { fn new(rng: R, max_write_size: usize, max_open_files: Option<usize>, max_created_files: Option<usize>) -> Self { Self { rng, max_open_files, max_created_files, max_write_size, open_files: Default::default(), existing_files: Default::default() } } fn max_open_files_reached(&self) -> bool { self.max_open_files .map(|of| self.open_files.len() >= of) .unwrap_or(false) } fn max_created_files_reached(&self) -> bool { self.max_created_files .map(|cf| { debug!("open_files.len: {}, existing_files.len: {}", self.open_files.len(), self.existing_files.len()); self.open_files.len() + self.existing_files.len() >= cf }) .unwrap_or(false) } } #[derive(Debug, PartialEq, Eq)] enum FSOperationResult { Done, Position(u64), Data(Vec<u8>) } impl Display for FSOperationResult { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { FSOperationResult::Done => write!(f, "Finished without result data"), FSOperationResult::Data(data) => write!(f, "Finished with {} bytes of raw data", data.len()), FSOperationResult::Position(pos) => write!(f, "Finished at position {}", pos), } } } trait FSOperationExecutor { type Error: Display; fn execute_fs_operation(&mut self, operation: FSOperation) -> Result<FSOperationResult, Self::Error>; } struct FSOperationComparator<R, A> { reference_fs: R, assessed_fs: A } impl<R, A> FSOperationComparator<R, A> { fn new(reference_fs: R, assessed_fs: A) -> Self { Self { reference_fs, assessed_fs } } } impl<R, A> FSOperationExecutor for FSOperationComparator<R, A> where A: FSOperationExecutor, R: FSOperationExecutor, R::Error: From<A::Error>+From<failure::Error> { type Error = R::Error; fn execute_fs_operation(&mut self, operation: FSOperation) -> Result<FSOperationResult, Self::Error> { self.reference_fs.execute_fs_operation(operation.clone()) .and_then(|reference_result| { let assessed_result = self.assessed_fs.execute_fs_operation(operation); if let Ok(ref assessed_op_result) = assessed_result { if *assessed_op_result != reference_result { return Err(format_err!( r"Reference FS has different behavior than assessed FS. Result of reference FS ====================== {} Result of assessed FS ===================== {}", &reference_result, assessed_op_result).into()); } } assessed_result.map_err(Into::into) }) } } struct GrinderFile { file: File, } struct FSGrinder<R> { base_path: PathBuf, open_files: HashMap<PathBuf, GrinderFile>, rng: R } impl<R: Rng> FSOperationExecutor for FSGrinder<R> { type Error = failure::Error; fn execute_fs_operation(&mut self, operation: FSOperation) -> Fallible<FSOperationResult> { match operation { FSOperation::SeekOpenFile { seek_pos, ref file_path } => { let file = self.open_files.get_mut(file_path) .ok_or(format_err!("Unable to find open file {}", file_path.display()))?; let file_pos = file.file.seek(SeekFrom::Current(0)).unwrap() as u64; let file_size = file.file.seek(SeekFrom::End(0)).unwrap() as u64; // restore previous position file.file.seek(SeekFrom::Start(file_pos)).unwrap(); let seek_from = seek_pos.into_seek_from(file_pos, file_size); debug!("Converted seek_pos for {} from {}/{}: {:?}", file_path.display(), file_pos, file_size, &seek_from); file.file.seek(seek_from).unwrap(); let new_file_pos = file.file.seek(SeekFrom::Current(0)).unwrap() as u64; Ok(FSOperationResult::Position(new_file_pos)) } FSOperation::CloseFile { ref file_path } => self.open_files.remove(file_path) .ok_or(format_err!("File {} wasn't open", file_path.display())) .map(|_| FSOperationResult::Done), FSOperation::CreateFile { file_path } => self.open_file(file_path, true), FSOperation::OpenFile { file_path } => self.open_file(file_path, false), FSOperation::WriteRandomData { ref file_path, written_size } => { let file = self.open_files.get_mut(file_path).ok_or( format_err!("Unable to find open file {} for writing", file_path.display()))?; let mut reader = RandomReader(&mut self.rng).take(written_size); io::copy(&mut reader, &mut file.file) .map(|_| FSOperationResult::Done) .map_err(|e| format_err!("Failed to write {} bytes to {}: {}", written_size, file_path.display(), e)) } FSOperation::ReadData { read_size, ref file_path } => { let file = self.open_files.get_mut(file_path).ok_or( format_err!("Unable to find open finle {} for reading", file_path.display()))?; let file_pos = file.file.seek(SeekFrom::Current(0)).unwrap(); let file_size = file.file.seek(SeekFrom::End(0)).unwrap(); // restore previous position file.file.seek(SeekFrom::Start(file_pos)).unwrap(); let data_size = if file_size > file_pos { read_size.min(file_size - file_pos) as usize } else { 0usize }; debug!("Read {} bytes from {} at {}/{}", data_size, file_path.display(), file_pos, file_size); let mut data = Vec::with_capacity(read_size as usize); data.resize(data_size, 0); file.file.read_exact(data.as_mut()) .map(move |_| FSOperationResult::Data(data)) .map_err(|e| format_err!("Unable to read {} bytes from {}: {}", read_size, file_path.display(), e)) } } } } impl<R: Rng> FSGrinder<R> { fn new<P: Into<PathBuf>>(base_path: P, rng: R) -> Self { Self { open_files: HashMap::new(), rng, base_path: base_path.into() } } fn open_file(&mut self, file_path: PathBuf, create: bool) -> Fallible<FSOperationResult> { fs::OpenOptions::new() .read(true) .write(true) .create(create) .open(self.base_path.join(&file_path)) .map_err(failure::Error::from) .and_then(|file| match self.open_files.entry(file_path) { hash_map::Entry::Vacant(entry) => { let file = GrinderFile { file }; entry.insert(file); Ok(FSOperationResult::Done) } hash_map::Entry::Occupied(entry) => bail!("File {} already opened", entry.key().display()) }) } } struct FSOperationSerializer<S, F> where S: SerializeSeq { ser: Option<S>, inner: F } impl<S, F> FSOperationSerializer<S, F> where S: SerializeSeq, F: FSOperationExecutor, F::Error: From<S::Error> { fn new<Ser>(ser: Ser, executor: F) -> Result<Self, Ser::Error> where Ser: Serializer<SerializeSeq=S, Ok=S::Ok, Error=S::Error> { ser.serialize_seq(None) .map(move |ser| Self { ser: Some(ser), inner: executor }) } } impl<S, F> FSOperationExecutor for FSOperationSerializer<S, F> where S: SerializeSeq, F: FSOperationExecutor, F::Error: From<S::Error> { type Error = F::Error; fn execute_fs_operation(&mut self, operation: FSOperation) -> Result<FSOperationResult, Self::Error> { self.ser.as_mut().unwrap().serialize_element(&operation)?; self.inner.execute_fs_operation(operation) } } impl<S, F> Drop for FSOperationSerializer<S, F> where S: SerializeSeq { fn drop(&mut self) { if let Err(e) = self.ser.take().unwrap().end() { warn!("Unable to end log sequence: {}", e); } } } fn grind(grind_args: GrindArguments) -> Fallible<()> { let GrindArguments { log_output, test_path, reference_path, timeout, rounds, max_created_files, max_open_files, max_write_size } = grind_args; let mut duration_keeper = if let Some(timeout) = timeout { GrindDurationKeeper::with_timeout(timeout) } else { GrindDurationKeeper::with_rounds(rounds.unwrap()) }; let mut fs_op_rng = SmallRng::from_entropy(); let reference_rng = SmallRng::from_rng(&mut fs_op_rng)?; let assessed_rng = reference_rng.clone(); let assessed_fs_grinder = FSGrinder::new(test_path, assessed_rng); let reference_fs_grinder = FSGrinder::new(reference_path, reference_rng); let operation_executor = FSOperationComparator::new(reference_fs_grinder, assessed_fs_grinder); let output = if let Some(log_output_path) = log_output { let file = BufWriter::new(File::create(log_output_path)?); Either::Left(file) } else { Either::Right(io::sink()) }; let mut serializer = serde_json::Serializer::pretty(output); let mut op_log_and_execute = FSOperationSerializer::new(&mut serializer, operation_executor)?; let fs_op_gen = RandFSOpGenerator::new(fs_op_rng, max_write_size, max_open_files, max_created_files); for op in fs_op_gen.take_while(move |_| !duration_keeper.elapsed()) { op_log_and_execute.execute_fs_operation(op)?; } Ok(()) } fn replay(log_path: PathBuf, reference_path: PathBuf, assessed_path: PathBuf) -> Fallible<()> { let log_file = BufReader::new(File::open(log_path)?); let log: Vec<FSOperation> = serde_json::from_reader(log_file)?; let reference_rng = SmallRng::from_entropy(); let assessed_rng = reference_rng.clone(); let assessed_fs_grinder = FSGrinder::new(assessed_path, assessed_rng); let reference_fs_grinder = FSGrinder::new(reference_path, reference_rng); let mut operation_executor = FSOperationComparator::new(reference_fs_grinder, assessed_fs_grinder); for op in log { operation_executor.execute_fs_operation(op)?; } Ok(()) } fn main() { flexi_logger::Logger::with_env().start().unwrap(); let args: Arguments = Arguments::from_args(); match args { Arguments::Grind(grind_args) => grind(grind_args), Arguments::Replay { log_path, test_path, reference_path } => replay(log_path, reference_path, test_path) }.unwrap(); }
use crate::algorithm::centroid::Centroid; use crate::algorithm::map_coords::MapCoords; use crate::{Line, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon}; use num_traits::{Float, FromPrimitive}; use std::iter::Sum; #[inline] fn rotate_inner<T>(x: T, y: T, x0: T, y0: T, sin_theta: T, cos_theta: T) -> Point<T> where T: Float, { let x = x - x0; let y = y - y0; Point::new( x * cos_theta - y * sin_theta + x0, x * sin_theta + y * cos_theta + y0, ) } // Rotate a single point "angle" degrees about an origin. Origin can be an // arbitrary point. Pass Point::new(0., 0.) for the actual origin. fn rotate_one<T: Float>(angle: T, origin: Point<T>, point: Point<T>) -> Point<T> { let (sin_theta, cos_theta) = angle.to_radians().sin_cos(); rotate_inner( point.x(), point.y(), origin.x(), origin.y(), sin_theta, cos_theta, ) } // Rotate an iterator of points "angle" degrees about an origin. Origin can be // an arbitrary point. Pass Point::new(0., 0.) for the actual origin. fn rotate_many<T>( angle: T, origin: Point<T>, points: impl Iterator<Item = Point<T>>, ) -> impl Iterator<Item = Point<T>> where T: Float, { let (sin_theta, cos_theta) = angle.to_radians().sin_cos(); let (x0, y0) = origin.x_y(); points.map(move |point| rotate_inner(point.x(), point.y(), x0, y0, sin_theta, cos_theta)) } pub trait Rotate<T> { /// Rotate a Geometry around its centroid by an angle, in degrees /// /// Positive angles are counter-clockwise, and negative angles are clockwise rotations. /// /// # Units /// /// - `angle`: degrees /// /// # Examples /// /// ``` /// use geo::algorithm::rotate::Rotate; /// use geo::{LineString, Point}; /// /// let mut vec = Vec::new(); /// vec.push(Point::new(0.0, 0.0)); /// vec.push(Point::new(5.0, 5.0)); /// vec.push(Point::new(10.0, 10.0)); /// let linestring = LineString::from(vec); /// let rotated = linestring.rotate(-45.0); /// let mut correct = Vec::new(); /// correct.push(Point::new(-2.0710678118654755, 5.0)); /// correct.push(Point::new(5.0, 5.0)); /// correct.push(Point::new(12.071067811865476, 5.0)); /// let correct_ls = LineString::from(correct); /// assert_eq!(rotated, correct_ls); /// ``` fn rotate(&self, angle: T) -> Self where T: Float; } pub trait RotatePoint<T> { /// Rotate a Geometry around an arbitrary point by an angle, given in degrees /// /// Positive angles are counter-clockwise, and negative angles are clockwise rotations. /// /// # Units /// /// - `angle`: degrees /// /// # Examples /// /// ``` /// use geo::algorithm::rotate::RotatePoint; /// use geo::{line_string, point}; /// /// let ls = line_string![ /// (x: 0.0, y: 0.0), /// (x: 5.0, y: 5.0), /// (x: 10.0, y: 10.0) /// ]; /// /// let rotated = ls.rotate_around_point( /// -45.0, /// point!(x: 10.0, y: 0.0), /// ); /// /// assert_eq!(rotated, line_string![ /// (x: 2.9289321881345245, y: 7.071067811865475), /// (x: 10.0, y: 7.0710678118654755), /// (x: 17.071067811865476, y: 7.0710678118654755) /// ]); /// ``` fn rotate_around_point(&self, angle: T, point: Point<T>) -> Self where T: Float; } impl<T, G> RotatePoint<T> for G where T: Float, G: MapCoords<T, T, Output = G>, { fn rotate_around_point(&self, angle: T, point: Point<T>) -> Self { let (sin_theta, cos_theta) = angle.to_radians().sin_cos(); let (x0, y0) = point.x_y(); self.map_coords(|&(x, y)| rotate_inner(x, y, x0, y0, sin_theta, cos_theta).x_y()) } } impl<T> Rotate<T> for Point<T> where T: Float, { /// Rotate the Point about itself by the given number of degrees /// This operation leaves the point coordinates unchanged fn rotate(&self, _angle: T) -> Self { *self } } impl<T> Rotate<T> for Line<T> where T: Float, { fn rotate(&self, angle: T) -> Self { let centroid = self.centroid(); Line::new( rotate_one(angle, centroid, self.start_point()), rotate_one(angle, centroid, self.end_point()), ) } } impl<T> Rotate<T> for LineString<T> where T: Float, { /// Rotate the LineString about its centroid by the given number of degrees fn rotate(&self, angle: T) -> Self { rotate_many(angle, self.centroid().unwrap(), self.points_iter()).collect() } } impl<T> Rotate<T> for Polygon<T> where T: Float + FromPrimitive + Sum, { /// Rotate the Polygon about its centroid by the given number of degrees fn rotate(&self, angle: T) -> Self { // if a polygon has holes, use the centroid of its outer shell as the rotation origin let centroid = if self.interiors().is_empty() { self.centroid().unwrap() } else { self.exterior().centroid().unwrap() }; Polygon::new( rotate_many(angle, centroid, self.exterior().points_iter()).collect(), self.interiors() .iter() .map(|ring| rotate_many(angle, centroid, ring.points_iter()).collect()) .collect(), ) } } impl<T> Rotate<T> for MultiPolygon<T> where T: Float + FromPrimitive + Sum, { /// Rotate the contained Polygons about their centroids by the given number of degrees fn rotate(&self, angle: T) -> Self { MultiPolygon(self.0.iter().map(|poly| poly.rotate(angle)).collect()) } } impl<T> Rotate<T> for MultiLineString<T> where T: Float + FromPrimitive, { /// Rotate the contained LineStrings about their centroids by the given number of degrees fn rotate(&self, angle: T) -> Self { MultiLineString(self.0.iter().map(|ls| ls.rotate(angle)).collect()) } } impl<T> Rotate<T> for MultiPoint<T> where T: Float + FromPrimitive, { /// Rotate the contained Points about their centroids by the given number of degrees fn rotate(&self, angle: T) -> Self { MultiPoint(self.0.iter().map(|p| p.rotate(angle)).collect()) } } #[cfg(test)] mod test { use super::*; use crate::{line_string, point, polygon, Coordinate, Point}; #[test] fn test_rotate_around_point() { let p = point!(x: 1.0, y: 5.0); let rotated = p.rotate(30.0); // results agree with Shapely / GEOS assert_eq!(rotated, Point::new(1.0, 5.0)); } #[test] fn test_rotate_linestring() { let linestring = line_string![ (x: 0.0, y: 0.0), (x: 5.0, y: 5.0), (x: 10.0, y: 10.0) ]; let rotated = linestring.rotate(-45.0); // results agree with Shapely / GEOS assert_eq!( rotated, line_string![ (x: -2.0710678118654755, y: 5.0), (x: 5.0, y: 5.0), (x: 12.071067811865476, y: 5.0) ] ); } #[test] fn test_rotate_polygon() { let poly1 = polygon![ (x: 5., y: 1.), (x: 4., y: 2.), (x: 4., y: 3.), (x: 5., y: 4.), (x: 6., y: 4.), (x: 7., y: 3.), (x: 7., y: 2.), (x: 6., y: 1.), (x: 5., y: 1.) ]; let rotated = poly1.rotate(-15.0); let correct = polygon![ (x: 4.628808519201685, y: 1.1805207831176578), (x: 3.921701738015137, y: 2.405265654509247), (x: 4.180520783117657, y: 3.3711914807983154), (x: 5.405265654509247, y: 4.0782982619848624), (x: 6.371191480798315, y: 3.819479216882342), (x: 7.0782982619848624, y: 2.594734345490753), (x: 6.819479216882343, y: 1.6288085192016848), (x: 5.594734345490753, y: 0.9217017380151371), (x: 4.628808519201685, y: 1.1805207831176578) ]; // results agree with Shapely / GEOS assert_eq!(rotated, correct); } #[test] fn test_rotate_polygon_holes() { let poly1 = polygon![ exterior: [ (x: 5.0, y: 1.0), (x: 4.0, y: 2.0), (x: 4.0, y: 3.0), (x: 5.0, y: 4.0), (x: 6.0, y: 4.0), (x: 7.0, y: 3.0), (x: 7.0, y: 2.0), (x: 6.0, y: 1.0), (x: 5.0, y: 1.0) ], interiors: [ [ (x: 5.0, y: 1.3), (x: 5.5, y: 2.0), (x: 6.0, y: 1.3), (x: 5.0, y: 1.3), ], [ (x: 5., y: 2.3), (x: 5.5, y: 3.0), (x: 6., y: 2.3), (x: 5., y: 2.3), ], ], ]; let rotated = poly1.rotate(-15.0); let correct_outside = vec![ Coordinate::from((4.628808519201685, 1.180520783117658)), Coordinate::from((3.921701738015137, 2.4052656545092472)), Coordinate::from((4.180520783117657, 3.3711914807983154)), Coordinate::from((5.405265654509247, 4.078298261984863)), Coordinate::from((6.371191480798315, 3.8194792168823426)), Coordinate::from((7.0782982619848624, 2.594734345490753)), Coordinate::from((6.819479216882343, 1.628808519201685)), Coordinate::from((5.594734345490753, 0.9217017380151373)), Coordinate::from((4.628808519201685, 1.180520783117658)), ]; let correct_inside = vec![ Coordinate::from((4.706454232732441, 1.4702985310043786)), Coordinate::from((5.37059047744874, 2.017037086855466)), Coordinate::from((5.672380059021509, 1.2114794859018578)), Coordinate::from((4.706454232732441, 1.4702985310043786)), ]; assert_eq!(rotated.exterior().0, correct_outside); assert_eq!(rotated.interiors()[0].0, correct_inside); } #[test] fn test_rotate_around_point_arbitrary() { let p = Point::new(5.0, 10.0); let rotated = p.rotate_around_point(-45., Point::new(10., 34.)); assert_eq!(rotated, Point::new(-10.506096654409877, 20.564971157455595)); } #[test] fn test_rotate_line() { let line0 = Line::from([(0., 0.), (0., 2.)]); let line1 = Line::from([(1., 0.9999999999999999), (-1., 1.)]); assert_eq!(line0.rotate(90.), line1); } #[test] fn test_rotate_line_around_point() { let line0 = Line::new(Point::new(0., 0.), Point::new(0., 2.)); let line1 = Line::new( Point::new(0., 0.), Point::new(-2., 0.00000000000000012246467991473532), ); assert_eq!(line0.rotate_around_point(90., Point::new(0., 0.)), line1); } }
use solana_program::sysvar::clock::Clock; use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, program_error::ProgramError, msg, pubkey::Pubkey, program_pack::{Pack, IsInitialized}, sysvar::{rent::Rent, Sysvar}, program::{invoke, invoke_signed}, system_program, system_instruction }; use crate::{instruction::LotteryInstruction, error::LotteryError, state::{Lottery, ENTRANT_COUNT}}; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; pub struct Processor; impl Processor { pub fn process(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult { let instruction = LotteryInstruction::unpack(instruction_data)?; match instruction { LotteryInstruction::InitLottery { initializer_pubkey } => { msg!("Instruction: InitLottery"); Self::process_init_lottery(accounts, program_id, &initializer_pubkey) }, LotteryInstruction::Enter => { msg!("Instruction: Enter"); Self::process_enter(accounts, program_id) }, LotteryInstruction::Receive => { msg!("Instruction: Receive"); Self::process_receive(accounts, program_id) } } } fn process_init_lottery( accounts: &[AccountInfo], program_id: &Pubkey, initializer_pubkey: &Pubkey ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let lottery_account = next_account_info(account_info_iter)?; let rent = &Rent::from_account_info(next_account_info(account_info_iter)?)?; let account_rent_exempt_minimum_balance = rent.minimum_balance(lottery_account.data_len()); if !(lottery_account.lamports() >= account_rent_exempt_minimum_balance) { return Err(LotteryError::NotRentExempt.into()); } if lottery_account.lamports() <= account_rent_exempt_minimum_balance { return Err(LotteryError::TicketAmountMissing.into()); } let mut lottery_info = Lottery::unpack_unchecked(&lottery_account.data.borrow())?; if lottery_info.is_initialized() { return Err(ProgramError::AccountAlreadyInitialized); } lottery_info.is_initialized = true; lottery_info.initializer_pubkey = *initializer_pubkey; lottery_info.ticket_price = lottery_account.lamports() - account_rent_exempt_minimum_balance; lottery_info.winner = Pubkey::default(); lottery_info.entrants[0] = *initializer_pubkey; // Default remaining entrants for entrant in lottery_info.entrants[1..].iter_mut() { *entrant = Pubkey::default(); // Is this default the best way to express not valid? } Lottery::pack(lottery_info, &mut lottery_account.data.borrow_mut())?; Ok(()) } fn process_enter( accounts: &[AccountInfo], program_id: &Pubkey, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let payer_account = next_account_info(account_info_iter)?; // Shortcut for now as we want to get that done let lottery_account = next_account_info(account_info_iter)?; let system_program_account = next_account_info(account_info_iter)?; if !payer_account.is_signer { return Err(ProgramError::MissingRequiredSignature); } if lottery_account.owner != program_id { return Err(ProgramError::IncorrectProgramId); } let mut lottery_info = Lottery::unpack_unchecked(&lottery_account.data.borrow())?; if !lottery_info.is_initialized() { return Err(ProgramError::InvalidAccountData); } if lottery_info.winner != Pubkey::default() { return Err(LotteryError::LotteryFinished.into()); } // Transfer of ticket price invoke( &system_instruction::transfer( &payer_account.key, lottery_account.key, lottery_info.ticket_price, ), &[ payer_account.clone(), lottery_account.clone(), system_program_account.clone(), ], )?; let clock_info = next_account_info(account_info_iter)?; let clock = &Clock::from_account_info(clock_info)?; // Write entry in entrants // TODO: Do not allow payer to enter more than once let mut entrants_count = 1; for entrant in lottery_info.entrants.iter_mut() { if *entrant == Pubkey::default() { *entrant = *payer_account.key; break } entrants_count += 1; } if entrants_count == ENTRANT_COUNT { let mut hasher = DefaultHasher::new(); // TODO: This is currently predictable, make this random somehow for entrant in lottery_info.entrants.iter_mut() { entrant.hash(&mut hasher); } let index = hasher.finish() as usize % ENTRANT_COUNT; lottery_info.winner = lottery_info.entrants[index]; } Lottery::pack(lottery_info, &mut lottery_account.data.borrow_mut())?; Ok(()) } fn process_receive( accounts: &[AccountInfo], program_id: &Pubkey, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let winner_account = next_account_info(account_info_iter)?; let lottery_account = next_account_info(account_info_iter)?; if !winner_account.is_signer { return Err(ProgramError::MissingRequiredSignature); } if lottery_account.owner != program_id { return Err(ProgramError::IncorrectProgramId); } let lottery_info = Lottery::unpack_unchecked(&lottery_account.data.borrow())?; if !lottery_info.is_initialized() { return Err(ProgramError::InvalidAccountData); } if *winner_account.key != lottery_info.winner { return Err(ProgramError::InvalidAccountData); // TODO: Better error here? } **winner_account.lamports.borrow_mut() = winner_account .lamports() .checked_add(lottery_account.lamports()) .ok_or(LotteryError::AmountOverflow)?; msg!("Closing the lottery account"); **lottery_account.lamports.borrow_mut() = 0; Ok(()) } }
use sqlx::postgres::PgPool; use std::{collections::HashMap, sync::Arc}; use tokio::sync::RwLock; use uuid::Uuid; use crate::handlers::rpc::client::Client; #[derive(Clone, Debug)] pub struct Environment { pool: Arc<PgPool>, clients: Arc<RwLock<HashMap<Uuid, Client>>>, } impl Environment { pub async fn new(pool: PgPool) -> anyhow::Result<Self> { Ok(Self { pool: Arc::new(pool), clients: Arc::new(RwLock::new(HashMap::new())), }) } pub fn db(&self) -> &PgPool { &self.pool } pub fn clients(&self) -> &RwLock<HashMap<Uuid, Client>> { &self.clients } }
use naia_socket_shared::LinkConditionerConfig; use std::{default::Default, time::Duration}; /// Contains Config properties which will be shared by Server and Client #[derive(Clone, Debug)] pub struct SharedConfig { /// The duration between each tick pub tick_interval: Duration, /// Configuration used to simulate network conditions pub link_condition_config: Option<LinkConditionerConfig>, } impl SharedConfig { /// Creates a new SharedConfig pub fn new( tick_interval: Duration, link_condition_config: Option<LinkConditionerConfig>, ) -> Self { SharedConfig { tick_interval, link_condition_config, } } } impl Default for SharedConfig { fn default() -> Self { Self { tick_interval: Duration::from_secs(1), link_condition_config: None, } } }
use super::script::PythonScripts; use crate::code::AddScripts; use crate::error::Result; use crate::nodes::NodeRoot; pub use n3_program::externs::ExternCode; impl AddScripts for ExternCode { fn add_scripts(&self, root: &NodeRoot, scripts: &mut PythonScripts) -> Result<()> { let name = &self.data.name; if !scripts.contains_key(name) { let script = root.get_extern(name)?; scripts.insert(name.clone(), script); } Ok(()) } }
//! Different behavior for enemies. //! use super::{avoid, go_to_path_point, halt, seek}; use crate::core::colors; use crate::core::random::RandomGenerator; use crate::core::transform::Transform; use crate::gameplay::collision::{CollisionLayer, CollisionWorld}; use crate::gameplay::physics::DynamicBody; use crate::render::path::debug; use crate::resources::Resources; use rand::Rng; /// Follow the player. Also rotate to face the player. pub fn follow_player( t: &mut Transform, body: &mut DynamicBody, player_pos: Option<glam::Vec2>, resources: &Resources, ) { if let Some(player_position) = player_pos { let steering = if (t.translation - player_position).length() > 200.0 { seek( t.translation, body.velocity, player_position, body.max_velocity, ) } else { halt(body.velocity) }; body.add_force(steering); debug::stroke_line( resources, t.translation, t.translation + steering, colors::RED, ); // rotate toward the player { let dir = glam::Mat2::from_angle(t.rotation) * glam::Vec2::unit_y(); let angle_to_perform = (player_position - t.translation).angle_between(dir); t.rotation -= 0.05 * angle_to_perform; } } } /// Variation of follow_player. Do not halt. pub fn follow_player_bis( t: &mut Transform, body: &mut DynamicBody, player_pos: Option<glam::Vec2>, resources: &Resources, ) { if let Some(player_position) = player_pos { let steering = seek( t.translation, body.velocity, player_position, body.max_velocity, ); body.add_force(steering); debug::stroke_line( resources, t.translation, t.translation + steering, colors::RED, ); // rotate toward the player { let dir = glam::Mat2::from_angle(t.rotation) * glam::Vec2::unit_y(); let angle_to_perform = (player_position - t.translation).angle_between(dir); t.rotation -= 0.05 * angle_to_perform; } } } fn rotate_towards(t: &mut Transform, target: glam::Vec2) { let dir = glam::Mat2::from_angle(t.rotation) * glam::Vec2::unit_y(); let angle_to_perform = (target - t.translation).angle_between(dir); t.rotation -= 0.05 * angle_to_perform; } /// /// Apply some steering force if there is some obstacle on the way, pub fn avoid_obstacles( e: hecs::Entity, t: &mut Transform, body: &mut DynamicBody, resources: &Resources, ignore_mask: CollisionLayer, ) { { let collision_world = resources.fetch::<CollisionWorld>().unwrap(); if body.velocity.length() > 0.0 { if let Some(f) = avoid( e, t, body.velocity, 300.0, &*collision_world, 300.0, ignore_mask, ) { body.add_force(f); debug::stroke_line(resources, t.translation, t.translation + f, colors::BLUE); } } } } pub fn follow_random_path( target: &mut glam::Vec2, is_initialized: &mut bool, t: &mut Transform, body: &mut DynamicBody, resources: &Resources, ) { if !(*is_initialized) { let mut random = resources.fetch_mut::<RandomGenerator>().unwrap(); *target = pick_point(&mut *random); *is_initialized = true; } let steering = go_to_path_point(*target, t.translation, body.velocity, body.max_velocity); debug::stroke_line(resources, t.translation, *target, colors::BLUE); if let Some(steering) = steering { body.add_force(steering); debug::stroke_line( resources, t.translation, t.translation + steering, colors::RED, ); } else { // Need to generate new target. // let mut random = resources.fetch_mut::<RandomGenerator>().unwrap(); *target = pick_point(&mut *random); } rotate_towards(t, *target); } fn pick_point(random: &mut RandomGenerator) -> glam::Vec2 { let x_range = (-1500.0, 1500.0f32); let y_range = (-850.0, 850.0f32); let rng = random.rng(); let (x, y) = ( rng.gen_range(x_range.0, x_range.1), rng.gen_range(y_range.0, y_range.1), ); glam::vec2(x, y) }
use std::fs; use std::time::Instant; fn main() { let start = Instant::now(); let mut tst_ship = Ship::from_file("example.txt"); let mut ship = Ship::from_file("input.txt"); // part 1 tst_ship.follow_instructions(1); assert_eq!(tst_ship.manhattan_distance(), 25); ship.follow_instructions(1); println!("Manhattan distance (part 1) = {}", ship.manhattan_distance()); // part 2 tst_ship.reset(); tst_ship.follow_instructions(2); assert_eq!(tst_ship.manhattan_distance(), 286); ship.reset(); ship.follow_instructions(2); println!("Manhattan distance (part 2) = {}", ship.manhattan_distance()); // exec time let duration = start.elapsed(); println!("Finished after {:?}", duration); } struct Ship { position : (i32, i32), direction: (i32, i32), way_point: (i32, i32), instructions: Vec<Instr> } enum Action {North, East, South, West, Left, Right, Forward} struct Instr { action: Action, val: i32, } impl Ship { fn follow_instructions(&mut self, part: i32) { for instr in &self.instructions { match instr.action { Action::North => { if part == 2 { self.way_point.1 += instr.val; } else { self.position.1 += instr.val; } }, Action::East => { if part == 2 { self.way_point.0 += instr.val; } else { self.position.0 += instr.val; } }, Action::South => { if part == 2 { self.way_point.1 -= instr.val; } else {self.position.1 -= instr.val;} }, Action::West => { if part == 2 { self.way_point.0 -= instr.val; } else { self.position.0 -= instr.val;} }, Action::Left => { if part == 2 { self.way_point = Ship::turn(self.way_point, instr.val);} else {self.direction = Ship::turn(self.direction, instr.val);} }, Action::Right => { if part == 2 { self.way_point = Ship::turn(self.way_point, -instr.val); } else {self.direction = Ship::turn(self.direction, -instr.val); } }, Action::Forward => { if part == 2 { self.position.0 += self.way_point.0 * instr.val; self.position.1 += self.way_point.1 * instr.val; } else { self.position.0 += self.direction.0 * instr.val; self.position.1 += self.direction.1 * instr.val; } } } } } fn turn(direction: (i32, i32), angle: i32) -> (i32, i32) { let cos_theta = f32::cos(angle as f32 / 180.0 * std::f32::consts::PI); let sin_theta = f32::sin(angle as f32 / 180.0 * std::f32::consts::PI); let x = direction.0 as f32; let y = direction.1 as f32; let new_x = x * cos_theta - y * sin_theta; let new_y = x * sin_theta + y * cos_theta; (new_x.round() as i32, new_y.round() as i32) } fn manhattan_distance(&self) -> i32 { self.position.0.abs() + self.position.1.abs() } fn reset(&mut self) { self.direction = (1, 0); self.position = (0, 0); self.way_point = (10, 1); } fn from_file(f_name: &str) -> Ship { let str_in = fs::read_to_string(f_name).expect("Error in reading file"); let mut instructions: Vec<Instr> = Vec::new(); for l in str_in.split_whitespace() { let char_action = &l[0..1]; let value = l[1..].parse::<i32>().unwrap(); match char_action { "N" => instructions.push(Instr { action: Action::North, val: value }), "E" => instructions.push(Instr { action: Action::East, val: value }), "S" => instructions.push(Instr { action: Action::South, val: value }), "W" => instructions.push(Instr { action: Action::West, val: value }), "L" => instructions.push(Instr { action: Action::Left, val: value }), "R" => instructions.push(Instr { action: Action::Right, val: value }), "F" => instructions.push(Instr { action: Action::Forward, val: value }), _ => break } } println!("Loaded {} instructions", instructions.len()); Ship { position: (0, 0), direction: (1, 0), way_point: (10, 1), instructions } } }
// verify-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0516 use spella::algebra::{AssociativeMagma, InvertibleMagma, Magma, UnitalMagma}; use spella::io::Scanner; use spella::sequences::CumulativeSum; use std::cmp; use std::io::{self, prelude::*}; use std::iter::FromIterator; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Sum(pub i32); impl Magma for Sum { fn op(&self, rhs: &Self) -> Self { Sum(self.0 + rhs.0) } } impl AssociativeMagma for Sum {} impl UnitalMagma for Sum { fn identity() -> Self { Sum(0) } } impl InvertibleMagma for Sum { fn invert(&self) -> Self { Sum(-self.0) } } fn main() -> io::Result<()> { let stdin = io::stdin(); let reader = stdin.lock(); let stdout = io::stdout(); let mut writer = std::io::BufWriter::new(stdout); let mut scanner = Scanner::new(reader); macro_rules! scan { ($T:ty) => { scanner.next::<$T>()?.unwrap() }; } loop { let n = scan!(usize); let k = scan!(usize); if n == 0 && k == 0 { break; } let mut a = Vec::with_capacity(n); for _ in 0..n { a.push(Sum(scan!(i32))); } let a = CumulativeSum::from_iter(a); let mut acc = Sum(i32::min_value()); for i in 0..n - (k - 1) { acc = cmp::max(acc, a.fold(i..i + k)); } writeln!(writer, "{}", acc.0)?; assert_eq!(CumulativeSum::from_iter((0..a.len()).map(|i| a.get(i))), a); } Ok(()) }
pub mod area; pub mod collapsing_header; pub mod frame; pub mod menu; pub mod popup; pub mod resize; pub mod scroll_area; pub mod window; pub use { area::Area, collapsing_header::CollapsingHeader, frame::Frame, popup::*, resize::Resize, scroll_area::ScrollArea, window::Window, };
// 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. use { failure::{Error, ResultExt}, fidl_fuchsia_update_channel::{ProviderRequest, ProviderRequestStream}, fuchsia_syslog::fx_log_warn, futures::prelude::*, serde_derive::{Deserialize, Serialize}, std::{fs::File, io, path::PathBuf}, }; #[derive(Clone)] pub(crate) struct ProviderHandler { pub misc_info_dir: PathBuf, } impl Default for ProviderHandler { fn default() -> Self { Self { misc_info_dir: "/misc/ota".into() } } } impl ProviderHandler { pub(crate) async fn handle_request_stream( &self, mut stream: ProviderRequestStream, ) -> Result<(), Error> { while let Some(request) = stream.try_next().await.context("extracting request from stream")? { match request { ProviderRequest::GetCurrent { responder } => { let channel = self.get_current().unwrap_or_else(|err| { fx_log_warn!("error getting current channel: {}", err); "".into() }); responder.send(&channel).context("sending GetCurrent response")?; } } } Ok(()) } fn get_current(&self) -> Result<String, Error> { // TODO: use async IO instead of sync IO once async IO is easy. let file = File::open(self.misc_info_dir.join("current_channel.json")) .context("opening current_channel.json")?; let contents: ChannelProviderContents = serde_json::from_reader(io::BufReader::new(file)) .context("reading current_channel.json")?; let ChannelProviderContents::Version1(info) = contents; Ok(info.legacy_amber_source_name.unwrap_or_else(|| "".into())) } } #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(tag = "version", content = "content", deny_unknown_fields)] enum ChannelProviderContents { #[serde(rename = "1")] Version1(ChannelProviderV1), } #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] struct ChannelProviderV1 { legacy_amber_source_name: Option<String>, } #[cfg(test)] mod tests { use { super::*, fidl::endpoints::create_proxy_and_stream, fidl_fuchsia_update_channel::{ProviderMarker, ProviderProxy}, fuchsia_async as fasync, std::fs, tempfile::TempDir, }; fn spawn_info_handler(info_dir: &TempDir) -> ProviderProxy { let info_handler = ProviderHandler { misc_info_dir: info_dir.path().into() }; let (proxy, stream) = create_proxy_and_stream::<ProviderMarker>().expect("create_proxy_and_stream"); fasync::spawn(async move { info_handler.handle_request_stream(stream).map(|_| ()).await }); proxy } #[fasync::run_singlethreaded(test)] async fn test_fidl_get_channel_works() { let tempdir = TempDir::new().expect("create tempdir"); fs::write( tempdir.path().join("current_channel.json"), r#"{"version":"1","content":{"legacy_amber_source_name":"example"}}"#, ) .expect("write current_channel.json"); let proxy = spawn_info_handler(&tempdir); let res = proxy.get_current().await; assert_eq!(res.map_err(|e| e.to_string()), Ok("example".into())); } #[fasync::run_singlethreaded(test)] async fn test_fidl_get_channel_handles_missing_file() { let tempdir = TempDir::new().expect("create tempdir"); let proxy = spawn_info_handler(&tempdir); let res = proxy.get_current().await; assert_eq!(res.map_err(|e| e.to_string()), Ok("".into())); } #[fasync::run_singlethreaded(test)] async fn test_fidl_get_channel_handles_unexpected_contents() { let tempdir = TempDir::new().expect("create tempdir"); let proxy = spawn_info_handler(&tempdir); fs::write(tempdir.path().join("current_channel.json"), r#"{"version":"1","content":{}}"#) .expect("write current_channel.json"); let res = proxy.get_current().await; assert_eq!(res.map_err(|e| e.to_string()), Ok("".into())); } }
#![deny(missing_debug_implementations)] #![feature(async_await, await_macro, futures_api)] #![forbid(unsafe_code)] pub extern crate deck_core as core; use std::fmt::Debug; use std::future::Future; use std::pin::Pin; use deck_core::{Manifest, ManifestId}; // NOTE: All this noise has been to work fine with a simple `async fn`, with no need for associated // types, this type alias, or `Pin<Box<_>>`. Replace _immediately_ once `async fn` in traits is // stabilized in Rust. pub type RepositoryFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, ()>> + Send + 'a>>; pub trait Repository: Debug { fn query<'a>(&'a mut self, id: &'a ManifestId) -> RepositoryFuture<'a, Manifest>; }
#[derive(Debug, Copy, Clone)] #[repr(i16)] pub enum TypeFormat { Text = 0, Binary = 1, } impl From<i16> for TypeFormat { fn from(code: i16) -> TypeFormat { match code { 0 => TypeFormat::Text, 1 => TypeFormat::Binary, _ => unreachable!(), } } }
use std::io::stdin; fn main() { println!("I am main function"); let x = { let a = 7; let b = 8; a + b // if semi colon is added, then it becomes an expression and not a return statement }; println!("{}", x); test_function(); println!("{}", add(3, 5)); println!("Enter fahrenheit value : "); let mut celcius = String::new(); stdin().read_line(&mut celcius).expect("Not a float"); let celcius: f32 = celcius.trim().parse().expect("Parsing failed"); println!( "Celcius {} to Fahrenheit {}", celcius, convert_cel_to_fah(celcius) ); println!("Enter limit value : "); let mut limit = String::new(); stdin().read_line(&mut limit).expect("Not a float"); let limit: i32 = limit.trim().parse().expect("Parsing failed"); // { // Ok(num) => num, // Err(_) => { // print!("{}", _); // } // }; // println!("{}", ); generate_fibonacci(limit); } fn test_function() { println!("I am from another function"); } fn add(a: i32, b: i32) -> i32 // this is the return type of the function { a + b // return should not have a semicolon } fn convert_cel_to_fah(celcius: f32) -> f32 { (celcius * (9.0 / 5.0)) + 32 as f32 } fn generate_fibonacci(no_of_numbers: i32) { let mut i = 0; while i < no_of_numbers { println!("{}", i); i = i + 1; } }
#[doc = "Reader of register ROUTELOC1"] pub type R = crate::R<u32, super::ROUTELOC1>; #[doc = "Writer for register ROUTELOC1"] pub type W = crate::W<u32, super::ROUTELOC1>; #[doc = "Register ROUTELOC1 `reset()`'s with value 0"] impl crate::ResetValue for super::ROUTELOC1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "I/O Location\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CH4LOC_A { #[doc = "0: Location 0"] LOC0 = 0, #[doc = "1: Location 1"] LOC1 = 1, #[doc = "2: Location 2"] LOC2 = 2, #[doc = "3: Location 3"] LOC3 = 3, #[doc = "4: Location 4"] LOC4 = 4, #[doc = "5: Location 5"] LOC5 = 5, #[doc = "6: Location 6"] LOC6 = 6, } impl From<CH4LOC_A> for u8 { #[inline(always)] fn from(variant: CH4LOC_A) -> Self { variant as _ } } #[doc = "Reader of field `CH4LOC`"] pub type CH4LOC_R = crate::R<u8, CH4LOC_A>; impl CH4LOC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, CH4LOC_A> { use crate::Variant::*; match self.bits { 0 => Val(CH4LOC_A::LOC0), 1 => Val(CH4LOC_A::LOC1), 2 => Val(CH4LOC_A::LOC2), 3 => Val(CH4LOC_A::LOC3), 4 => Val(CH4LOC_A::LOC4), 5 => Val(CH4LOC_A::LOC5), 6 => Val(CH4LOC_A::LOC6), i => Res(i), } } #[doc = "Checks if the value of the field is `LOC0`"] #[inline(always)] pub fn is_loc0(&self) -> bool { *self == CH4LOC_A::LOC0 } #[doc = "Checks if the value of the field is `LOC1`"] #[inline(always)] pub fn is_loc1(&self) -> bool { *self == CH4LOC_A::LOC1 } #[doc = "Checks if the value of the field is `LOC2`"] #[inline(always)] pub fn is_loc2(&self) -> bool { *self == CH4LOC_A::LOC2 } #[doc = "Checks if the value of the field is `LOC3`"] #[inline(always)] pub fn is_loc3(&self) -> bool { *self == CH4LOC_A::LOC3 } #[doc = "Checks if the value of the field is `LOC4`"] #[inline(always)] pub fn is_loc4(&self) -> bool { *self == CH4LOC_A::LOC4 } #[doc = "Checks if the value of the field is `LOC5`"] #[inline(always)] pub fn is_loc5(&self) -> bool { *self == CH4LOC_A::LOC5 } #[doc = "Checks if the value of the field is `LOC6`"] #[inline(always)] pub fn is_loc6(&self) -> bool { *self == CH4LOC_A::LOC6 } } #[doc = "Write proxy for field `CH4LOC`"] pub struct CH4LOC_W<'a> { w: &'a mut W, } impl<'a> CH4LOC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CH4LOC_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Location 0"] #[inline(always)] pub fn loc0(self) -> &'a mut W { self.variant(CH4LOC_A::LOC0) } #[doc = "Location 1"] #[inline(always)] pub fn loc1(self) -> &'a mut W { self.variant(CH4LOC_A::LOC1) } #[doc = "Location 2"] #[inline(always)] pub fn loc2(self) -> &'a mut W { self.variant(CH4LOC_A::LOC2) } #[doc = "Location 3"] #[inline(always)] pub fn loc3(self) -> &'a mut W { self.variant(CH4LOC_A::LOC3) } #[doc = "Location 4"] #[inline(always)] pub fn loc4(self) -> &'a mut W { self.variant(CH4LOC_A::LOC4) } #[doc = "Location 5"] #[inline(always)] pub fn loc5(self) -> &'a mut W { self.variant(CH4LOC_A::LOC5) } #[doc = "Location 6"] #[inline(always)] pub fn loc6(self) -> &'a mut W { self.variant(CH4LOC_A::LOC6) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f); self.w } } #[doc = "I/O Location\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CH5LOC_A { #[doc = "0: Location 0"] LOC0 = 0, #[doc = "1: Location 1"] LOC1 = 1, #[doc = "2: Location 2"] LOC2 = 2, #[doc = "3: Location 3"] LOC3 = 3, #[doc = "4: Location 4"] LOC4 = 4, #[doc = "5: Location 5"] LOC5 = 5, #[doc = "6: Location 6"] LOC6 = 6, } impl From<CH5LOC_A> for u8 { #[inline(always)] fn from(variant: CH5LOC_A) -> Self { variant as _ } } #[doc = "Reader of field `CH5LOC`"] pub type CH5LOC_R = crate::R<u8, CH5LOC_A>; impl CH5LOC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, CH5LOC_A> { use crate::Variant::*; match self.bits { 0 => Val(CH5LOC_A::LOC0), 1 => Val(CH5LOC_A::LOC1), 2 => Val(CH5LOC_A::LOC2), 3 => Val(CH5LOC_A::LOC3), 4 => Val(CH5LOC_A::LOC4), 5 => Val(CH5LOC_A::LOC5), 6 => Val(CH5LOC_A::LOC6), i => Res(i), } } #[doc = "Checks if the value of the field is `LOC0`"] #[inline(always)] pub fn is_loc0(&self) -> bool { *self == CH5LOC_A::LOC0 } #[doc = "Checks if the value of the field is `LOC1`"] #[inline(always)] pub fn is_loc1(&self) -> bool { *self == CH5LOC_A::LOC1 } #[doc = "Checks if the value of the field is `LOC2`"] #[inline(always)] pub fn is_loc2(&self) -> bool { *self == CH5LOC_A::LOC2 } #[doc = "Checks if the value of the field is `LOC3`"] #[inline(always)] pub fn is_loc3(&self) -> bool { *self == CH5LOC_A::LOC3 } #[doc = "Checks if the value of the field is `LOC4`"] #[inline(always)] pub fn is_loc4(&self) -> bool { *self == CH5LOC_A::LOC4 } #[doc = "Checks if the value of the field is `LOC5`"] #[inline(always)] pub fn is_loc5(&self) -> bool { *self == CH5LOC_A::LOC5 } #[doc = "Checks if the value of the field is `LOC6`"] #[inline(always)] pub fn is_loc6(&self) -> bool { *self == CH5LOC_A::LOC6 } } #[doc = "Write proxy for field `CH5LOC`"] pub struct CH5LOC_W<'a> { w: &'a mut W, } impl<'a> CH5LOC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CH5LOC_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Location 0"] #[inline(always)] pub fn loc0(self) -> &'a mut W { self.variant(CH5LOC_A::LOC0) } #[doc = "Location 1"] #[inline(always)] pub fn loc1(self) -> &'a mut W { self.variant(CH5LOC_A::LOC1) } #[doc = "Location 2"] #[inline(always)] pub fn loc2(self) -> &'a mut W { self.variant(CH5LOC_A::LOC2) } #[doc = "Location 3"] #[inline(always)] pub fn loc3(self) -> &'a mut W { self.variant(CH5LOC_A::LOC3) } #[doc = "Location 4"] #[inline(always)] pub fn loc4(self) -> &'a mut W { self.variant(CH5LOC_A::LOC4) } #[doc = "Location 5"] #[inline(always)] pub fn loc5(self) -> &'a mut W { self.variant(CH5LOC_A::LOC5) } #[doc = "Location 6"] #[inline(always)] pub fn loc6(self) -> &'a mut W { self.variant(CH5LOC_A::LOC6) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8); self.w } } #[doc = "I/O Location\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CH6LOC_A { #[doc = "0: Location 0"] LOC0 = 0, #[doc = "1: Location 1"] LOC1 = 1, #[doc = "2: Location 2"] LOC2 = 2, #[doc = "3: Location 3"] LOC3 = 3, #[doc = "4: Location 4"] LOC4 = 4, #[doc = "5: Location 5"] LOC5 = 5, #[doc = "6: Location 6"] LOC6 = 6, #[doc = "7: Location 7"] LOC7 = 7, #[doc = "8: Location 8"] LOC8 = 8, #[doc = "9: Location 9"] LOC9 = 9, #[doc = "10: Location 10"] LOC10 = 10, #[doc = "11: Location 11"] LOC11 = 11, #[doc = "12: Location 12"] LOC12 = 12, #[doc = "13: Location 13"] LOC13 = 13, #[doc = "14: Location 14"] LOC14 = 14, #[doc = "15: Location 15"] LOC15 = 15, #[doc = "16: Location 16"] LOC16 = 16, #[doc = "17: Location 17"] LOC17 = 17, } impl From<CH6LOC_A> for u8 { #[inline(always)] fn from(variant: CH6LOC_A) -> Self { variant as _ } } #[doc = "Reader of field `CH6LOC`"] pub type CH6LOC_R = crate::R<u8, CH6LOC_A>; impl CH6LOC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, CH6LOC_A> { use crate::Variant::*; match self.bits { 0 => Val(CH6LOC_A::LOC0), 1 => Val(CH6LOC_A::LOC1), 2 => Val(CH6LOC_A::LOC2), 3 => Val(CH6LOC_A::LOC3), 4 => Val(CH6LOC_A::LOC4), 5 => Val(CH6LOC_A::LOC5), 6 => Val(CH6LOC_A::LOC6), 7 => Val(CH6LOC_A::LOC7), 8 => Val(CH6LOC_A::LOC8), 9 => Val(CH6LOC_A::LOC9), 10 => Val(CH6LOC_A::LOC10), 11 => Val(CH6LOC_A::LOC11), 12 => Val(CH6LOC_A::LOC12), 13 => Val(CH6LOC_A::LOC13), 14 => Val(CH6LOC_A::LOC14), 15 => Val(CH6LOC_A::LOC15), 16 => Val(CH6LOC_A::LOC16), 17 => Val(CH6LOC_A::LOC17), i => Res(i), } } #[doc = "Checks if the value of the field is `LOC0`"] #[inline(always)] pub fn is_loc0(&self) -> bool { *self == CH6LOC_A::LOC0 } #[doc = "Checks if the value of the field is `LOC1`"] #[inline(always)] pub fn is_loc1(&self) -> bool { *self == CH6LOC_A::LOC1 } #[doc = "Checks if the value of the field is `LOC2`"] #[inline(always)] pub fn is_loc2(&self) -> bool { *self == CH6LOC_A::LOC2 } #[doc = "Checks if the value of the field is `LOC3`"] #[inline(always)] pub fn is_loc3(&self) -> bool { *self == CH6LOC_A::LOC3 } #[doc = "Checks if the value of the field is `LOC4`"] #[inline(always)] pub fn is_loc4(&self) -> bool { *self == CH6LOC_A::LOC4 } #[doc = "Checks if the value of the field is `LOC5`"] #[inline(always)] pub fn is_loc5(&self) -> bool { *self == CH6LOC_A::LOC5 } #[doc = "Checks if the value of the field is `LOC6`"] #[inline(always)] pub fn is_loc6(&self) -> bool { *self == CH6LOC_A::LOC6 } #[doc = "Checks if the value of the field is `LOC7`"] #[inline(always)] pub fn is_loc7(&self) -> bool { *self == CH6LOC_A::LOC7 } #[doc = "Checks if the value of the field is `LOC8`"] #[inline(always)] pub fn is_loc8(&self) -> bool { *self == CH6LOC_A::LOC8 } #[doc = "Checks if the value of the field is `LOC9`"] #[inline(always)] pub fn is_loc9(&self) -> bool { *self == CH6LOC_A::LOC9 } #[doc = "Checks if the value of the field is `LOC10`"] #[inline(always)] pub fn is_loc10(&self) -> bool { *self == CH6LOC_A::LOC10 } #[doc = "Checks if the value of the field is `LOC11`"] #[inline(always)] pub fn is_loc11(&self) -> bool { *self == CH6LOC_A::LOC11 } #[doc = "Checks if the value of the field is `LOC12`"] #[inline(always)] pub fn is_loc12(&self) -> bool { *self == CH6LOC_A::LOC12 } #[doc = "Checks if the value of the field is `LOC13`"] #[inline(always)] pub fn is_loc13(&self) -> bool { *self == CH6LOC_A::LOC13 } #[doc = "Checks if the value of the field is `LOC14`"] #[inline(always)] pub fn is_loc14(&self) -> bool { *self == CH6LOC_A::LOC14 } #[doc = "Checks if the value of the field is `LOC15`"] #[inline(always)] pub fn is_loc15(&self) -> bool { *self == CH6LOC_A::LOC15 } #[doc = "Checks if the value of the field is `LOC16`"] #[inline(always)] pub fn is_loc16(&self) -> bool { *self == CH6LOC_A::LOC16 } #[doc = "Checks if the value of the field is `LOC17`"] #[inline(always)] pub fn is_loc17(&self) -> bool { *self == CH6LOC_A::LOC17 } } #[doc = "Write proxy for field `CH6LOC`"] pub struct CH6LOC_W<'a> { w: &'a mut W, } impl<'a> CH6LOC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CH6LOC_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Location 0"] #[inline(always)] pub fn loc0(self) -> &'a mut W { self.variant(CH6LOC_A::LOC0) } #[doc = "Location 1"] #[inline(always)] pub fn loc1(self) -> &'a mut W { self.variant(CH6LOC_A::LOC1) } #[doc = "Location 2"] #[inline(always)] pub fn loc2(self) -> &'a mut W { self.variant(CH6LOC_A::LOC2) } #[doc = "Location 3"] #[inline(always)] pub fn loc3(self) -> &'a mut W { self.variant(CH6LOC_A::LOC3) } #[doc = "Location 4"] #[inline(always)] pub fn loc4(self) -> &'a mut W { self.variant(CH6LOC_A::LOC4) } #[doc = "Location 5"] #[inline(always)] pub fn loc5(self) -> &'a mut W { self.variant(CH6LOC_A::LOC5) } #[doc = "Location 6"] #[inline(always)] pub fn loc6(self) -> &'a mut W { self.variant(CH6LOC_A::LOC6) } #[doc = "Location 7"] #[inline(always)] pub fn loc7(self) -> &'a mut W { self.variant(CH6LOC_A::LOC7) } #[doc = "Location 8"] #[inline(always)] pub fn loc8(self) -> &'a mut W { self.variant(CH6LOC_A::LOC8) } #[doc = "Location 9"] #[inline(always)] pub fn loc9(self) -> &'a mut W { self.variant(CH6LOC_A::LOC9) } #[doc = "Location 10"] #[inline(always)] pub fn loc10(self) -> &'a mut W { self.variant(CH6LOC_A::LOC10) } #[doc = "Location 11"] #[inline(always)] pub fn loc11(self) -> &'a mut W { self.variant(CH6LOC_A::LOC11) } #[doc = "Location 12"] #[inline(always)] pub fn loc12(self) -> &'a mut W { self.variant(CH6LOC_A::LOC12) } #[doc = "Location 13"] #[inline(always)] pub fn loc13(self) -> &'a mut W { self.variant(CH6LOC_A::LOC13) } #[doc = "Location 14"] #[inline(always)] pub fn loc14(self) -> &'a mut W { self.variant(CH6LOC_A::LOC14) } #[doc = "Location 15"] #[inline(always)] pub fn loc15(self) -> &'a mut W { self.variant(CH6LOC_A::LOC15) } #[doc = "Location 16"] #[inline(always)] pub fn loc16(self) -> &'a mut W { self.variant(CH6LOC_A::LOC16) } #[doc = "Location 17"] #[inline(always)] pub fn loc17(self) -> &'a mut W { self.variant(CH6LOC_A::LOC17) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 16)) | (((value as u32) & 0x3f) << 16); self.w } } #[doc = "I/O Location\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CH7LOC_A { #[doc = "0: Location 0"] LOC0 = 0, #[doc = "1: Location 1"] LOC1 = 1, #[doc = "2: Location 2"] LOC2 = 2, #[doc = "3: Location 3"] LOC3 = 3, #[doc = "4: Location 4"] LOC4 = 4, #[doc = "5: Location 5"] LOC5 = 5, #[doc = "6: Location 6"] LOC6 = 6, #[doc = "7: Location 7"] LOC7 = 7, #[doc = "8: Location 8"] LOC8 = 8, #[doc = "9: Location 9"] LOC9 = 9, #[doc = "10: Location 10"] LOC10 = 10, } impl From<CH7LOC_A> for u8 { #[inline(always)] fn from(variant: CH7LOC_A) -> Self { variant as _ } } #[doc = "Reader of field `CH7LOC`"] pub type CH7LOC_R = crate::R<u8, CH7LOC_A>; impl CH7LOC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, CH7LOC_A> { use crate::Variant::*; match self.bits { 0 => Val(CH7LOC_A::LOC0), 1 => Val(CH7LOC_A::LOC1), 2 => Val(CH7LOC_A::LOC2), 3 => Val(CH7LOC_A::LOC3), 4 => Val(CH7LOC_A::LOC4), 5 => Val(CH7LOC_A::LOC5), 6 => Val(CH7LOC_A::LOC6), 7 => Val(CH7LOC_A::LOC7), 8 => Val(CH7LOC_A::LOC8), 9 => Val(CH7LOC_A::LOC9), 10 => Val(CH7LOC_A::LOC10), i => Res(i), } } #[doc = "Checks if the value of the field is `LOC0`"] #[inline(always)] pub fn is_loc0(&self) -> bool { *self == CH7LOC_A::LOC0 } #[doc = "Checks if the value of the field is `LOC1`"] #[inline(always)] pub fn is_loc1(&self) -> bool { *self == CH7LOC_A::LOC1 } #[doc = "Checks if the value of the field is `LOC2`"] #[inline(always)] pub fn is_loc2(&self) -> bool { *self == CH7LOC_A::LOC2 } #[doc = "Checks if the value of the field is `LOC3`"] #[inline(always)] pub fn is_loc3(&self) -> bool { *self == CH7LOC_A::LOC3 } #[doc = "Checks if the value of the field is `LOC4`"] #[inline(always)] pub fn is_loc4(&self) -> bool { *self == CH7LOC_A::LOC4 } #[doc = "Checks if the value of the field is `LOC5`"] #[inline(always)] pub fn is_loc5(&self) -> bool { *self == CH7LOC_A::LOC5 } #[doc = "Checks if the value of the field is `LOC6`"] #[inline(always)] pub fn is_loc6(&self) -> bool { *self == CH7LOC_A::LOC6 } #[doc = "Checks if the value of the field is `LOC7`"] #[inline(always)] pub fn is_loc7(&self) -> bool { *self == CH7LOC_A::LOC7 } #[doc = "Checks if the value of the field is `LOC8`"] #[inline(always)] pub fn is_loc8(&self) -> bool { *self == CH7LOC_A::LOC8 } #[doc = "Checks if the value of the field is `LOC9`"] #[inline(always)] pub fn is_loc9(&self) -> bool { *self == CH7LOC_A::LOC9 } #[doc = "Checks if the value of the field is `LOC10`"] #[inline(always)] pub fn is_loc10(&self) -> bool { *self == CH7LOC_A::LOC10 } } #[doc = "Write proxy for field `CH7LOC`"] pub struct CH7LOC_W<'a> { w: &'a mut W, } impl<'a> CH7LOC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CH7LOC_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Location 0"] #[inline(always)] pub fn loc0(self) -> &'a mut W { self.variant(CH7LOC_A::LOC0) } #[doc = "Location 1"] #[inline(always)] pub fn loc1(self) -> &'a mut W { self.variant(CH7LOC_A::LOC1) } #[doc = "Location 2"] #[inline(always)] pub fn loc2(self) -> &'a mut W { self.variant(CH7LOC_A::LOC2) } #[doc = "Location 3"] #[inline(always)] pub fn loc3(self) -> &'a mut W { self.variant(CH7LOC_A::LOC3) } #[doc = "Location 4"] #[inline(always)] pub fn loc4(self) -> &'a mut W { self.variant(CH7LOC_A::LOC4) } #[doc = "Location 5"] #[inline(always)] pub fn loc5(self) -> &'a mut W { self.variant(CH7LOC_A::LOC5) } #[doc = "Location 6"] #[inline(always)] pub fn loc6(self) -> &'a mut W { self.variant(CH7LOC_A::LOC6) } #[doc = "Location 7"] #[inline(always)] pub fn loc7(self) -> &'a mut W { self.variant(CH7LOC_A::LOC7) } #[doc = "Location 8"] #[inline(always)] pub fn loc8(self) -> &'a mut W { self.variant(CH7LOC_A::LOC8) } #[doc = "Location 9"] #[inline(always)] pub fn loc9(self) -> &'a mut W { self.variant(CH7LOC_A::LOC9) } #[doc = "Location 10"] #[inline(always)] pub fn loc10(self) -> &'a mut W { self.variant(CH7LOC_A::LOC10) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 24)) | (((value as u32) & 0x3f) << 24); self.w } } impl R { #[doc = "Bits 0:5 - I/O Location"] #[inline(always)] pub fn ch4loc(&self) -> CH4LOC_R { CH4LOC_R::new((self.bits & 0x3f) as u8) } #[doc = "Bits 8:13 - I/O Location"] #[inline(always)] pub fn ch5loc(&self) -> CH5LOC_R { CH5LOC_R::new(((self.bits >> 8) & 0x3f) as u8) } #[doc = "Bits 16:21 - I/O Location"] #[inline(always)] pub fn ch6loc(&self) -> CH6LOC_R { CH6LOC_R::new(((self.bits >> 16) & 0x3f) as u8) } #[doc = "Bits 24:29 - I/O Location"] #[inline(always)] pub fn ch7loc(&self) -> CH7LOC_R { CH7LOC_R::new(((self.bits >> 24) & 0x3f) as u8) } } impl W { #[doc = "Bits 0:5 - I/O Location"] #[inline(always)] pub fn ch4loc(&mut self) -> CH4LOC_W { CH4LOC_W { w: self } } #[doc = "Bits 8:13 - I/O Location"] #[inline(always)] pub fn ch5loc(&mut self) -> CH5LOC_W { CH5LOC_W { w: self } } #[doc = "Bits 16:21 - I/O Location"] #[inline(always)] pub fn ch6loc(&mut self) -> CH6LOC_W { CH6LOC_W { w: self } } #[doc = "Bits 24:29 - I/O Location"] #[inline(always)] pub fn ch7loc(&mut self) -> CH7LOC_W { CH7LOC_W { w: self } } }
use runestick::Id; use std::cell::Cell; use std::rc::Rc; #[derive(Default, Debug, Clone)] pub(crate) struct Gen { id: Rc<Cell<Id>>, } impl Gen { /// Construct a new shared generator. pub(crate) fn new() -> Self { Self { id: Rc::new(Cell::new(Id::initial())), } } /// Get the next identifier. pub(crate) fn next(&self) -> Id { let id = self.id.get(); let next = id.next().expect("ran out of ids"); self.id.set(next); id } }
use crate::io::Buf; use crate::postgres::database::Postgres; use byteorder::NetworkEndian; use std::ops::Range; #[derive(Debug)] pub(crate) struct DataRow<'c> { values: &'c [Option<(u32, u32)>], buffer: &'c [u8], } impl<'c> DataRow<'c> { pub(crate) fn len(&self) -> usize { self.values.len() } pub(crate) fn get(&self, index: usize) -> Option<&'c [u8]> { self.values[index] .as_ref() .map(|(offset, size)| &self.buffer[(*offset as usize)..((*offset + *size) as usize)]) } } impl<'c> DataRow<'c> { pub(crate) fn read( buffer: &'c [u8], values: &'c mut Vec<Option<(u32, u32)>>, ) -> crate::Result<Self> { values.clear(); let mut buf = buffer; let len = buf.get_u16::<NetworkEndian>()?; let mut offset = 6; while values.len() < (len as usize) { // The length of the column value, in bytes (this count does not include itself). // Can be zero. As a special case, -1 indicates a NULL column value. // No value bytes follow in the NULL case. let mut size = buf.get_i32::<NetworkEndian>()?; if size < 0 { values.push(None); offset += 4; } else { values.push(Some((offset, size as u32))); offset += (size as u32) + 4; buf.advance(size as usize); } } Ok(Self { buffer, values }) } } #[cfg(feature = "bench")] #[bench] fn bench_get_data_row(b: &mut test::Bencher) { let buffer = b"\x00\x08\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00\n\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00\x14\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00(\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00P"; let mut values = Vec::with_capacity(10); let row = DataRow::read(buffer, &mut values).unwrap(); b.iter(|| { assert_eq!(row.get(0), None); assert_eq!(row.get(1), Some(&[0, 0, 0, 10][..])); assert_eq!(row.get(2), None); assert_eq!(row.get(3), Some(&[0, 0, 0, 20][..])); assert_eq!(row.get(4), None); }); } #[cfg(feature = "bench")] #[bench] fn bench_read_data_row(b: &mut test::Bencher) { let buffer = b"\x00\x08\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00\n\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00\x14\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00(\xff\xff\xff\xff\x00\x00\x00\x04\x00\x00\x00P"; let mut values = Vec::with_capacity(10); b.iter(|| { let row = DataRow::read(buffer, &mut values).unwrap(); }); }
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ codec::{Decode, Encode}, debug, decl_error, decl_event, decl_module, decl_storage, ensure, StorageMap, }; use frame_system::ensure_signed; use sp_runtime::print; use sp_std::vec::Vec; #[derive(Encode, Decode, Default, Clone, PartialEq)] pub struct PersonData { age: u32, sex: u32, bmi: u32, } /// Configure the pallet by specifying the parameters and types on which it depends. pub trait Trait: frame_system::Trait { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; } // The pallet's runtime storage items. // https://substrate.dev/docs/en/knowledgebase/runtime/storage decl_storage! { trait Store for Module<T: Trait> as TemplateModule { /// The storage item for our proofs. /// It maps a proof to the user who made the claim and when they made it. // Persons get(fn persons): map hasher(blake2_128_concat) T::AccountId => PersonData; Persons get(fn persons): map hasher(blake2_128_concat) T::AccountId => (u32,u32,u32); BloodData get(fn blood_data): map hasher(blake2_128_concat) T::AccountId => (u32,u32,u32,u32,u32,u32,u32); Thing1 get(fn thing1): u32; Thing2 get(fn thing2): u32; } } // Pallets use events to inform users when important changes are made. // Event documentation should end with an array that provides descriptive names for parameters. // https://substrate.dev/docs/en/knowledgebase/runtime/events decl_event! { pub enum Event<T> where AccountId = <T as frame_system::Trait>::AccountId { /// Event emitted when a person has been created. [who] PersonCreated(AccountId), /// Event emitted when a person has been updated. [who] PersonUpdated(AccountId), /// Event emitted when a person has been inserted blood data. [who] BloodDataInserted(AccountId), /// Event emitted when a person has been requested diabet prediction. [who] PredictDiabet(AccountId), /// Set new value. [key] [value] ValueSet(u32, u32), } } // Errors inform users that something went wrong. decl_error! { pub enum Error for Module<T: Trait> { NotEnoughDataFields } } // Dispatchable functions allows users to interact with the pallet and invoke state changes. // These functions materialize as "extrinsics", which are often compared to transactions. // Dispatchable functions must be annotated with a weight and must return a DispatchResult. decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { // Errors must be initialized if they are used by the pallet. type Error = Error<T>; // Events must be initialized if they are used by the pallet. fn deposit_event() = default; /// Allow a user to claim ownership of an unclaimed proof. #[weight = 10_000] fn create_person(origin, age: u32, sex: u32, bmi: u32) { // Check that the extrinsic was signed and get the signer. // This function will return an error if the extrinsic is not signed. // https://substrate.dev/docs/en/knowledgebase/runtime/origin let sender = ensure_signed(origin)?; debug::info!("Create person request from {:?}", sender); /*let body = PersonData { age, sex, bmi, };*/ // Store the proof with the sender and block number. Persons::<T>::insert(&sender,(age,sex,bmi)); // Emit an event that the person was created. Self::deposit_event(RawEvent::PersonCreated(sender)); } /// Allow a user to claim ownership of an unclaimed proof. #[weight = 10_000] fn insert_blood(origin, bp: u32, sr1: u32, sr2: u32, sr3: u32, sr4: u32, sr5: u32, sr6: u32) { // Check that the extrinsic was signed and get the signer. // This function will return an error if the extrinsic is not signed. // https://substrate.dev/docs/en/knowledgebase/runtime/origin let sender = ensure_signed(origin)?; debug::info!("Insert blood data request from {:?}", sender); // Store the proof with the sender and block number. BloodData::<T>::insert(&sender,(bp,sr1,sr2,sr3,sr4,sr5,sr6)); // Emit an event that the person was created. Self::deposit_event(RawEvent::BloodDataInserted(sender)); } /// Allow a user to claim ownership of an unclaimed proof. #[weight = 20_000] fn prdict_diabet(origin) { // Check that the extrinsic was signed and get the signer. // This function will return an error if the extrinsic is not signed. // https://substrate.dev/docs/en/knowledgebase/runtime/origin let sender = ensure_signed(origin)?; debug::info!("Predict diabet request from {:?}", sender); // let val: f64 = 0.1 * thread_rng().sample::<f64,_>(StandardNormal); let val: f64 = 0.088; debug::info!("{}", val); } /// Sets the first simple storage value #[weight = 10_000] pub fn set_thing_1(origin, val: u32) { let _ = ensure_signed(origin)?; Thing1::put(val); Self::deposit_event(RawEvent::ValueSet(1, val)); } /// Sets the second stored value #[weight = 10_000] pub fn set_thing_2(origin, val: u32) { let _ = ensure_signed(origin)?; Thing2::put(val); Self::deposit_event(RawEvent::ValueSet(2, val)); } } } impl<T: Trait> Module<T> { pub fn get_sum() -> u32 { Thing1::get() + Thing2::get() } }
struct EthernetPacket { / } struct IPv4Packet<U> { // } struct IPv6Packet<V> { } struct UDPPacket<W> { }
use winapi::shared::winerror::{HRESULT, SUCCEEDED}; use winapi::Interface; use wio::com::ComPtr; #[derive(Debug)] pub struct Error(HRESULT); pub unsafe fn wrap<T, U, F>(hr: HRESULT, ptr: *mut T, f: F) -> Result<U, Error> where F: Fn(ComPtr<T>) -> U, T: Interface, { if SUCCEEDED(hr) { Ok(f(ComPtr::from_raw(ptr))) } else { Err(Error(hr)) } } pub fn wrap_unit(hr: HRESULT) -> Result<(), Error> { if SUCCEEDED(hr) { Ok(()) } else { Err(Error(hr)) } }
use rumble::api::Central; use rumble::api::Peripheral; use rumble::bluez::manager::Manager; use std::thread; use std::time::Duration; fn main() { let manager = Manager::new().unwrap(); let adapters = manager.adapters().unwrap(); let mut adapter = adapters.into_iter().nth(0).unwrap(); adapter = manager.down(&adapter).unwrap(); adapter = manager.up(&adapter).unwrap(); let central = adapter.connect().unwrap(); central.start_scan().unwrap(); thread::sleep(Duration::from_secs(2)); for peripheral in central.peripherals().into_iter() { println!("{:?}", peripheral.properties().local_name); } }
// Buttplug Rust Source Code File - See https://buttplug.io for more info. // // Copyright 2016-2020 Nonpolynomial Labs LLC. All rights reserved. // // Licensed under the BSD 3-Clause license. See LICENSE file in the project root // for full license information. //! Implementation of internal Buttplug Client event loop. use super::{ client_message_sorter::ClientMessageSorter, device::{ButtplugClientDevice, ButtplugClientDeviceEvent}, ButtplugClientError, ButtplugClientEvent, ButtplugClientMessageFuturePair, }; use crate::{ connector::{ButtplugConnector, ButtplugConnectorStateShared}, core::{ errors::ButtplugServerError, messages::{ ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage, DeviceList, DeviceMessageInfo, }, }, }; use async_channel::{bounded, Receiver, Sender}; use broadcaster::BroadcastChannel; use dashmap::DashMap; use futures::{Future, FutureExt, StreamExt, Stream}; use std::{ hash::{Hash, Hasher}, sync::Arc, }; use tracing_futures::Instrument; /// Enum used for communication from the client to the event loop. pub(super) enum ButtplugClientRequest { /// Client request to disconnect, via already sent connector instance. Disconnect(ButtplugConnectorStateShared), /// Given a DeviceList message, update the inner loop values and create /// events for additions. HandleDeviceList(DeviceList), /// Client request to send a message via the connector. /// /// Bundled future should have reply set and waker called when this is /// finished. Message(ButtplugClientMessageFuturePair), } pub(super) struct ButtplugClientDeviceInternal { // We do not want to store a full ButtplugClientDevice here, as it will // contain event channels that are never handled. Instead, we create new // client devices when they are requested. pub device: Arc<DeviceMessageInfo>, pub channel: Arc<BroadcastChannel<ButtplugClientDeviceEvent>>, } impl Eq for ButtplugClientDeviceInternal { } impl ButtplugClientDeviceInternal { pub fn new( device: DeviceMessageInfo, channel: BroadcastChannel<ButtplugClientDeviceEvent>, ) -> Self { Self { device: Arc::new(device), channel: Arc::new(channel), } } } impl PartialEq for ButtplugClientDeviceInternal { fn eq(&self, other: &Self) -> bool { self.device.device_index == other.device.device_index } } impl Hash for ButtplugClientDeviceInternal { fn hash<H: Hasher>(&self, state: &mut H) { self.device.device_index.hash(state); self.device.device_name.hash(state); } } /// Event loop for running [ButtplugClient] connections. /// /// Acts as a hub for communication between the connector and [ButtplugClient] /// instances. /// /// # Why an event loop? /// /// Due to the async nature of Buttplug, we many channels routed to many /// different tasks. However, all of those tasks will refer to the same event /// loop. This allows us to coordinate and centralize our information while /// keeping the API async. /// /// Note that no async call here should block. Any .await should only be on /// async channels, and those channels should never have backpressure. We hope. struct ButtplugClientEventLoop<ConnectorType> where ConnectorType: ButtplugConnector<ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage> + 'static, { device_map: Arc<DashMap<u32, ButtplugClientDeviceInternal>>, /// Sends events to the [ButtplugClient] instance. This needs to be a /// broadcast channel, as the client will have at least 2 copies of it, so we /// want one sender, many receivers, all receiving messages. event_sender: BroadcastChannel<ButtplugClientEvent>, /// Sends events to the client receiver. Stored here so it can be handed to /// new ButtplugClientDevice instances. client_sender: Sender<ButtplugClientRequest>, /// Receives incoming messages from client instances. client_receiver: Receiver<ButtplugClientRequest>, /// Connector the event loop will use to communicate with the [ButtplugServer] connector: ConnectorType, /// Receiver for messages send from the [ButtplugServer] via the connector. connector_receiver: Receiver<Result<ButtplugCurrentSpecServerMessage, ButtplugServerError>>, sorter: ClientMessageSorter, } impl<ConnectorType> ButtplugClientEventLoop<ConnectorType> where ConnectorType: ButtplugConnector<ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage> + 'static, { /// Creates a new [ButtplugClientEventLoop]. /// /// Given the [ButtplugClientConnector] object, as well as the channels used /// for communicating with the client, creates an event loop structure and /// returns it. pub fn new( connector: ConnectorType, connector_receiver: Receiver<Result<ButtplugCurrentSpecServerMessage, ButtplugServerError>>, event_sender: BroadcastChannel<ButtplugClientEvent>, client_sender: Sender<ButtplugClientRequest>, client_receiver: Receiver<ButtplugClientRequest>, device_map: Arc<DashMap<u32, ButtplugClientDeviceInternal>>, ) -> Self { trace!("Creating ButtplugClientEventLoop instance."); Self { device_map, client_sender, client_receiver, event_sender, connector_receiver, connector, sorter: ClientMessageSorter::default(), } } /// Creates a [ButtplugClientDevice] from [DeviceMessageInfo]. /// /// Given a [DeviceMessageInfo] from a [DeviceAdded] or [DeviceList] message, /// creates a ButtplugClientDevice and adds it the internal device map, then /// returns the instance. fn create_client_device(&mut self, info: &DeviceMessageInfo) -> ButtplugClientDevice { debug!( "Trying to create a client device from DeviceMessageInfo: {:?}", info ); match self.device_map.get(&info.device_index) { // If the device already exists in our map, clone it. Some(dev) => { debug!("Device already exists, creating clone."); ButtplugClientDevice::from(( &*dev.device, self.client_sender.clone(), (*dev.channel).clone(), )) } // If it doesn't, insert it. None => { debug!("Device does not exist, creating new entry."); let channel = BroadcastChannel::new(); let device = ButtplugClientDevice::from((info, self.client_sender.clone(), channel.clone())); self.device_map.insert( info.device_index, ButtplugClientDeviceInternal::new(info.clone(), channel), ); device } } } async fn send_client_event(&mut self, event: &ButtplugClientEvent) { trace!("Forwarding event to client"); self.event_sender.send(event).await.unwrap(); // Due to how broadcaster works, it will always send messages to ALL copies // of itself, including this one. This means that many time we send a value, // we also have to read it out here. Sucks, but not gonna kill us. self.event_sender.recv().await.unwrap(); } /// Parse device messages from the connector. /// /// Since the event loop maintains the state of all devices reported from the /// server, it will catch [DeviceAdded]/[DeviceList]/[DeviceRemoved] messages /// and update its map accordingly. After that, it will pass the information /// on as a [ButtplugClientEvent] to the [ButtplugClient]. async fn parse_connector_message( &mut self, msg_result: Result<ButtplugCurrentSpecServerMessage, ButtplugServerError>, ) { if self.sorter.maybe_resolve_result(&msg_result).await { trace!("Message future found, returning"); return; } match msg_result { Ok(msg) => { trace!("Message received from connector, sending to clients."); trace!("Message future not found, assuming server event."); match &msg { ButtplugCurrentSpecServerMessage::DeviceAdded(dev) => { trace!("Device added, updating map and sending to client"); let info = DeviceMessageInfo::from(dev); let device = self.create_client_device(&info); self .send_client_event(&ButtplugClientEvent::DeviceAdded(device)) .await; } ButtplugCurrentSpecServerMessage::DeviceRemoved(dev) => { if self.device_map.contains_key(&dev.device_index) { trace!("Device removed, updating map and sending to client"); let info = (*self.device_map.get(&dev.device_index).unwrap().device).clone(); // Grab a clone of the device let device = self.create_client_device(&info); // Then remove it from our storage map self.device_map.remove(&dev.device_index); self .send_client_event(&ButtplugClientEvent::DeviceRemoved(device)) .await; } else { error!("Received DeviceRemoved for non-existent device index"); } } ButtplugCurrentSpecServerMessage::ScanningFinished(_) => { trace!("Scanning finished event received, forwarding to client."); self .send_client_event(&ButtplugClientEvent::ScanningFinished) .await; } _ => error!("Cannot process message, dropping: {:?}", msg), } } Err(err) => { self .send_client_event(&ButtplugClientEvent::Error(err.into())) .await; } } } /// Send a message from the [ButtplugClient] to the [ButtplugClientConnector]. async fn send_message(&mut self, mut msg_fut: ButtplugClientMessageFuturePair) { trace!("Sending message to connector: {:?}", msg_fut.msg); self.sorter.register_future(&mut msg_fut); // TODO What happens if the connector isn't connected? self.connector.send(msg_fut.msg).await.unwrap(); } /// Parses message types from the client, returning false when disconnect /// happens. /// /// Takes different messages from the client and handles them: /// /// - For outbound messages to the server, sends them to the connector/server. /// - For disconnections, requests connector disconnect /// - For RequestDeviceList, builds a reply out of its own async fn parse_client_request(&mut self, msg: ButtplugClientRequest) -> bool { match msg { ButtplugClientRequest::Message(msg_fut) => { trace!("Sending message through connector: {:?}", msg_fut.msg); self.send_message(msg_fut).await; true } ButtplugClientRequest::Disconnect(state) => { trace!("Client requested disconnect"); state.set_reply(self.connector.disconnect().await); false } ButtplugClientRequest::HandleDeviceList(device_list) => { trace!("Device list received, updating map."); for d in &device_list.devices { if self.device_map.contains_key(&d.device_index) { continue; } let device = self.create_client_device(&d); self .send_client_event(&ButtplugClientEvent::DeviceAdded(device)) .await; } true } } } /// Runs the event loop, returning once either the client or connector drops. pub async fn run(&mut self) { debug!("Running client event loop."); // Once connected, wait for messages from either the client, the generated // client devices, or the connector, and send them the direction they're // supposed to go. let mut client_receiver = self.client_receiver.clone(); let mut connector_receiver = self.connector_receiver.clone(); let event_sender = self.event_sender.clone(); loop { select! { event = connector_receiver.next().fuse() => match event { None => { info!("Connector disconnected, exiting loop."); if event_sender.send(&ButtplugClientEvent::ServerDisconnect).await.is_err() { error!("Cannot send disconnection event."); } return; } Some(msg) => { self.parse_connector_message(msg).await; } }, client = client_receiver.next().fuse() => match client { None => { info!("Client disconnected, exiting loop."); if event_sender.send(&ButtplugClientEvent::ServerDisconnect).await.is_err() { error!("Cannot send disconnection event."); } return; } Some(msg) => { if !self.parse_client_request(msg).await { break; } } }, }; } if event_sender.send(&ButtplugClientEvent::ServerDisconnect).await.is_err() { error!("Cannot send disconnection event."); } debug!("Exiting client event loop."); } } /// The internal event loop for [super::ButtplugClient] connection and /// communication /// /// Created whenever a new [super::ButtplugClient] is created, the internal loop /// handles connection and communication with the server through the connector, /// and creation of events received from the server. /// /// The event_loop does a few different things during its lifetime: /// /// - It will listen for events from the connector, or messages from the client, /// routing them to their proper receivers until either server/client /// disconnects. /// /// - On disconnect, it will tear down, and cannot be used again. All clients /// and devices associated with the loop will be invalidated, and a new /// [super::ButtplugClient] must be created. pub(super) fn client_event_loop( connector: impl ButtplugConnector<ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage> + 'static, connector_receiver: Receiver<Result<ButtplugCurrentSpecServerMessage, ButtplugServerError>>, ) -> ( impl Future<Output = Result<(), ButtplugClientError>>, Arc<DashMap<u32, ButtplugClientDeviceInternal>>, Sender<ButtplugClientRequest>, // This needs clone internally, as the client will make multiple copies. impl Stream<Item = ButtplugClientEvent> + Clone, ) { trace!("Creating client event loop future."); let event_channel = BroadcastChannel::new(); let device_map = Arc::new(DashMap::new()); // Make sure we update the map, otherwise it won't exist. let device_map_clone = device_map.clone(); let (client_sender, client_receiver) = bounded(256); let client_sender_clone = client_sender.clone(); let event_loop_sender = event_channel.clone(); let mut event_loop = ButtplugClientEventLoop::new( connector, connector_receiver, event_loop_sender, client_sender, client_receiver, device_map, ); ( Box::pin(async move { info!("Starting client event loop."); event_loop .run() .instrument(tracing::info_span!("Client Event Loop")) .await; info!("Stopping client event loop."); Ok(()) }), device_map_clone, client_sender_clone, event_channel, ) }
// x86_64 pub const MEMORY_OFFSET: usize = 0; pub const KERNEL_OFFSET: usize = 0xffffff00_00000000; pub const PHYSICAL_MEMORY_OFFSET: usize = 0xffff8000_00000000; pub const KERNEL_HEAP_SIZE: usize = 16 * 1024 * 1024; // 16 MB pub const PAGE_SIZE: usize = 1 << 12; pub const KERNEL_PM4: usize = (KERNEL_OFFSET >> 39) & 0o777; pub const PHYSICAL_MEMORY_PM4: usize = (PHYSICAL_MEMORY_OFFSET >> 39) & 0o777;
pub trait Lazy { type Type; fn need(&self) -> &Self::Type; fn need_mut(&mut self) -> &mut Self::Type; } impl<T> Lazy for Option<T> { type Type = T; fn need(&self) -> &Self::Type { self.as_ref().unwrap() } fn need_mut(&mut self) -> &mut Self::Type { self.as_mut().unwrap() } }
#[macro_use] extern crate glium; extern crate specs; extern crate nalgebra; extern crate common; extern crate time; #[allow(dead_code)] mod renderer; #[allow(dead_code)] mod component; #[allow(dead_code)] mod state; use std::io::prelude::*; use std::net::{TcpStream, UdpSocket, SocketAddr}; use glium::backend::glutin_backend::GlutinFacade; use common::net::{Packet, RegPacket}; fn setup_display() -> GlutinFacade { use glium::DisplayBuild; glium::glutin::WindowBuilder::new().build_glium().unwrap() } fn main() { let display = setup_display(); let mut renderer = renderer::Renderer::new(&display); let mut global_state = state::GlobalState { delta: 0, prev_time: time::precise_time_ns() }; // Create ECS let mut planner : specs::Planner<state::GlobalState> = { use component::*; let mut w = specs::World::new(); w.register::<CompAABB>(); w.register::<CompBody>(); w.register::<CompColor>(); w.create_now().with(CompAABB([0.0, 0.0, 32.0, 32.0])) .with(CompColor([0.0, 1.0, 0.0, 1.0])) .with(CompBody{vel: [0.0, 0.0], acc: [0.5, 0.3], mass: 5.0, flags: BODY_GRAVITY}) .build(); specs::Planner::new(w) }; // Add systems planner.add_system::<renderer::SysRenderer>(renderer::SysRenderer::new(&renderer), "render", 0); let this_addr : SocketAddr = "127.0.0.1:0".parse().unwrap(); let server_udp_addr : SocketAddr = "127.0.0.1:12345".parse().unwrap(); let server_tcp_addr : SocketAddr = "127.0.0.1:12346".parse().unwrap(); { // Send some UDP data let socket = UdpSocket::bind(this_addr).unwrap(); socket.connect(server_udp_addr).unwrap(); // Connect to the server on localhost socket.send(&[65, 0]).unwrap(); } { // Connect to the TCP listener let mut stream = TcpStream::connect(server_tcp_addr).unwrap(); // Register us with the name 'John' let reg_packet = RegPacket::new("John"); stream.write(&reg_packet.serialise()).unwrap(); } loop { // Check input for ev in display.poll_events() { use glium::glutin::Event; match ev { Event::Closed => return, _ => () } } // Calculate frame delta, store in global state object global_state.delta = time::precise_time_ns() - global_state.prev_time; global_state.prev_time = time::precise_time_ns(); // Dispatch ECS with the global state object planner.dispatch(global_state.clone()); planner.wait(); // Receive any vertex data sent by the ECS renderer.recv_data(); // Render everything use glium::Surface; let mut frame = display.draw(); frame.clear_color(0.0, 0.0, 0.0, 1.0); renderer.render(&mut frame); frame.finish().unwrap(); } }
use super::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct TimePointSec { utc_seconds: u32, }
#[doc = "Reader of register TIMCCR"] pub type R = crate::R<u32, super::TIMCCR>; #[doc = "Writer for register TIMCCR"] pub type W = crate::W<u32, super::TIMCCR>; #[doc = "Register TIMCCR `reset()`'s with value 0"] impl crate::ResetValue for super::TIMCCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `UPDGAT`"] pub type UPDGAT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `UPDGAT`"] pub struct UPDGAT_W<'a> { w: &'a mut W, } impl<'a> UPDGAT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28); self.w } } #[doc = "Reader of field `PREEN`"] pub type PREEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PREEN`"] pub struct PREEN_W<'a> { w: &'a mut W, } impl<'a> PREEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `DACSYNC`"] pub type DACSYNC_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DACSYNC`"] pub struct DACSYNC_W<'a> { w: &'a mut W, } impl<'a> DACSYNC_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 25)) | (((value as u32) & 0x03) << 25); self.w } } #[doc = "Reader of field `MSTU`"] pub type MSTU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MSTU`"] pub struct MSTU_W<'a> { w: &'a mut W, } impl<'a> MSTU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `TEU`"] pub type TEU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TEU`"] pub struct TEU_W<'a> { w: &'a mut W, } impl<'a> TEU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `TDU`"] pub type TDU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TDU`"] pub struct TDU_W<'a> { w: &'a mut W, } impl<'a> TDU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `TCU`"] pub type TCU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TCU`"] pub struct TCU_W<'a> { w: &'a mut W, } impl<'a> TCU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `TBU`"] pub type TBU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TBU`"] pub struct TBU_W<'a> { w: &'a mut W, } impl<'a> TBU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `TxRSTU`"] pub type TXRSTU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TxRSTU`"] pub struct TXRSTU_W<'a> { w: &'a mut W, } impl<'a> TXRSTU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `TxREPU`"] pub type TXREPU_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TxREPU`"] pub struct TXREPU_W<'a> { w: &'a mut W, } impl<'a> TXREPU_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `DELCMP4`"] pub type DELCMP4_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DELCMP4`"] pub struct DELCMP4_W<'a> { w: &'a mut W, } impl<'a> DELCMP4_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14); self.w } } #[doc = "Reader of field `DELCMP2`"] pub type DELCMP2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DELCMP2`"] pub struct DELCMP2_W<'a> { w: &'a mut W, } impl<'a> DELCMP2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "Reader of field `SYNCSTRTx`"] pub type SYNCSTRTX_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNCSTRTx`"] pub struct SYNCSTRTX_W<'a> { w: &'a mut W, } impl<'a> SYNCSTRTX_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `SYNCRSTx`"] pub type SYNCRSTX_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNCRSTx`"] pub struct SYNCRSTX_W<'a> { w: &'a mut W, } impl<'a> SYNCRSTX_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `PSHPLL`"] pub type PSHPLL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PSHPLL`"] pub struct PSHPLL_W<'a> { w: &'a mut W, } impl<'a> PSHPLL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `HALF`"] pub type HALF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HALF`"] pub struct HALF_W<'a> { w: &'a mut W, } impl<'a> HALF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `RETRIG`"] pub type RETRIG_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RETRIG`"] pub struct RETRIG_W<'a> { w: &'a mut W, } impl<'a> RETRIG_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `CONT`"] pub type CONT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CONT`"] pub struct CONT_W<'a> { w: &'a mut W, } impl<'a> CONT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `CK_PSCx`"] pub type CK_PSCX_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CK_PSCx`"] pub struct CK_PSCX_W<'a> { w: &'a mut W, } impl<'a> CK_PSCX_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07); self.w } } impl R { #[doc = "Bits 28:31 - Update Gating"] #[inline(always)] pub fn updgat(&self) -> UPDGAT_R { UPDGAT_R::new(((self.bits >> 28) & 0x0f) as u8) } #[doc = "Bit 27 - Preload enable"] #[inline(always)] pub fn preen(&self) -> PREEN_R { PREEN_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bits 25:26 - AC Synchronization"] #[inline(always)] pub fn dacsync(&self) -> DACSYNC_R { DACSYNC_R::new(((self.bits >> 25) & 0x03) as u8) } #[doc = "Bit 24 - Master Timer update"] #[inline(always)] pub fn mstu(&self) -> MSTU_R { MSTU_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - TEU"] #[inline(always)] pub fn teu(&self) -> TEU_R { TEU_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - TDU"] #[inline(always)] pub fn tdu(&self) -> TDU_R { TDU_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - TCU"] #[inline(always)] pub fn tcu(&self) -> TCU_R { TCU_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - TBU"] #[inline(always)] pub fn tbu(&self) -> TBU_R { TBU_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 18 - Timerx reset update"] #[inline(always)] pub fn tx_rstu(&self) -> TXRSTU_R { TXRSTU_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - Timer x Repetition update"] #[inline(always)] pub fn tx_repu(&self) -> TXREPU_R { TXREPU_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bits 14:15 - Delayed CMP4 mode"] #[inline(always)] pub fn delcmp4(&self) -> DELCMP4_R { DELCMP4_R::new(((self.bits >> 14) & 0x03) as u8) } #[doc = "Bits 12:13 - Delayed CMP2 mode"] #[inline(always)] pub fn delcmp2(&self) -> DELCMP2_R { DELCMP2_R::new(((self.bits >> 12) & 0x03) as u8) } #[doc = "Bit 11 - Synchronization Starts Timer x"] #[inline(always)] pub fn syncstrtx(&self) -> SYNCSTRTX_R { SYNCSTRTX_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - Synchronization Resets Timer x"] #[inline(always)] pub fn syncrstx(&self) -> SYNCRSTX_R { SYNCRSTX_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 6 - Push-Pull mode enable"] #[inline(always)] pub fn pshpll(&self) -> PSHPLL_R { PSHPLL_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - Half mode enable"] #[inline(always)] pub fn half(&self) -> HALF_R { HALF_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - Re-triggerable mode"] #[inline(always)] pub fn retrig(&self) -> RETRIG_R { RETRIG_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - Continuous mode"] #[inline(always)] pub fn cont(&self) -> CONT_R { CONT_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bits 0:2 - HRTIM Timer x Clock prescaler"] #[inline(always)] pub fn ck_pscx(&self) -> CK_PSCX_R { CK_PSCX_R::new((self.bits & 0x07) as u8) } } impl W { #[doc = "Bits 28:31 - Update Gating"] #[inline(always)] pub fn updgat(&mut self) -> UPDGAT_W { UPDGAT_W { w: self } } #[doc = "Bit 27 - Preload enable"] #[inline(always)] pub fn preen(&mut self) -> PREEN_W { PREEN_W { w: self } } #[doc = "Bits 25:26 - AC Synchronization"] #[inline(always)] pub fn dacsync(&mut self) -> DACSYNC_W { DACSYNC_W { w: self } } #[doc = "Bit 24 - Master Timer update"] #[inline(always)] pub fn mstu(&mut self) -> MSTU_W { MSTU_W { w: self } } #[doc = "Bit 23 - TEU"] #[inline(always)] pub fn teu(&mut self) -> TEU_W { TEU_W { w: self } } #[doc = "Bit 22 - TDU"] #[inline(always)] pub fn tdu(&mut self) -> TDU_W { TDU_W { w: self } } #[doc = "Bit 21 - TCU"] #[inline(always)] pub fn tcu(&mut self) -> TCU_W { TCU_W { w: self } } #[doc = "Bit 20 - TBU"] #[inline(always)] pub fn tbu(&mut self) -> TBU_W { TBU_W { w: self } } #[doc = "Bit 18 - Timerx reset update"] #[inline(always)] pub fn tx_rstu(&mut self) -> TXRSTU_W { TXRSTU_W { w: self } } #[doc = "Bit 17 - Timer x Repetition update"] #[inline(always)] pub fn tx_repu(&mut self) -> TXREPU_W { TXREPU_W { w: self } } #[doc = "Bits 14:15 - Delayed CMP4 mode"] #[inline(always)] pub fn delcmp4(&mut self) -> DELCMP4_W { DELCMP4_W { w: self } } #[doc = "Bits 12:13 - Delayed CMP2 mode"] #[inline(always)] pub fn delcmp2(&mut self) -> DELCMP2_W { DELCMP2_W { w: self } } #[doc = "Bit 11 - Synchronization Starts Timer x"] #[inline(always)] pub fn syncstrtx(&mut self) -> SYNCSTRTX_W { SYNCSTRTX_W { w: self } } #[doc = "Bit 10 - Synchronization Resets Timer x"] #[inline(always)] pub fn syncrstx(&mut self) -> SYNCRSTX_W { SYNCRSTX_W { w: self } } #[doc = "Bit 6 - Push-Pull mode enable"] #[inline(always)] pub fn pshpll(&mut self) -> PSHPLL_W { PSHPLL_W { w: self } } #[doc = "Bit 5 - Half mode enable"] #[inline(always)] pub fn half(&mut self) -> HALF_W { HALF_W { w: self } } #[doc = "Bit 4 - Re-triggerable mode"] #[inline(always)] pub fn retrig(&mut self) -> RETRIG_W { RETRIG_W { w: self } } #[doc = "Bit 3 - Continuous mode"] #[inline(always)] pub fn cont(&mut self) -> CONT_W { CONT_W { w: self } } #[doc = "Bits 0:2 - HRTIM Timer x Clock prescaler"] #[inline(always)] pub fn ck_pscx(&mut self) -> CK_PSCX_W { CK_PSCX_W { w: self } } }
use anyhow::{bail, Result}; use assembler::assemble; use std::fs; fn main() -> Result<()> { let mut args = std::env::args().skip(1); let (input_path, output_path) = if let (Some(i), Some(o)) = (args.next(), args.next()) { (i, o) } else { bail!("Usage: <input_path> <output_path>"); }; let text = fs::read_to_string(input_path)?; if text == "" { bail!("Empty input file!"); } let bytecode = assemble(&text)?; fs::write(output_path, &bytecode)?; Ok(()) }
// Copyright 2022 Datafuse Labs. // // 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::str::FromStr; use common_meta_stoerr::MetaStorageError; use common_meta_types::LogId; /// Structured snapshot id used by meta service #[derive(Clone, Debug, PartialEq, Eq)] pub struct MetaSnapshotId { /// The last log id upto which a snapshot includes(inclusive). pub last_applied: Option<LogId>, /// A unique number to distinguish different snapshot with the same `last_applied. /// /// It is rare but possible a snapshot is built more than once with the same `last_applied`. pub uniq: u64, } impl MetaSnapshotId { pub(crate) fn new(last_applied: Option<LogId>, uniq: u64) -> Self { Self { last_applied, uniq } } } impl FromStr for MetaSnapshotId { type Err = MetaStorageError; fn from_str(s: &str) -> Result<Self, Self::Err> { // TODO: let _ = s; unimplemented!("do not need to parse snapshot id"); // let invalid = || { // MetaStorageError::SnapshotError(AnyError::error(format!("invalid snapshot_id: {}", s))) // }; // let mut segs = s.split('-'); // // let term = segs.next().ok_or_else(invalid)?; // let log_index = segs.next().ok_or_else(invalid)?; // let snapshot_index = segs.next().ok_or_else(invalid)?; // // let log_id = if term.is_empty() { // if log_index.is_empty() { // None // } else { // return Err(invalid()); // } // } else { // let t = term.parse::<u64>().map_err(|_e| invalid())?; // let i = log_index.parse::<LogIndex>().map_err(|_e| invalid())?; // Some(LogId::new(t, i)) // }; // // let snapshot_index = snapshot_index.parse::<u64>().map_err(|_e| invalid())?; // // Ok(Self { // last_applied: log_id, // uniq: snapshot_index, // }) } } impl ToString for MetaSnapshotId { fn to_string(&self) -> String { if let Some(last) = self.last_applied { format!("{}-{}-{}", last.leader_id, last.index, self.uniq) } else { format!("---{}", self.uniq) } } } #[cfg(test)] mod tests { use std::str::FromStr; use common_meta_types::new_log_id; use crate::state_machine::snapshot_id::MetaSnapshotId; #[test] fn test_meta_snapshot_id() -> anyhow::Result<()> { assert_eq!("--5", MetaSnapshotId::new(None, 5).to_string()); assert_eq!( "1-8-2-5", MetaSnapshotId::new(Some(new_log_id(1, 8, 2)), 5).to_string() ); assert_eq!( Ok(MetaSnapshotId::new(None, 5)), MetaSnapshotId::from_str("--5") ); assert_eq!( Ok(MetaSnapshotId::new(Some(new_log_id(1, 8, 2)), 5)), MetaSnapshotId::from_str("1-2-5") ); assert!(MetaSnapshotId::from_str("").is_err()); assert!(MetaSnapshotId::from_str("-").is_err()); assert!(MetaSnapshotId::from_str("--").is_err()); assert!(MetaSnapshotId::from_str("1--0").is_err()); assert!(MetaSnapshotId::from_str("-1-0").is_err()); assert!(MetaSnapshotId::from_str("x-1-0").is_err()); assert!(MetaSnapshotId::from_str("1-x-0").is_err()); assert!(MetaSnapshotId::from_str("1-1-x").is_err()); Ok(()) } }
mod xml_parse_lib; use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, Read}; use xml_parse_lib::*; fn main() { let mut ascii_map: HashMap<u8, char> = HashMap::new(); let mut tag_buff: Vec<char> = Vec::new(); ascii_map.insert(32, ' '); ascii_map.insert(33, '!'); ascii_map.insert(34, '"'); ascii_map.insert(35, '#'); ascii_map.insert(36, '$'); ascii_map.insert(37, '%'); ascii_map.insert(38, '&'); ascii_map.insert(39, '\''); ascii_map.insert(40, '('); ascii_map.insert(41, ')'); ascii_map.insert(42, '*'); ascii_map.insert(43, '+'); ascii_map.insert(44, ','); ascii_map.insert(45, '-'); ascii_map.insert(46, '.'); ascii_map.insert(47, '/'); ascii_map.insert(48, '0'); ascii_map.insert(49, '1'); ascii_map.insert(50, '2'); ascii_map.insert(51, '3'); ascii_map.insert(52, '4'); ascii_map.insert(53, '5'); ascii_map.insert(54, '6'); ascii_map.insert(55, '7'); ascii_map.insert(56, '8'); ascii_map.insert(57, '9'); ascii_map.insert(58, ':'); ascii_map.insert(59, ';'); ascii_map.insert(60, '<'); ascii_map.insert(61, '='); ascii_map.insert(62, '>'); ascii_map.insert(63, '?'); ascii_map.insert(64, '@'); ascii_map.insert(65, 'A'); ascii_map.insert(66, 'B'); ascii_map.insert(67, 'C'); ascii_map.insert(68, 'D'); ascii_map.insert(69, 'E'); ascii_map.insert(70, 'F'); ascii_map.insert(71, 'G'); ascii_map.insert(72, 'H'); ascii_map.insert(73, 'I'); ascii_map.insert(74, 'J'); ascii_map.insert(75, 'K'); ascii_map.insert(76, 'L'); ascii_map.insert(77, 'M'); ascii_map.insert(78, 'N'); ascii_map.insert(79, 'O'); ascii_map.insert(80, 'P'); ascii_map.insert(81, 'Q'); ascii_map.insert(82, 'R'); ascii_map.insert(83, 'S'); ascii_map.insert(84, 'T'); ascii_map.insert(85, 'U'); ascii_map.insert(86, 'V'); ascii_map.insert(87, 'W'); ascii_map.insert(88, 'X'); ascii_map.insert(89, 'Y'); ascii_map.insert(90, 'Z'); ascii_map.insert(91, '['); ascii_map.insert(92, '\''); ascii_map.insert(93, ']'); ascii_map.insert(94, '^'); ascii_map.insert(95, '_'); ascii_map.insert(96, '`'); ascii_map.insert(97, 'a'); ascii_map.insert(98, 'b'); ascii_map.insert(99, 'c'); ascii_map.insert(100, 'd'); ascii_map.insert(101, 'e'); ascii_map.insert(102, 'f'); ascii_map.insert(103, 'g'); ascii_map.insert(104, 'h'); ascii_map.insert(105, 'i'); ascii_map.insert(106, 'j'); ascii_map.insert(107, 'k'); ascii_map.insert(108, 'l'); ascii_map.insert(109, 'm'); ascii_map.insert(110, 'n'); ascii_map.insert(111, 'o'); ascii_map.insert(112, 'p'); ascii_map.insert(113, 'q'); ascii_map.insert(114, 'r'); ascii_map.insert(115, 's'); ascii_map.insert(116, 't'); ascii_map.insert(117, 'u'); ascii_map.insert(118, 'v'); ascii_map.insert(119, 'w'); ascii_map.insert(120, 'x'); ascii_map.insert(121, 'y'); ascii_map.insert(122, 'z'); ascii_map.insert(123, '{'); ascii_map.insert(124, '|'); ascii_map.insert(125, '}'); ascii_map.insert(126, '~'); let mut reader = BufReader::new( File::open("./tester_fmtted.xml").expect("open failed"), ); let mut buffer = [0; 16]; let mut flag_pop_name: bool = false; let mut rec_tag_name: bool = false; let mut rec_tag_data: bool = false; let mut tag_collector_string: String; let mut bytes_read: usize; let mut curr_byte = 1; let mut last_read = false; let mut tag_stack: Vec<String> = Vec::new(); 'read_file: loop { curr_byte = 0; bytes_read = reader.read(&mut buffer[..]).unwrap(); let chunk: Vec<char> = buffer .iter() .map(|byte| dec_to_ascii(*byte, &ascii_map)) .collect(); if bytes_read < 15 { last_read = true; } 'read_chunk: for byte in chunk.iter() { // BEGIN CRAPPY PARSING if *byte == '<' { if rec_tag_data { tag_collector_string = tag_buff.clone().into_iter().collect(); rec_tag_data = false; rec_tag_name = true; } } else if *byte == '/' { if rec_tag_name { flag_pop_name = true; } } else if *byte == '>' { if flag_pop_name { tag_collector_string = tag_buff.clone().into_iter().collect(); if tag_stack.contains(&tag_collector_string) { rec_tag_name = false; rec_tag_data = true; } } else { tag_collector_string = tag_buff.clone().into_iter().collect(); println!("pushing: {}", tag_collector_string); tag_stack.push(tag_collector_string); rec_tag_name = false; rec_tag_data = true; } } else { tag_buff.push(*byte); } // END CRAPPY PARSING curr_byte += 1; if curr_byte == bytes_read && last_read { break 'read_file; } } } }
use std::f32; use std::io; extern crate image; use image::{ImageBuffer, Rgba}; extern crate rand; use rand::prelude::*; mod math; use math::Vec3; fn clip(f: f32) -> f32 { if f > 1.0 { 1.0 } else if f < 0.0 { 0.0 } else { f } } fn color(r: f32, g: f32, b: f32, a: f32) -> Rgba<u8> { Rgba([ (clip(r) * 255.0) as u8, (clip(g) * 255.0) as u8, (clip(b) * 255.0) as u8, (clip(a) * 255.0) as u8 ]) } fn random_in_unit_sphere(rng: &mut ThreadRng) -> Vec3 { loop { let rand = Vec3::new(rng.gen(), rng.gen(), rng.gen()); let p = rand * 2.0 - Vec3::new(1.0, 1.0, 1.0); if p.squared_length() < 1.0 { return p } } } fn refract(v: Vec3, n: Vec3, ni_over_nt: f32) -> Option<Vec3> { let uv = v.norm(); let dt = uv.dot(n); let delta = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt); if delta > 0.0 { let refracted = (uv - n * dt) * ni_over_nt - n * delta.sqrt(); Some(refracted) } else { None } } fn schlick(cosine: f32, ref_idx: f32) -> f32 { let mut r0 = (1.0 - ref_idx) / (1.0 + ref_idx); r0 *= r0; r0 + (1.0 - r0) * (1.0 - cosine).powi(5) } #[derive(Clone, Copy, Debug)] enum Material { Diffuse(Vec3), Metal(Vec3, f32), Glass(f32) } struct HitRec { t: f32, p: Vec3, normal: Vec3, material: Material } impl HitRec { fn scatter(&self, in_ray: &Ray, rng: &mut ThreadRng) -> Option<(Ray, Vec3)> { match self.material { Material::Diffuse(albedo) => { let direction = self.normal + random_in_unit_sphere(rng); let scattered = Ray::new(self.p, direction); let attenuation = albedo; Some((scattered, attenuation)) } Material::Metal(albedo, fuzz) => { let reflected = in_ray.direction.norm().reflect(self.normal); let direction = reflected + random_in_unit_sphere(rng) * fuzz; let scattered = Ray::new(self.p, direction); let attenuation = albedo; if scattered.direction.dot(self.normal) > 0.0 { Some((scattered, attenuation)) } else { None } } Material::Glass(ri) => { let reflected = in_ray.direction.reflect(self.normal); let attenuation = Vec3::new(1.0, 1.0, 1.0); let outward_normal; let ni_over_nt; let cosine; let dot = in_ray.direction.dot(self.normal); if dot > 0.0 { outward_normal = -self.normal; ni_over_nt = ri; cosine = ri * dot / in_ray.direction.length(); } else { outward_normal = self.normal; ni_over_nt = 1.0 / ri; cosine = -dot / in_ray.direction.length(); } let scattered; let m_refract = refract(in_ray.direction, outward_normal, ni_over_nt); if let Some(refracted) = m_refract { let reflect_prob = schlick(cosine, ri); if rng.gen::<f32>() > reflect_prob { scattered = Ray::new(self.p, refracted) } else { scattered = Ray::new(self.p, reflected) } } else { scattered = Ray::new(self.p, reflected) } Some((scattered, attenuation)) } } } } trait Hittable { fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRec>; } #[derive(Debug)] struct Ray { origin: Vec3, direction: Vec3 } impl Ray { fn new(origin: Vec3, direction: Vec3) -> Self { Ray { origin, direction } } fn point_at(&self, t: f32) -> Vec3 { self.origin + self.direction * t } } fn cast_ray(mut ray: Ray, rng: &mut ThreadRng, target: &impl Hittable, depth: i32) -> Vec3 { let mut color = Vec3::new(1.0, 1.0, 1.0); for _ in 0..depth { if let Some(rec) = target.hit(&ray, 0.0001, f32::MAX) { if let Some((scattered, attenuation)) = rec.scatter(&ray, rng) { ray = scattered; color *= attenuation; } } else { let unit = ray.direction.norm(); let t = 0.5 * (unit.y + 1.0); let left = Vec3::new(1.0, 1.0, 1.0) * (1.0 - t); let right = Vec3::new(0.5, 0.7, 1.0) * t; return color * (left + right) } } Vec3::new(0.0, 0.0, 0.0) } struct Sphere { center: Vec3, radius: f32, material: Material } impl Sphere { fn new(center: Vec3, radius: f32, material: Material) -> Self { Sphere { center, radius, material } } } impl Hittable for Sphere { fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRec> { let oc = ray.origin - self.center; let a = ray.direction.squared_length(); let b = oc.dot(ray.direction); let c = oc.squared_length() - self.radius * self.radius; let delta = b * b - a * c; if delta < 0.0 { return None; } let mut solution = None; let left_solution = (-b - delta.sqrt()) / a; if left_solution < t_max && left_solution > t_min { solution = Some(left_solution); } if solution.is_none() { let right_solution = (-b + delta.sqrt()) / a; if right_solution < t_max && right_solution > t_min { solution = Some(right_solution); } } solution.map(|t| { let p = ray.point_at(t); let normal = (p - self.center) / self.radius; HitRec { t, p, normal, material: self.material } }) } } struct Hittables { data: Vec<Box<Hittable>> } impl Hittables { fn new() -> Self { Hittables { data: Vec::new() } } fn add<H: Hittable + 'static>(&mut self, object: H) { self.data.push(Box::new(object)) } } impl Hittable for Hittables { fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRec> { let mut res = None; let mut closest = t_max; for hittable in self.data.iter() { let next_hit = hittable.hit(ray, t_min, closest); if let Some(rec) = next_hit { closest = rec.t; res = Some(rec); } } res } } struct Camera { origin: Vec3, lower_left: Vec3, horizontal: Vec3, vertical: Vec3 } impl Camera { fn new(lookfrom: Vec3, lookat: Vec3, vup: Vec3, vfov: f32, aspect: f32) -> Self { let theta = vfov * f32::consts::PI / 180.0; let half_height = (theta / 2.0).tan(); let half_width = aspect * half_height; let origin = lookfrom; let w = (lookfrom - lookat).norm(); let u = vup.cross(w).norm(); let v = w.cross(u); let lower_left = origin - u * half_width - v * half_height - w; let horizontal = u * half_width * 2.0; let vertical = v * half_height * 2.0; Camera { origin, lower_left, horizontal, vertical } } fn get_ray(&self, u: f32, v: f32) -> Ray { let shift = self.horizontal * u + self.vertical * v; Ray::new(self.origin, self.lower_left + shift - self.origin) } } fn main() -> io::Result<()> { let mut hittables = Hittables::new(); hittables.add(Sphere::new( Vec3::new(0.0, 0.0, -1.0), 0.3, Material::Diffuse(Vec3::new(0.8, 0.3, 0.3)) )); hittables.add(Sphere::new( Vec3::new(0.0, -100.5, -1.0), 100.0, Material::Diffuse(Vec3::new(0.8, 0.8, 0.0)) )); hittables.add(Sphere::new( Vec3::new(1.0, 0.0, -1.0), 0.5, Material::Metal(Vec3::new(0.8, 0.6, 0.2), 0.3) )); hittables.add(Sphere::new( Vec3::new(-1.0, 0.0, -1.0), 0.5, Material::Glass(1.5) )); hittables.add(Sphere::new( Vec3::new(0.0, 3.0, -4.0), 2.0, Material::Metal(Vec3::new(0.5, 0.7, 0.5), 0.05) )); let camera = Camera::new( Vec3::new(0.0, 1.4, 4.0), Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 1.0, 0.0), 90.0, 2.0 ); let mut rng = rand::thread_rng(); let samples = 100; let img = ImageBuffer::from_fn(800, 400, |x, y| { let mut col = Vec3::new(0.0, 0.0, 0.0); for _ in 0..samples { let u = ((x as f32) + rng.gen::<f32>()) / 800.0; // We want the y coordinate to go up let v = 1.0 - ((y as f32) - rng.gen::<f32>()) / 400.0; col += cast_ray(camera.get_ray(u, v), &mut rng, &hittables, 50); } col /= samples as f32; col = Vec3::new(col.x.sqrt(), col.y.sqrt(), col.z.sqrt()); color(col.x, col.y, col.z, 1.0) }); img.save("image.png")?; Ok(()) }
fn task1(step: usize) -> i32 { let mut v = Vec::new(); v.push(0); let mut pos = 0 as usize; for i in 0..2017 { pos = (pos + step) % v.len() + 1; v.insert(pos, i + 1); } v[pos + 1] } fn task2(step: usize) -> i32 { let mut zeropos = 0; let mut res = 0; let mut pos = 0 as usize; let mut len = 1; for i in 0..50_000_000 { pos = (pos + step) % len + 1; if pos < zeropos { zeropos += 1; } else if pos == zeropos + 1 { res = i + 1; } len += 1; } res } fn main() { println!("{} {}", task1(329), task2(329)); }
// Copyright 2022 Datafuse Labs. // // 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::any::Any; use std::collections::VecDeque; use std::sync::Arc; use common_exception::Result; use common_expression::DataBlock; use common_expression::DataSchemaRef; use common_pipeline_sinks::Sink; use super::hash_join::ProbeState; use crate::pipelines::processors::port::InputPort; use crate::pipelines::processors::port::OutputPort; use crate::pipelines::processors::processor::Event; use crate::pipelines::processors::transforms::hash_join::HashJoinState; use crate::pipelines::processors::Processor; use crate::sessions::QueryContext; use crate::sessions::TableContext; pub struct SinkBuildHashTable { join_state: Arc<dyn HashJoinState>, } impl SinkBuildHashTable { pub fn try_create(join_state: Arc<dyn HashJoinState>) -> Result<Self> { join_state.attach()?; Ok(Self { join_state }) } } impl Sink for SinkBuildHashTable { const NAME: &'static str = "BuildHashTable"; fn on_finish(&mut self) -> Result<()> { self.join_state.detach() } fn interrupt(&self) { self.join_state.interrupt() } fn consume(&mut self, data_block: DataBlock) -> Result<()> { self.join_state.build(data_block) } } enum HashJoinStep { Build, Probe, } pub struct TransformHashJoinProbe { input_data: Option<DataBlock>, output_data_blocks: VecDeque<DataBlock>, input_port: Arc<InputPort>, output_port: Arc<OutputPort>, step: HashJoinStep, join_state: Arc<dyn HashJoinState>, probe_state: ProbeState, } impl TransformHashJoinProbe { pub fn create( ctx: Arc<QueryContext>, input_port: Arc<InputPort>, output_port: Arc<OutputPort>, join_state: Arc<dyn HashJoinState>, _output_schema: DataSchemaRef, ) -> Result<Box<dyn Processor>> { let default_block_size = ctx.get_settings().get_max_block_size()?; Ok(Box::new(TransformHashJoinProbe { input_data: None, output_data_blocks: VecDeque::new(), input_port, output_port, step: HashJoinStep::Build, join_state, probe_state: ProbeState::with_capacity(default_block_size as usize), })) } fn probe(&mut self, block: &DataBlock) -> Result<()> { self.probe_state.clear(); self.output_data_blocks .extend(self.join_state.probe(block, &mut self.probe_state)?); Ok(()) } } #[async_trait::async_trait] impl Processor for TransformHashJoinProbe { fn name(&self) -> String { "HashJoin".to_string() } fn as_any(&mut self) -> &mut dyn Any { self } fn event(&mut self) -> Result<Event> { match self.step { HashJoinStep::Build => Ok(Event::Async), HashJoinStep::Probe => { if self.output_port.is_finished() { self.input_port.finish(); return Ok(Event::Finished); } if !self.output_port.can_push() { self.input_port.set_not_need_data(); return Ok(Event::NeedConsume); } if !self.output_data_blocks.is_empty() { let data = self.output_data_blocks.pop_front().unwrap(); self.output_port.push_data(Ok(data)); return Ok(Event::NeedConsume); } if self.input_data.is_some() { return Ok(Event::Sync); } if self.input_port.has_data() { let data = self.input_port.pull_data().unwrap()?; self.input_data = Some(data); return Ok(Event::Sync); } if self.input_port.is_finished() { self.output_port.finish(); return Ok(Event::Finished); } self.input_port.set_need_data(); Ok(Event::NeedData) } } } fn interrupt(&self) { self.join_state.interrupt() } fn process(&mut self) -> Result<()> { match self.step { HashJoinStep::Build => Ok(()), HashJoinStep::Probe => { if let Some(data) = self.input_data.take() { let data = data.convert_to_full(); self.probe(&data)?; } Ok(()) } } } async fn async_process(&mut self) -> Result<()> { if let HashJoinStep::Build = &self.step { self.join_state.wait_finish().await?; self.step = HashJoinStep::Probe; } Ok(()) } }
use std::collections::{ HashMap, VecDeque, }; use std::hash::Hash; use std::io::{ Cursor, Read, Result as IOResult, Seek, SeekFrom, }; use std::sync::atomic::{ AtomicBool, AtomicU32, Ordering, }; use std::sync::{ Arc, Condvar, Mutex, RwLock, Weak, }; use crossbeam_channel::{ unbounded, Receiver, Sender, }; use legion::World; use log::{ error, trace, warn, }; use sourcerenderer_core::graphics::TextureInfo; use sourcerenderer_core::platform::Platform; use sourcerenderer_core::{ graphics, Vec4, }; use crate::math::BoundingBox; struct AssetLoadRequest { path: String, asset_type: AssetType, progress: Arc<AssetLoaderProgress>, priority: AssetLoadPriority, } pub struct LoadedAsset { pub path: String, pub asset: Asset, pub priority: AssetLoadPriority, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum AssetType { Texture, Model, Mesh, Material, Sound, Level, Chunk, Container, Shader, } #[derive(Clone)] pub struct MeshRange { pub start: u32, pub count: u32, } pub struct Texture { pub info: TextureInfo, pub data: Box<[Box<[u8]>]>, } pub struct Mesh { pub indices: Option<Box<[u8]>>, pub vertices: Box<[u8]>, pub parts: Box<[MeshRange]>, pub bounding_box: Option<BoundingBox>, pub vertex_count: u32, } #[derive(Clone)] pub struct Model { pub mesh_path: String, pub material_paths: Vec<String>, } #[derive(Clone)] pub struct Material { pub shader_name: String, pub properties: HashMap<String, MaterialValue>, } impl Material { pub fn new_pbr(albedo_texture_path: &str, roughness: f32, metalness: f32) -> Self { let mut props = HashMap::new(); props.insert( "albedo".to_string(), MaterialValue::Texture(albedo_texture_path.to_string()), ); props.insert("roughness".to_string(), MaterialValue::Float(roughness)); props.insert("metalness".to_string(), MaterialValue::Float(metalness)); Self { shader_name: "pbr".to_string(), properties: props, } } pub fn new_pbr_color(albedo: Vec4, roughness: f32, metalness: f32) -> Self { let mut props = HashMap::new(); props.insert("albedo".to_string(), MaterialValue::Vec4(albedo)); props.insert("roughness".to_string(), MaterialValue::Float(roughness)); props.insert("metalness".to_string(), MaterialValue::Float(metalness)); Self { shader_name: "pbr".to_string(), properties: props, } } } #[derive(Clone)] pub enum MaterialValue { Texture(String), Float(f32), Vec4(Vec4), } pub struct AssetFile { pub path: String, pub data: Cursor<Box<[u8]>>, } impl Read for AssetFile { fn read(&mut self, buf: &mut [u8]) -> IOResult<usize> { self.data.read(buf) } } impl Seek for AssetFile { fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> { self.data.seek(pos) } } pub trait AssetContainer: Send + Sync { fn contains(&self, path: &str) -> bool { self.load(path).is_some() } fn load(&self, path: &str) -> Option<AssetFile>; } pub struct AssetLoaderProgress { expected: AtomicU32, finished: AtomicU32, } impl AssetLoaderProgress { pub fn is_done(&self) -> bool { self.finished.load(Ordering::SeqCst) == self.expected.load(Ordering::SeqCst) } } pub enum AssetLoaderResult { None, Level(World), } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum AssetLoadPriority { High, Normal, Low, } pub trait AssetLoader<P: Platform>: Send + Sync { fn matches(&self, file: &mut AssetFile) -> bool; fn load( &self, file: AssetFile, manager: &Arc<AssetManager<P>>, priority: AssetLoadPriority, progress: &Arc<AssetLoaderProgress>, ) -> Result<AssetLoaderResult, ()>; } pub enum Asset { Texture(Texture), Mesh(Mesh), Model(Model), Sound, Material(Material), Shader(Box<[u8]>), } pub struct AssetManager<P: Platform> { device: Arc<<P::GraphicsBackend as graphics::Backend>::Device>, inner: Mutex<AssetManagerInner>, containers: RwLock<Vec<Box<dyn AssetContainer>>>, loaders: RwLock<Vec<Box<dyn AssetLoader<P>>>>, renderer_sender: Sender<LoadedAsset>, renderer_receiver: Receiver<LoadedAsset>, cond_var: Arc<Condvar>, is_running: AtomicBool, } struct AssetManagerInner { load_queue: VecDeque<AssetLoadRequest>, low_priority_load_queue: VecDeque<AssetLoadRequest>, high_priority_load_queue: VecDeque<AssetLoadRequest>, requested_assets: HashMap<String, AssetType>, loaded_assets: HashMap<String, AssetType>, } impl<P: Platform> AssetManager<P> { pub fn new( platform: &P, device: &Arc<<P::GraphicsBackend as graphics::Backend>::Device>, ) -> Arc<Self> { let (renderer_sender, renderer_receiver) = unbounded(); let cond_var = Arc::new(Condvar::new()); let manager = Arc::new(Self { device: device.clone(), inner: Mutex::new(AssetManagerInner { load_queue: VecDeque::new(), low_priority_load_queue: VecDeque::new(), high_priority_load_queue: VecDeque::new(), loaded_assets: HashMap::new(), requested_assets: HashMap::new(), }), loaders: RwLock::new(Vec::new()), containers: RwLock::new(Vec::new()), renderer_sender, renderer_receiver, cond_var, is_running: AtomicBool::new(true), }); let thread_count = 4; for _ in 0..thread_count { let c_manager = Arc::downgrade(&manager); platform.start_thread("AssetManagerThread", move || { asset_manager_thread_fn(c_manager) }); } manager } pub fn graphics_device(&self) -> &Arc<<P::GraphicsBackend as graphics::Backend>::Device> { &self.device } pub fn add_mesh( &self, path: &str, vertex_buffer_data: Box<[u8]>, vertex_count: u32, index_buffer_data: Box<[u8]>, parts: Box<[MeshRange]>, bounding_box: Option<BoundingBox>, ) { assert_ne!(vertex_count, 0); let mesh = Mesh { vertices: vertex_buffer_data, indices: if !index_buffer_data.is_empty() { Some(index_buffer_data) } else { None }, parts, bounding_box, vertex_count, }; self.add_asset(path, Asset::Mesh(mesh), AssetLoadPriority::Normal); } pub fn add_material(&self, path: &str, albedo: &str, roughness: f32, metalness: f32) { let material = Material::new_pbr(albedo, roughness, metalness); self.add_asset(path, Asset::Material(material), AssetLoadPriority::Normal); } pub fn add_material_color(&self, path: &str, albedo: Vec4, roughness: f32, metalness: f32) { let material = Material::new_pbr_color(albedo, roughness, metalness); self.add_asset(path, Asset::Material(material), AssetLoadPriority::Normal); } pub fn add_model(&self, path: &str, mesh_path: &str, material_paths: &[&str]) { let model = Model { mesh_path: mesh_path.to_string(), material_paths: material_paths.iter().map(|mat| (*mat).to_owned()).collect(), }; self.add_asset(path, Asset::Model(model), AssetLoadPriority::Normal); } pub fn add_texture(&self, path: &str, info: &TextureInfo, texture_data: Box<[u8]>) { self.add_asset( path, Asset::Texture(Texture { info: info.clone(), data: Box::new([texture_data.to_vec().into_boxed_slice()]), }), AssetLoadPriority::Normal, ); } pub fn add_container(&self, container: Box<dyn AssetContainer>) { self.add_container_with_progress(container, None) } pub fn add_container_with_progress( &self, container: Box<dyn AssetContainer>, progress: Option<&Arc<AssetLoaderProgress>>, ) { let mut containers = self.containers.write().unwrap(); containers.push(container); if let Some(progress) = progress { progress.finished.fetch_add(1, Ordering::SeqCst); } } pub fn add_loader(&self, loader: Box<dyn AssetLoader<P>>) { let mut loaders = self.loaders.write().unwrap(); loaders.push(loader); } pub fn add_asset(&self, path: &str, asset: Asset, priority: AssetLoadPriority) { self.add_asset_with_progress(path, asset, None, priority) } pub fn add_asset_with_progress( &self, path: &str, asset: Asset, progress: Option<&Arc<AssetLoaderProgress>>, priority: AssetLoadPriority, ) { let asset_type = match &asset { Asset::Texture(_) => AssetType::Texture, Asset::Material(_) => AssetType::Material, Asset::Mesh(_) => AssetType::Mesh, Asset::Model(_) => AssetType::Model, Asset::Sound => AssetType::Sound, Asset::Shader(_) => AssetType::Shader, }; { let mut inner = self.inner.lock().unwrap(); inner.loaded_assets.insert(path.to_string(), asset_type); inner.requested_assets.remove(path); } if let Some(progress) = progress { progress.finished.fetch_add(1, Ordering::SeqCst); } match asset { Asset::Material(material) => { self.renderer_sender .send(LoadedAsset { asset: Asset::Material(material), path: path.to_owned(), priority, }) .unwrap(); } Asset::Mesh(mesh) => { assert_ne!(mesh.vertex_count, 0); self.renderer_sender .send(LoadedAsset { asset: Asset::Mesh(mesh), path: path.to_owned(), priority, }) .unwrap(); } Asset::Texture(texture) => { self.renderer_sender .send(LoadedAsset { asset: Asset::Texture(texture), path: path.to_owned(), priority, }) .unwrap(); } Asset::Model(model) => { self.renderer_sender .send(LoadedAsset { asset: Asset::Model(model), path: path.to_owned(), priority, }) .unwrap(); } Asset::Shader(shader_bytecode) => { self.renderer_sender .send(LoadedAsset { asset: Asset::Shader(shader_bytecode), path: path.to_owned(), priority, }) .unwrap(); } _ => unimplemented!(), } } pub fn request_asset_update(&self, path: &str) { log::info!("Reloading: {}", path); let asset_type = { let inner = self.inner.lock().unwrap(); inner.loaded_assets.get(path).copied() }; if let Some(asset_type) = asset_type { self.request_asset_internal(path, asset_type, AssetLoadPriority::Low, None, true); } else { warn!("Cannot reload unloaded asset {}", path); } } pub fn request_asset( &self, path: &str, asset_type: AssetType, priority: AssetLoadPriority, ) -> Arc<AssetLoaderProgress> { self.request_asset_internal(path, asset_type, priority, None, false) } pub fn request_asset_with_progress( &self, path: &str, asset_type: AssetType, priority: AssetLoadPriority, progress: &Arc<AssetLoaderProgress>, ) -> Arc<AssetLoaderProgress> { self.request_asset_internal(path, asset_type, priority, Some(progress), false) } fn request_asset_internal( &self, path: &str, asset_type: AssetType, priority: AssetLoadPriority, progress: Option<&Arc<AssetLoaderProgress>>, refresh: bool, ) -> Arc<AssetLoaderProgress> { let progress = progress.map_or_else( || { Arc::new(AssetLoaderProgress { expected: AtomicU32::new(0), finished: AtomicU32::new(0), }) }, |p| p.clone(), ); progress.expected.fetch_add(1, Ordering::SeqCst); { let mut inner = self.inner.lock().unwrap(); if (inner.loaded_assets.contains_key(path) && !refresh) || inner.requested_assets.contains_key(path) { progress.finished.fetch_add(1, Ordering::SeqCst); return progress; } inner.requested_assets.insert(path.to_owned(), asset_type); let queue = match priority { AssetLoadPriority::High => &mut inner.high_priority_load_queue, AssetLoadPriority::Normal => &mut inner.load_queue, AssetLoadPriority::Low => &mut inner.low_priority_load_queue, }; queue.push_back(AssetLoadRequest { asset_type, path: path.to_owned(), progress: progress.clone(), priority, }); } self.cond_var.notify_one(); progress } pub fn load_level(self: &Arc<Self>, path: &str) -> Option<World> { let file_opt = self.load_file(path); if file_opt.is_none() { error!("Could not load file: {:?}", path); return None; } let mut file = file_opt.unwrap(); let loaders = self.loaders.read().unwrap(); let loader_opt = AssetManager::find_loader(&mut file, loaders.as_ref()); if loader_opt.is_none() { error!("Could not find loader for file: {:?}", path); return None; } let progress = Arc::new(AssetLoaderProgress { expected: AtomicU32::new(1), finished: AtomicU32::new(0), }); let loader = loader_opt.unwrap(); let assets_opt = loader.load(file, self, AssetLoadPriority::Normal, &progress); if assets_opt.is_err() { error!("Could not load file: {:?}", path); return None; } let result = assets_opt.unwrap(); let level = match result { AssetLoaderResult::Level(level) => Some(level), _ => None, }; progress.finished.fetch_add(1, Ordering::SeqCst); level } pub fn load_file(&self, path: &str) -> Option<AssetFile> { let containers = self.containers.read().unwrap(); let mut file_opt: Option<AssetFile> = None; for container in containers.iter().rev() { let container_file_opt = container.load(path); if container_file_opt.is_some() { file_opt = container_file_opt; break; } } if file_opt.is_none() { error!("Could not find file: {:?}", path); { let mut inner = self.inner.lock().unwrap(); inner.requested_assets.remove(path); } } file_opt } pub fn file_exists(&self, path: &str) -> bool { let containers = self.containers.read().unwrap(); for container in containers.iter() { if container.contains(path) { return true; } } false } fn find_loader<'a>( file: &mut AssetFile, loaders: &'a [Box<dyn AssetLoader<P>>], ) -> Option<&'a dyn AssetLoader<P>> { let start = file .seek(SeekFrom::Current(0)) .unwrap_or_else(|_| panic!("Failed to read file: {:?}", file.path)); let loader_opt = loaders.iter().find(|loader| { let loader_matches = loader.matches(file); file.seek(SeekFrom::Start(start)).unwrap(); loader_matches }); loader_opt.map(|b| b.as_ref()) } fn load_asset( self: &Arc<Self>, mut file: AssetFile, priority: AssetLoadPriority, progress: &Arc<AssetLoaderProgress>, ) { let path = file.path.clone(); let loaders = self.loaders.read().unwrap(); let loader_opt = AssetManager::find_loader(&mut file, loaders.as_ref()); if loader_opt.is_none() { progress.finished.fetch_add(1, Ordering::SeqCst); { let mut inner = self.inner.lock().unwrap(); inner.requested_assets.remove(&path); } error!("Could not find loader for file: {:?}", path.as_str()); return; } let loader = loader_opt.unwrap(); let assets_opt = loader.load(file, self, priority, progress); if assets_opt.is_err() { progress.finished.fetch_add(1, Ordering::SeqCst); { let mut inner = self.inner.lock().unwrap(); inner.requested_assets.remove(&path); } error!("Could not load file: {:?}", path.as_str()); } } pub fn has_open_renderer_assets(&self) -> bool { !self.renderer_receiver.is_empty() } pub fn receive_render_asset(&self) -> Option<LoadedAsset> { self.renderer_receiver.try_recv().ok() } pub fn notify_loaded(&self, path: &str) { let mut inner = self.inner.lock().unwrap(); if let Some(asset_type) = inner.requested_assets.remove(path) { inner.loaded_assets.insert(path.to_string(), asset_type); } } pub fn notify_unloaded(&self, path: &str) { let mut inner = self.inner.lock().unwrap(); inner.loaded_assets.remove(path); } pub fn stop(&self) { trace!("Stopping asset manager"); let was_running = self.is_running.swap(false, Ordering::SeqCst); if !was_running { return; } self.cond_var.notify_all(); } } fn asset_manager_thread_fn<P: Platform>(asset_manager: Weak<AssetManager<P>>) { trace!("Started asset manager thread"); let cond_var = { let mgr_opt = asset_manager.upgrade(); if mgr_opt.is_none() { return; } let mgr = mgr_opt.unwrap(); mgr.cond_var.clone() }; 'asset_loop: loop { let mgr_opt = asset_manager.upgrade(); if mgr_opt.is_none() { break 'asset_loop; } let mgr = mgr_opt.unwrap(); if !mgr.is_running.load(Ordering::SeqCst) { break 'asset_loop; } let request = { let mut inner = mgr.inner.lock().unwrap(); let mut request_opt = inner.high_priority_load_queue.pop_front(); request_opt = request_opt.or_else(|| inner.load_queue.pop_front()); request_opt = request_opt.or_else(|| inner.low_priority_load_queue.pop_front()); while request_opt.is_none() { if !mgr.is_running.load(Ordering::SeqCst) { break 'asset_loop; } inner = cond_var.wait(inner).unwrap(); request_opt = inner.load_queue.pop_front(); request_opt = request_opt.or_else(|| inner.load_queue.pop_front()); request_opt = request_opt.or_else(|| inner.low_priority_load_queue.pop_front()); } match request_opt { Some(request) => request, None => continue 'asset_loop, } }; { let file_opt = mgr.load_file(&request.path); if file_opt.is_none() { request.progress.finished.fetch_add(1, Ordering::SeqCst); continue 'asset_loop; } let file = file_opt.unwrap(); mgr.load_asset(file, request.priority, &request.progress); } } trace!("Stopped asset manager thread"); }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qmenubar.h // dst-file: /src/widgets/qmenubar.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qwidget::*; // 773 use std::ops::Deref; use super::super::core::qstring::*; // 771 use super::qaction::*; // 773 // use super::qplatformmenubar::*; // 775 use super::qmenu::*; // 773 use super::super::core::qsize::*; // 771 use super::super::core::qpoint::*; // 771 use super::super::core::qobjectdefs::*; // 771 use super::super::gui::qicon::*; // 771 use super::super::core::qrect::*; // 771 use super::super::core::qobject::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QMenuBar_Class_Size() -> c_int; // proto: QAction * QMenuBar::addAction(const QString & text); fn C_ZN8QMenuBar9addActionERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QPlatformMenuBar * QMenuBar::platformMenuBar(); fn C_ZN8QMenuBar15platformMenuBarEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QMenuBar::setNativeMenuBar(bool nativeMenuBar); fn C_ZN8QMenuBar16setNativeMenuBarEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QMenuBar::~QMenuBar(); fn C_ZN8QMenuBarD2Ev(qthis: u64 /* *mut c_void*/); // proto: QAction * QMenuBar::addMenu(QMenu * menu); fn C_ZN8QMenuBar7addMenuEP5QMenu(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QSize QMenuBar::sizeHint(); fn C_ZNK8QMenuBar8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QAction * QMenuBar::actionAt(const QPoint & ); fn C_ZNK8QMenuBar8actionAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: const QMetaObject * QMenuBar::metaObject(); fn C_ZNK8QMenuBar10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QMenuBar::isNativeMenuBar(); fn C_ZNK8QMenuBar15isNativeMenuBarEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QAction * QMenuBar::insertSeparator(QAction * before); fn C_ZN8QMenuBar15insertSeparatorEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QAction * QMenuBar::addSeparator(); fn C_ZN8QMenuBar12addSeparatorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QSize QMenuBar::minimumSizeHint(); fn C_ZNK8QMenuBar15minimumSizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QMenuBar::isDefaultUp(); fn C_ZNK8QMenuBar11isDefaultUpEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QMenuBar::QMenuBar(QWidget * parent); fn C_ZN8QMenuBarC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: void QMenuBar::setActiveAction(QAction * action); fn C_ZN8QMenuBar15setActiveActionEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QMenuBar::clear(); fn C_ZN8QMenuBar5clearEv(qthis: u64 /* *mut c_void*/); // proto: QAction * QMenuBar::activeAction(); fn C_ZNK8QMenuBar12activeActionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QMenu * QMenuBar::addMenu(const QIcon & icon, const QString & title); fn C_ZN8QMenuBar7addMenuERK5QIconRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: QMenu * QMenuBar::addMenu(const QString & title); fn C_ZN8QMenuBar7addMenuERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QRect QMenuBar::actionGeometry(QAction * ); fn C_ZNK8QMenuBar14actionGeometryEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QAction * QMenuBar::insertMenu(QAction * before, QMenu * menu); fn C_ZN8QMenuBar10insertMenuEP7QActionP5QMenu(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: void QMenuBar::setDefaultUp(bool ); fn C_ZN8QMenuBar12setDefaultUpEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QMenuBar::setVisible(bool visible); fn C_ZN8QMenuBar10setVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QAction * QMenuBar::addAction(const QString & text, const QObject * receiver, const char * member); fn C_ZN8QMenuBar9addActionERK7QStringPK7QObjectPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_char) -> *mut c_void; // proto: int QMenuBar::heightForWidth(int ); fn C_ZNK8QMenuBar14heightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; fn QMenuBar_SlotProxy_connect__ZN8QMenuBar9triggeredEP7QAction(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QMenuBar_SlotProxy_connect__ZN8QMenuBar7hoveredEP7QAction(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QMenuBar)=1 #[derive(Default)] pub struct QMenuBar { qbase: QWidget, pub qclsinst: u64 /* *mut c_void*/, pub _hovered: QMenuBar_hovered_signal, pub _triggered: QMenuBar_triggered_signal, } impl /*struct*/ QMenuBar { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMenuBar { return QMenuBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QMenuBar { type Target = QWidget; fn deref(&self) -> &QWidget { return & self.qbase; } } impl AsRef<QWidget> for QMenuBar { fn as_ref(& self) -> & QWidget { return & self.qbase; } } // proto: QAction * QMenuBar::addAction(const QString & text); impl /*struct*/ QMenuBar { pub fn addAction<RetType, T: QMenuBar_addAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addAction(self); // return 1; } } pub trait QMenuBar_addAction<RetType> { fn addAction(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::addAction(const QString & text); impl<'a> /*trait*/ QMenuBar_addAction<QAction> for (&'a QString) { fn addAction(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar9addActionERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QMenuBar9addActionERK7QString(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPlatformMenuBar * QMenuBar::platformMenuBar(); impl /*struct*/ QMenuBar { pub fn platformMenuBar<RetType, T: QMenuBar_platformMenuBar<RetType>>(& self, overload_args: T) -> RetType { return overload_args.platformMenuBar(self); // return 1; } } pub trait QMenuBar_platformMenuBar<RetType> { fn platformMenuBar(self , rsthis: & QMenuBar) -> RetType; } // proto: QPlatformMenuBar * QMenuBar::platformMenuBar(); impl<'a> /*trait*/ QMenuBar_platformMenuBar<u64> for () { fn platformMenuBar(self , rsthis: & QMenuBar) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar15platformMenuBarEv()}; let mut ret = unsafe {C_ZN8QMenuBar15platformMenuBarEv(rsthis.qclsinst)}; return ret as u64; // 4 // return 1; } } // proto: void QMenuBar::setNativeMenuBar(bool nativeMenuBar); impl /*struct*/ QMenuBar { pub fn setNativeMenuBar<RetType, T: QMenuBar_setNativeMenuBar<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setNativeMenuBar(self); // return 1; } } pub trait QMenuBar_setNativeMenuBar<RetType> { fn setNativeMenuBar(self , rsthis: & QMenuBar) -> RetType; } // proto: void QMenuBar::setNativeMenuBar(bool nativeMenuBar); impl<'a> /*trait*/ QMenuBar_setNativeMenuBar<()> for (i8) { fn setNativeMenuBar(self , rsthis: & QMenuBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar16setNativeMenuBarEb()}; let arg0 = self as c_char; unsafe {C_ZN8QMenuBar16setNativeMenuBarEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMenuBar::~QMenuBar(); impl /*struct*/ QMenuBar { pub fn free<RetType, T: QMenuBar_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QMenuBar_free<RetType> { fn free(self , rsthis: & QMenuBar) -> RetType; } // proto: void QMenuBar::~QMenuBar(); impl<'a> /*trait*/ QMenuBar_free<()> for () { fn free(self , rsthis: & QMenuBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBarD2Ev()}; unsafe {C_ZN8QMenuBarD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QAction * QMenuBar::addMenu(QMenu * menu); impl /*struct*/ QMenuBar { pub fn addMenu<RetType, T: QMenuBar_addMenu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addMenu(self); // return 1; } } pub trait QMenuBar_addMenu<RetType> { fn addMenu(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::addMenu(QMenu * menu); impl<'a> /*trait*/ QMenuBar_addMenu<QAction> for (&'a QMenu) { fn addMenu(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar7addMenuEP5QMenu()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QMenuBar7addMenuEP5QMenu(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QSize QMenuBar::sizeHint(); impl /*struct*/ QMenuBar { pub fn sizeHint<RetType, T: QMenuBar_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QMenuBar_sizeHint<RetType> { fn sizeHint(self , rsthis: & QMenuBar) -> RetType; } // proto: QSize QMenuBar::sizeHint(); impl<'a> /*trait*/ QMenuBar_sizeHint<QSize> for () { fn sizeHint(self , rsthis: & QMenuBar) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar8sizeHintEv()}; let mut ret = unsafe {C_ZNK8QMenuBar8sizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QMenuBar::actionAt(const QPoint & ); impl /*struct*/ QMenuBar { pub fn actionAt<RetType, T: QMenuBar_actionAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.actionAt(self); // return 1; } } pub trait QMenuBar_actionAt<RetType> { fn actionAt(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::actionAt(const QPoint & ); impl<'a> /*trait*/ QMenuBar_actionAt<QAction> for (&'a QPoint) { fn actionAt(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar8actionAtERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK8QMenuBar8actionAtERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QMenuBar::metaObject(); impl /*struct*/ QMenuBar { pub fn metaObject<RetType, T: QMenuBar_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QMenuBar_metaObject<RetType> { fn metaObject(self , rsthis: & QMenuBar) -> RetType; } // proto: const QMetaObject * QMenuBar::metaObject(); impl<'a> /*trait*/ QMenuBar_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QMenuBar) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar10metaObjectEv()}; let mut ret = unsafe {C_ZNK8QMenuBar10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QMenuBar::isNativeMenuBar(); impl /*struct*/ QMenuBar { pub fn isNativeMenuBar<RetType, T: QMenuBar_isNativeMenuBar<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isNativeMenuBar(self); // return 1; } } pub trait QMenuBar_isNativeMenuBar<RetType> { fn isNativeMenuBar(self , rsthis: & QMenuBar) -> RetType; } // proto: bool QMenuBar::isNativeMenuBar(); impl<'a> /*trait*/ QMenuBar_isNativeMenuBar<i8> for () { fn isNativeMenuBar(self , rsthis: & QMenuBar) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar15isNativeMenuBarEv()}; let mut ret = unsafe {C_ZNK8QMenuBar15isNativeMenuBarEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QAction * QMenuBar::insertSeparator(QAction * before); impl /*struct*/ QMenuBar { pub fn insertSeparator<RetType, T: QMenuBar_insertSeparator<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertSeparator(self); // return 1; } } pub trait QMenuBar_insertSeparator<RetType> { fn insertSeparator(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::insertSeparator(QAction * before); impl<'a> /*trait*/ QMenuBar_insertSeparator<QAction> for (&'a QAction) { fn insertSeparator(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar15insertSeparatorEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QMenuBar15insertSeparatorEP7QAction(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QMenuBar::addSeparator(); impl /*struct*/ QMenuBar { pub fn addSeparator<RetType, T: QMenuBar_addSeparator<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addSeparator(self); // return 1; } } pub trait QMenuBar_addSeparator<RetType> { fn addSeparator(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::addSeparator(); impl<'a> /*trait*/ QMenuBar_addSeparator<QAction> for () { fn addSeparator(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar12addSeparatorEv()}; let mut ret = unsafe {C_ZN8QMenuBar12addSeparatorEv(rsthis.qclsinst)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QSize QMenuBar::minimumSizeHint(); impl /*struct*/ QMenuBar { pub fn minimumSizeHint<RetType, T: QMenuBar_minimumSizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumSizeHint(self); // return 1; } } pub trait QMenuBar_minimumSizeHint<RetType> { fn minimumSizeHint(self , rsthis: & QMenuBar) -> RetType; } // proto: QSize QMenuBar::minimumSizeHint(); impl<'a> /*trait*/ QMenuBar_minimumSizeHint<QSize> for () { fn minimumSizeHint(self , rsthis: & QMenuBar) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar15minimumSizeHintEv()}; let mut ret = unsafe {C_ZNK8QMenuBar15minimumSizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QMenuBar::isDefaultUp(); impl /*struct*/ QMenuBar { pub fn isDefaultUp<RetType, T: QMenuBar_isDefaultUp<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isDefaultUp(self); // return 1; } } pub trait QMenuBar_isDefaultUp<RetType> { fn isDefaultUp(self , rsthis: & QMenuBar) -> RetType; } // proto: bool QMenuBar::isDefaultUp(); impl<'a> /*trait*/ QMenuBar_isDefaultUp<i8> for () { fn isDefaultUp(self , rsthis: & QMenuBar) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar11isDefaultUpEv()}; let mut ret = unsafe {C_ZNK8QMenuBar11isDefaultUpEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QMenuBar::QMenuBar(QWidget * parent); impl /*struct*/ QMenuBar { pub fn new<T: QMenuBar_new>(value: T) -> QMenuBar { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QMenuBar_new { fn new(self) -> QMenuBar; } // proto: void QMenuBar::QMenuBar(QWidget * parent); impl<'a> /*trait*/ QMenuBar_new for (Option<&'a QWidget>) { fn new(self) -> QMenuBar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBarC2EP7QWidget()}; let ctysz: c_int = unsafe{QMenuBar_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN8QMenuBarC2EP7QWidget(arg0)}; let rsthis = QMenuBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QMenuBar::setActiveAction(QAction * action); impl /*struct*/ QMenuBar { pub fn setActiveAction<RetType, T: QMenuBar_setActiveAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setActiveAction(self); // return 1; } } pub trait QMenuBar_setActiveAction<RetType> { fn setActiveAction(self , rsthis: & QMenuBar) -> RetType; } // proto: void QMenuBar::setActiveAction(QAction * action); impl<'a> /*trait*/ QMenuBar_setActiveAction<()> for (&'a QAction) { fn setActiveAction(self , rsthis: & QMenuBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar15setActiveActionEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN8QMenuBar15setActiveActionEP7QAction(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMenuBar::clear(); impl /*struct*/ QMenuBar { pub fn clear<RetType, T: QMenuBar_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QMenuBar_clear<RetType> { fn clear(self , rsthis: & QMenuBar) -> RetType; } // proto: void QMenuBar::clear(); impl<'a> /*trait*/ QMenuBar_clear<()> for () { fn clear(self , rsthis: & QMenuBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar5clearEv()}; unsafe {C_ZN8QMenuBar5clearEv(rsthis.qclsinst)}; // return 1; } } // proto: QAction * QMenuBar::activeAction(); impl /*struct*/ QMenuBar { pub fn activeAction<RetType, T: QMenuBar_activeAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.activeAction(self); // return 1; } } pub trait QMenuBar_activeAction<RetType> { fn activeAction(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::activeAction(); impl<'a> /*trait*/ QMenuBar_activeAction<QAction> for () { fn activeAction(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar12activeActionEv()}; let mut ret = unsafe {C_ZNK8QMenuBar12activeActionEv(rsthis.qclsinst)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMenu * QMenuBar::addMenu(const QIcon & icon, const QString & title); impl<'a> /*trait*/ QMenuBar_addMenu<QMenu> for (&'a QIcon, &'a QString) { fn addMenu(self , rsthis: & QMenuBar) -> QMenu { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar7addMenuERK5QIconRK7QString()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QMenuBar7addMenuERK5QIconRK7QString(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QMenu::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMenu * QMenuBar::addMenu(const QString & title); impl<'a> /*trait*/ QMenuBar_addMenu<QMenu> for (&'a QString) { fn addMenu(self , rsthis: & QMenuBar) -> QMenu { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar7addMenuERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QMenuBar7addMenuERK7QString(rsthis.qclsinst, arg0)}; let mut ret1 = QMenu::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QRect QMenuBar::actionGeometry(QAction * ); impl /*struct*/ QMenuBar { pub fn actionGeometry<RetType, T: QMenuBar_actionGeometry<RetType>>(& self, overload_args: T) -> RetType { return overload_args.actionGeometry(self); // return 1; } } pub trait QMenuBar_actionGeometry<RetType> { fn actionGeometry(self , rsthis: & QMenuBar) -> RetType; } // proto: QRect QMenuBar::actionGeometry(QAction * ); impl<'a> /*trait*/ QMenuBar_actionGeometry<QRect> for (&'a QAction) { fn actionGeometry(self , rsthis: & QMenuBar) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar14actionGeometryEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK8QMenuBar14actionGeometryEP7QAction(rsthis.qclsinst, arg0)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QMenuBar::insertMenu(QAction * before, QMenu * menu); impl /*struct*/ QMenuBar { pub fn insertMenu<RetType, T: QMenuBar_insertMenu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertMenu(self); // return 1; } } pub trait QMenuBar_insertMenu<RetType> { fn insertMenu(self , rsthis: & QMenuBar) -> RetType; } // proto: QAction * QMenuBar::insertMenu(QAction * before, QMenu * menu); impl<'a> /*trait*/ QMenuBar_insertMenu<QAction> for (&'a QAction, &'a QMenu) { fn insertMenu(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar10insertMenuEP7QActionP5QMenu()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QMenuBar10insertMenuEP7QActionP5QMenu(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMenuBar::setDefaultUp(bool ); impl /*struct*/ QMenuBar { pub fn setDefaultUp<RetType, T: QMenuBar_setDefaultUp<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDefaultUp(self); // return 1; } } pub trait QMenuBar_setDefaultUp<RetType> { fn setDefaultUp(self , rsthis: & QMenuBar) -> RetType; } // proto: void QMenuBar::setDefaultUp(bool ); impl<'a> /*trait*/ QMenuBar_setDefaultUp<()> for (i8) { fn setDefaultUp(self , rsthis: & QMenuBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar12setDefaultUpEb()}; let arg0 = self as c_char; unsafe {C_ZN8QMenuBar12setDefaultUpEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMenuBar::setVisible(bool visible); impl /*struct*/ QMenuBar { pub fn setVisible<RetType, T: QMenuBar_setVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setVisible(self); // return 1; } } pub trait QMenuBar_setVisible<RetType> { fn setVisible(self , rsthis: & QMenuBar) -> RetType; } // proto: void QMenuBar::setVisible(bool visible); impl<'a> /*trait*/ QMenuBar_setVisible<()> for (i8) { fn setVisible(self , rsthis: & QMenuBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar10setVisibleEb()}; let arg0 = self as c_char; unsafe {C_ZN8QMenuBar10setVisibleEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QAction * QMenuBar::addAction(const QString & text, const QObject * receiver, const char * member); impl<'a> /*trait*/ QMenuBar_addAction<QAction> for (&'a QString, &'a QObject, &'a String) { fn addAction(self , rsthis: & QMenuBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QMenuBar9addActionERK7QStringPK7QObjectPKc()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.as_ptr() as *mut c_char; let mut ret = unsafe {C_ZN8QMenuBar9addActionERK7QStringPK7QObjectPKc(rsthis.qclsinst, arg0, arg1, arg2)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QMenuBar::heightForWidth(int ); impl /*struct*/ QMenuBar { pub fn heightForWidth<RetType, T: QMenuBar_heightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.heightForWidth(self); // return 1; } } pub trait QMenuBar_heightForWidth<RetType> { fn heightForWidth(self , rsthis: & QMenuBar) -> RetType; } // proto: int QMenuBar::heightForWidth(int ); impl<'a> /*trait*/ QMenuBar_heightForWidth<i32> for (i32) { fn heightForWidth(self , rsthis: & QMenuBar) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QMenuBar14heightForWidthEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK8QMenuBar14heightForWidthEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } #[derive(Default)] // for QMenuBar_hovered pub struct QMenuBar_hovered_signal{poi:u64} impl /* struct */ QMenuBar { pub fn hovered(&self) -> QMenuBar_hovered_signal { return QMenuBar_hovered_signal{poi:self.qclsinst}; } } impl /* struct */ QMenuBar_hovered_signal { pub fn connect<T: QMenuBar_hovered_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QMenuBar_hovered_signal_connect { fn connect(self, sigthis: QMenuBar_hovered_signal); } #[derive(Default)] // for QMenuBar_triggered pub struct QMenuBar_triggered_signal{poi:u64} impl /* struct */ QMenuBar { pub fn triggered(&self) -> QMenuBar_triggered_signal { return QMenuBar_triggered_signal{poi:self.qclsinst}; } } impl /* struct */ QMenuBar_triggered_signal { pub fn connect<T: QMenuBar_triggered_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QMenuBar_triggered_signal_connect { fn connect(self, sigthis: QMenuBar_triggered_signal); } // triggered(class QAction *) extern fn QMenuBar_triggered_signal_connect_cb_0(rsfptr:fn(QAction), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QAction::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QMenuBar_triggered_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QAction)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QAction::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QMenuBar_triggered_signal_connect for fn(QAction) { fn connect(self, sigthis: QMenuBar_triggered_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QMenuBar_triggered_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QMenuBar_SlotProxy_connect__ZN8QMenuBar9triggeredEP7QAction(arg0, arg1, arg2)}; } } impl /* trait */ QMenuBar_triggered_signal_connect for Box<Fn(QAction)> { fn connect(self, sigthis: QMenuBar_triggered_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QMenuBar_triggered_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QMenuBar_SlotProxy_connect__ZN8QMenuBar9triggeredEP7QAction(arg0, arg1, arg2)}; } } // hovered(class QAction *) extern fn QMenuBar_hovered_signal_connect_cb_1(rsfptr:fn(QAction), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QAction::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QMenuBar_hovered_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(QAction)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QAction::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QMenuBar_hovered_signal_connect for fn(QAction) { fn connect(self, sigthis: QMenuBar_hovered_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QMenuBar_hovered_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QMenuBar_SlotProxy_connect__ZN8QMenuBar7hoveredEP7QAction(arg0, arg1, arg2)}; } } impl /* trait */ QMenuBar_hovered_signal_connect for Box<Fn(QAction)> { fn connect(self, sigthis: QMenuBar_hovered_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QMenuBar_hovered_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QMenuBar_SlotProxy_connect__ZN8QMenuBar7hoveredEP7QAction(arg0, arg1, arg2)}; } } // <= body block end
extern crate quicksilver; use quicksilver::{ Result, geom::{Shape, Vector, Rectangle}, graphics::{Background, Background::Img, Background::Col, Color, Font, FontStyle, Image, PixelFormat}, lifecycle::{Asset, Window}, }; extern crate naive_gui; use naive_gui::{ Gui, Widget, Drawer, }; pub struct QuickSilverDrawContext<'a> { font_size: f32, fill_color: Color, font_loader: &'a mut Asset<Font>, //stroke_color: Color, window: &'a mut Window, } impl<'a> QuickSilverDrawContext<'a>{ pub fn new(window: &'a mut Window, default_font: &'a mut Asset<Font>) -> Self{ let (r,g,b,a) = (0., 0., 0., 1.); QuickSilverDrawContext{ fill_color: Color::BLACK, //stroke_color: (0., 0., 0., 1.), font_size: 12., font_loader: default_font, window: window, } } } impl<'a> Drawer for QuickSilverDrawContext<'a>{ fn set_fill_style(&mut self, rgba:(f32, f32, f32, f32)){ self.fill_color = Color::BLACK; } fn set_stroke_style(&mut self, rgba:(f32, f32, f32, f32)){ //self.stroke_rgba = rgba; } fn set_font_style(&mut self, size: f32) { self.font_size = size; } fn draw_rect(&mut self, xywh:(f32, f32, f32, f32)) { self.window.draw(&Rectangle::new((xywh.0, xywh.1), (xywh.2, xywh.3)), Col(self.fill_color)); } fn draw_text(&mut self, text: &str, xy:(f32, f32)){ let font_size = &mut self.font_size; let fill_color = &mut self.fill_color; let window = &mut self.window; self.font_loader.execute(|font| { let image = font.render(text, &FontStyle::new(*font_size, *fill_color)).unwrap(); let rect = &image.area(); (*window).draw(&image.area().translate((xy.0-image.area().x(), xy.1-image.area().y())), Img(&image)); Ok(()) }); } fn rendered_text_wh(&mut self, text: &str) -> (f32, f32) { let mut wh = (0., 0.); let font_size = &mut self.font_size; let fill_color = &mut self.fill_color; self.font_loader.execute(|font| { let image = font.render(text, &FontStyle::new(*font_size, *fill_color)).unwrap(); wh = (image.area().width(), image.area().height()); Ok(()) }); wh } }
//! An InfluxDB IOx API client. #![deny( rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms, missing_debug_implementations, unreachable_pub )] #![warn( missing_docs, clippy::todo, clippy::dbg_macro, clippy::clone_on_ref_ptr, // See https://github.com/influxdata/influxdb_iox/pull/1671 clippy::future_not_send, clippy::todo, clippy::dbg_macro, unused_crate_dependencies )] #![allow(clippy::missing_docs_in_private_items)] pub use generated_types::{google, protobuf_type_url, protobuf_type_url_eq}; pub use client::*; pub use client_util::connection; pub use client_util::namespace_translation; #[cfg(feature = "format")] /// Output formatting utilities pub mod format; mod client;
use winapi::shared::ntdef::HANDLE; use winapi::um::handleapi::*; use winapi::um::errhandlingapi::*; use std::ptr::null_mut; #[repr(C)] #[derive(Debug)] pub struct KernelHandle(HANDLE); #[derive(Debug, Clone, Copy)] pub struct Win32Error(u32); impl Drop for KernelHandle { fn drop(&mut self) { if self.0 as isize > 0 { unsafe { CloseHandle(self.0); } } } } impl KernelHandle { pub fn new(handle: HANDLE) -> Self { KernelHandle(handle) } pub fn close(&mut self) -> Result<(), Win32Error> { let success = unsafe { CloseHandle(self.0) }; if success != 0 { Ok(()) } else { Err(Win32Error::new()) } } pub fn is_valid(&self) -> bool { self.0 != null_mut() } pub fn get(&self) -> HANDLE { self.0 } } impl Win32Error { pub fn new() -> Self { unsafe { Win32Error(GetLastError()) } } pub fn from_error(error: u32) -> Self { Win32Error(error) } pub fn from_ntstatus(status: i32) -> Self { unsafe { Win32Error(ntapi::ntrtl::RtlNtStatusToDosError(status)) } } }
//! A dynamically sized, multi-channel interleaved audio buffer. use crate::wrap; use audio_core::{ AsInterleaved, AsInterleavedMut, Buf, Channels, ChannelsMut, ExactSizeBuf, InterleavedBuf, ResizableBuf, Sample, }; use std::cmp; use std::fmt; use std::hash; use std::marker; use std::ptr; mod channel; pub use self::channel::{Channel, ChannelMut}; use self::channel::{RawChannelMut, RawChannelRef}; mod iter; pub use self::iter::{Iter, IterMut}; /// A dynamically sized, multi-channel interleaved audio buffer. /// /// An audio buffer can only be resized if it contains a type which is /// sample-apt For more information of what this means, see [Sample]. /// /// An *interleaved* audio buffer stores all audio data interleaved in memory, /// one sample from each channel in sequence until we're out of samples. This /// naturally makes the buffer a bit harder to work with, and we have to rely on /// iterators to access logical channels. /// /// Resized regions aren't zeroed, so certain operations might cause stale data /// to be visible after a resize. /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 4); /// /// for (c, s) in buffer /// .get_mut(0) /// .unwrap() /// .iter_mut() /// .zip(&[1.0, 2.0, 3.0, 4.0]) /// { /// *c = *s; /// } /// /// for (c, s) in buffer /// .get_mut(1) /// .unwrap() /// .iter_mut() /// .zip(&[5.0, 6.0, 7.0, 8.0]) /// { /// *c = *s; /// } /// /// assert_eq!(buffer.as_slice(), &[1.0, 5.0, 2.0, 6.0, 3.0, 7.0, 4.0, 8.0]); /// ``` #[derive(Default)] pub struct Interleaved<T> { data: Vec<T>, channels: usize, frames: usize, } impl<T> Interleaved<T> { /// Construct a new empty audio buffer. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::new(); /// /// assert_eq!(buffer.frames(), 0); /// ``` pub fn new() -> Self { Self { data: Vec::new(), channels: 0, frames: 0, } } /// Allocate an audio buffer with the given topology. A "topology" is a /// given number of `channels` and the corresponding number of `frames` in /// their buffers. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(4, 256); /// /// assert_eq!(buffer.frames(), 256); /// assert_eq!(buffer.channels(), 4); /// ``` pub fn with_topology(channels: usize, frames: usize) -> Self where T: Sample, { Self { data: vec![T::ZERO; channels * frames], channels, frames, } } /// Allocate an audio buffer from a fixed-size array. /// /// See [dynamic!]. /// /// # Examples /// /// ```rust /// let mut buffer = audio::interleaved![[2.0; 256]; 4]; /// /// assert_eq!(buffer.frames(), 256); /// assert_eq!(buffer.channels(), 4); /// /// for chan in &buffer { /// assert!(chan.iter().eq(&[2.0; 256][..])); /// } /// ``` pub fn from_vec(data: Vec<T>, channels: usize, frames: usize) -> Self { Self { data, channels, frames, } } /// Allocate an interleaved audio buffer from a fixed-size array acting as a /// template for all the channels. /// /// See [sequential!]. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::from_frames([1.0, 2.0, 3.0, 4.0], 4); /// /// assert_eq!(buffer.frames(), 4); /// assert_eq!(buffer.channels(), 4); /// ``` pub fn from_frames<const N: usize>(frames: [T; N], channels: usize) -> Self where T: Copy, { return Self { data: data_from_frames(frames, channels), channels, frames: N, }; fn data_from_frames<T, const N: usize>(frames: [T; N], channels: usize) -> Vec<T> where T: Copy, { let mut data = Vec::with_capacity(N * channels); for f in std::array::IntoIter::new(frames) { for _ in 0..channels { data.push(f); } } data } } /// Allocate an interleaved audio buffer from a fixed-size array. /// /// See [interleaved!]. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::from_array([[1; 4]; 2]); /// /// assert_eq!(buffer.frames(), 4); /// assert_eq!(buffer.channels(), 2); /// /// assert_eq! { /// buffer.as_slice(), /// &[1, 1, 1, 1, 1, 1, 1, 1], /// } /// ``` /// /// Using a specific array topology. /// /// ```rust /// let mut buffer = audio::Interleaved::from_array([[1, 2, 3, 4], [5, 6, 7, 8]]); /// /// assert_eq!(buffer.frames(), 4); /// assert_eq!(buffer.channels(), 2); /// /// assert_eq! { /// buffer.as_slice(), /// &[1, 5, 2, 6, 3, 7, 4, 8], /// } /// ``` pub fn from_array<const F: usize, const C: usize>(channels: [[T; F]; C]) -> Self where T: Copy, { return Self { data: data_from_array(channels), channels: C, frames: F, }; #[inline] fn data_from_array<T, const F: usize, const C: usize>(channels: [[T; F]; C]) -> Vec<T> { let mut data = Vec::with_capacity(C * F); // TODO: It would be nice to avoid this heap allocation! Could be // done w/ ArrayVec, but we don't want to pull that dependency. let mut vecs: Vec<std::array::IntoIter<T, F>> = std::array::IntoIter::new(channels) .map(std::array::IntoIter::new) .collect(); for _ in 0..F { for v in vecs.iter_mut() { data.extend(v.next()); } } data } } /// Take ownership of the backing vector. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 4); /// /// for (c, s) in buffer.get_mut(0).unwrap().iter_mut().zip(&[1.0, 2.0, 3.0, 4.0]) { /// *c = *s; /// } /// /// for (c, s) in buffer.get_mut(1).unwrap().iter_mut().zip(&[1.0, 2.0, 3.0, 4.0]) { /// *c = *s; /// } /// /// buffer.resize(3); /// /// assert_eq!(buffer.into_vec(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]) /// ``` pub fn into_vec(self) -> Vec<T> { self.data } /// Access the underlying vector as a slice. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<i16>::with_topology(2, 4); /// assert_eq!(buffer.as_slice(), &[0, 0, 0, 0, 0, 0, 0, 0]); /// ``` pub fn as_slice(&self) -> &[T] { &self.data } /// Access the underlying vector as a mutable slice. /// /// # Examples /// /// ```rust /// use audio::Channels as _; /// /// let mut buffer = audio::Interleaved::<i16>::with_topology(2, 4); /// buffer.as_slice_mut().copy_from_slice(&[1, 1, 2, 2, 3, 3, 4, 4]); /// /// assert_eq! { /// buffer.channel(0).iter().collect::<Vec<_>>(), /// &[1, 2, 3, 4], /// }; /// /// assert_eq! { /// buffer.channel(1).iter().collect::<Vec<_>>(), /// &[1, 2, 3, 4], /// }; /// /// assert_eq!(buffer.as_slice(), &[1, 1, 2, 2, 3, 3, 4, 4]); /// ``` pub fn as_slice_mut(&mut self) -> &mut [T] { &mut self.data } /// Get the number of frames in the channels of an audio buffer. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::new(); /// /// assert_eq!(buffer.frames(), 0); /// buffer.resize(256); /// assert_eq!(buffer.frames(), 256); /// ``` pub fn frames(&self) -> usize { self.frames } /// Get the capacity of the interleaved buffer in number of frames. /// /// The underlying buffer over-allocates a bit, so this will report the /// exact capacity available in the interleaved buffer. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::new(); /// /// assert_eq!(buffer.capacity(), 0); /// /// buffer.resize(11); /// assert_eq!(buffer.capacity(), 0); /// /// buffer.resize_channels(2); /// assert_eq!(buffer.capacity(), 11); /// /// buffer.resize(12); /// assert_eq!(buffer.capacity(), 22); /// /// buffer.resize(22); /// assert_eq!(buffer.capacity(), 22); /// ``` pub fn capacity(&self) -> usize { if self.channels == 0 { 0 } else { self.data.capacity() / self.channels } } /// Get the number of channels in the buffer. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::new(); /// /// assert_eq!(buffer.channels(), 0); /// buffer.resize_channels(2); /// assert_eq!(buffer.channels(), 2); /// ``` pub fn channels(&self) -> usize { self.channels } /// Offset the interleaved buffer and return a wrapped buffer. /// /// This is provided as a special operation for this buffer kind, because it /// can be done more efficiently than what is available through [Buf::skip]. pub fn interleaved_skip(&self, skip: usize) -> wrap::Interleaved<&[T]> { let data = self.data.get(skip * self.channels..).unwrap_or_default(); wrap::interleaved(data, self.channels) } /// Offset the interleaved buffer and return a mutable wrapped buffer. /// /// This is provided as a special operation for this buffer kind, because it /// can be done more efficiently than what is available through [Buf::skip]. /// /// # Examples /// /// ```rust /// use audio::{Channels as _, ChannelsMut as _}; /// /// let mut buffer = audio::Interleaved::with_topology(2, 4); /// /// buffer.interleaved_skip_mut(2).channel_mut(0).copy_from_slice(&[1.0, 1.0]); /// /// assert_eq!(buffer.as_slice(), &[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0]) /// ``` pub fn interleaved_skip_mut(&mut self, skip: usize) -> wrap::Interleaved<&mut [T]> { let data = self .data .get_mut(skip * self.channels..) .unwrap_or_default(); wrap::interleaved(data, self.channels) } /// Limit the interleaved buffer and return a wrapped buffer. /// /// This is provided as a special operation for this buffer kind, because it /// can be done more efficiently than what is available through /// [Buf::limit]. /// /// # Examples /// /// ```rust /// use audio::{Channels as _, ChannelsMut as _}; /// /// let from = audio::interleaved![[1.0f32; 4]; 2]; /// let mut to = audio::Interleaved::<f32>::with_topology(2, 4); /// /// to.channel_mut(0).copy_from(from.interleaved_limit(2).channel(0)); /// assert_eq!(to.as_slice(), &[1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); /// ``` pub fn interleaved_limit(&self, limit: usize) -> wrap::Interleaved<&[T]> { wrap::interleaved(&self.data[..limit * self.channels], self.channels) } /// Limit the interleaved buffer and return a mutable wrapped buffer. /// /// This is provided as a special operation for this buffer kind, because it /// can be done more efficiently than what is available through /// [Buf::limit]. pub fn interleaved_limit_mut(&mut self, limit: usize) -> wrap::Interleaved<&mut [T]> { wrap::interleaved(&mut self.data[..limit * self.channels], self.channels) } /// Resize to the given number of channels in use. /// /// If the size of the buffer increases as a result, the new channels will /// be zeroed. If the size decreases, the channels that falls outside of the /// new size will be dropped. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::new(); /// /// assert_eq!(buffer.channels(), 0); /// assert_eq!(buffer.frames(), 0); /// /// buffer.resize_channels(4); /// buffer.resize(256); /// /// assert_eq!(buffer.channels(), 4); /// assert_eq!(buffer.frames(), 256); /// ``` pub fn resize_channels(&mut self, channels: usize) where T: Sample, { self.inner_resize(channels, self.frames); } /// Set the size of the buffer. The size is the size of each channel's /// buffer. /// /// If the size of the buffer increases as a result, the new regions in the /// frames will be zeroed. If the size decreases, the region will be left /// untouched. So if followed by another increase, the data will be "dirty". /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::new(); /// /// assert_eq!(buffer.channels(), 0); /// assert_eq!(buffer.frames(), 0); /// /// buffer.resize_channels(4); /// buffer.resize(256); /// /// assert_eq!(buffer.channels(), 4); /// assert_eq!(buffer.frames(), 256); /// /// { /// let mut chan = buffer.get_mut(1).unwrap(); /// /// assert_eq!(chan.get(127), Some(0.0)); /// *chan.get_mut(127).unwrap() = 42.0; /// assert_eq!(chan.get(127), Some(42.0)); /// } /// /// buffer.resize(128); /// assert_eq!(buffer.frame(1, 127), Some(42.0)); /// /// buffer.resize(256); /// assert_eq!(buffer.frame(1, 127), Some(42.0)); /// /// buffer.resize_channels(2); /// assert_eq!(buffer.frame(1, 127), Some(42.0)); /// /// buffer.resize(64); /// assert_eq!(buffer.frame(1, 127), None); /// ``` pub fn resize(&mut self, frames: usize) where T: Sample, { self.inner_resize(self.channels, frames); } /// Get a reference to a channel. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 4); /// /// for (c, s) in buffer.get_mut(0).unwrap().iter_mut().zip(&[1.0, 2.0, 3.0, 4.0]) { /// *c = *s; /// } /// /// for (c, s) in buffer.get_mut(1).unwrap().iter_mut().zip(&[5.0, 6.0, 7.0, 8.0]) { /// *c = *s; /// } /// /// assert_eq!(buffer.get(0).unwrap().iter().nth(2), Some(&3.0)); /// assert_eq!(buffer.get(1).unwrap().iter().nth(2), Some(&7.0)); /// ``` pub fn get(&self, channel: usize) -> Option<Channel<'_, T>> { if channel < self.channels { Some(Channel { inner: RawChannelRef { buffer: self.data.as_ptr(), channel, channels: self.channels, frames: self.frames, }, _marker: marker::PhantomData, }) } else { None } } /// Helper to access a single frame in a single channel. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 256); /// /// assert_eq!(buffer.frame(1, 128), Some(0.0)); /// *buffer.frame_mut(1, 128).unwrap() = 1.0; /// assert_eq!(buffer.frame(1, 128), Some(1.0)); /// ``` pub fn frame(&self, channel: usize, frame: usize) -> Option<T> where T: Copy, { self.get(channel)?.get(frame) } /// Get a mutable reference to a channel. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 4); /// /// for (c, s) in buffer.get_mut(0).unwrap().iter_mut().zip(&[1.0, 2.0, 3.0, 4.0]) { /// *c = *s; /// } /// /// for (c, s) in buffer.get_mut(1).unwrap().iter_mut().zip(&[5.0, 6.0, 7.0, 8.0]) { /// *c = *s; /// } /// /// assert_eq!(buffer.as_slice(), &[1.0, 5.0, 2.0, 6.0, 3.0, 7.0, 4.0, 8.0]); /// ``` pub fn get_mut(&mut self, channel: usize) -> Option<ChannelMut<'_, T>> { if channel < self.channels { Some(ChannelMut { inner: RawChannelMut { buffer: self.data.as_mut_ptr(), channel, channels: self.channels, frames: self.frames, }, _marker: marker::PhantomData, }) } else { None } } /// Helper to access a single frame in a single channel mutably. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 256); /// /// assert_eq!(buffer.frame(1, 128), Some(0.0)); /// *buffer.frame_mut(1, 128).unwrap() = 1.0; /// assert_eq!(buffer.frame(1, 128), Some(1.0)); /// ``` pub fn frame_mut(&mut self, channel: usize, frame: usize) -> Option<&mut T> { self.get_mut(channel)?.into_mut(frame) } /// Construct an iterator over all available channels. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 4); /// /// let mut it = buffer.iter_mut(); /// /// for (c, f) in it.next().unwrap().iter_mut().zip(&[1.0, 2.0, 3.0, 4.0]) { /// *c = *f; /// } /// /// for (c, f) in it.next().unwrap().iter_mut().zip(&[5.0, 6.0, 7.0, 8.0]) { /// *c = *f; /// } /// /// let channels = buffer.iter().collect::<Vec<_>>(); /// let left = channels[0].iter().copied().collect::<Vec<_>>(); /// let right = channels[1].iter().copied().collect::<Vec<_>>(); /// /// assert_eq!(left, &[1.0, 2.0, 3.0, 4.0]); /// assert_eq!(right, &[5.0, 6.0, 7.0, 8.0]); /// ``` pub fn iter(&self) -> Iter<'_, T> { Iter { buffer: self.data.as_ptr(), channel: 0, channels: self.channels, frames: self.frames, _marker: marker::PhantomData, } } /// Construct a mutable iterator over all available channels. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 4); /// /// let mut it = buffer.iter_mut(); /// /// for (c, f) in it.next().unwrap().iter_mut().zip(&[1.0, 2.0, 3.0, 4.0]) { /// *c = *f; /// } /// /// for (c, f) in it.next().unwrap().iter_mut().zip(&[5.0, 6.0, 7.0, 8.0]) { /// *c = *f; /// } /// /// assert_eq!(buffer.as_slice(), &[1.0, 5.0, 2.0, 6.0, 3.0, 7.0, 4.0, 8.0]); /// ``` pub fn iter_mut(&mut self) -> IterMut<'_, T> { IterMut { buffer: self.data.as_mut_ptr(), channel: 0, channels: self.channels, frames: self.frames, _marker: marker::PhantomData, } } /// The internal resize function for interleaved channel buffers. /// Note: this is safe only because of the `T: Sample` bound. DO NOT REMOVE. fn inner_resize(&mut self, channels: usize, frames: usize) where T: Sample, { if self.channels == channels && self.frames == frames { return; } self.inner_reserve_cap(frames.saturating_mul(channels)); if self.channels != channels { let len = usize::min(self.channels, channels); // Safety: We trust the known lengths lengths. unsafe { if channels < self.channels { self.inner_shuffle_channels(1..frames, len, channels); } else { self.inner_shuffle_channels((1..frames).rev(), len, channels); } } } self.channels = channels; self.frames = frames; } /// Note: this is safe only because of the `T: Sample` bound. DO NOT REMOVE. fn inner_reserve_cap(&mut self, new_cap: usize) where T: Sample, { let old_cap = self.data.capacity(); if new_cap > old_cap { self.data.reserve(new_cap - old_cap); let new_cap = self.data.capacity(); // Safety: capacity is governed by the underlying vector. unsafe { ptr::write_bytes(self.data.as_mut_ptr().add(old_cap), 0, new_cap - old_cap); } } // Safety: since we're decreasing the number of frames we're sure // that the data for them is already allocated. unsafe { self.data.set_len(new_cap); } } /// Internal function to re-shuffle channels. /// /// # Safety /// /// The caller must ensure that the ranges of frames, the length and that /// the updates `channels` argument is validly within the buffer. #[inline] unsafe fn inner_shuffle_channels<F>(&mut self, frames: F, len: usize, channels: usize) where F: IntoIterator<Item = usize>, { let base = self.data.as_mut_ptr(); for f in frames { let from = f * self.channels; let to = f * channels; ptr::copy(base.add(from), base.add(to), len) } } } impl<T> fmt::Debug for Interleaved<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() } } impl<T> cmp::PartialEq for Interleaved<T> where T: cmp::PartialEq, { fn eq(&self, other: &Self) -> bool { self.iter().eq(other.iter()) } } impl<T> cmp::Eq for Interleaved<T> where T: cmp::Eq {} impl<T> cmp::PartialOrd for Interleaved<T> where T: cmp::PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.iter().partial_cmp(other.iter()) } } impl<T> cmp::Ord for Interleaved<T> where T: cmp::Ord, { fn cmp(&self, other: &Self) -> cmp::Ordering { self.iter().cmp(other.iter()) } } impl<T> hash::Hash for Interleaved<T> where T: hash::Hash, { fn hash<H: hash::Hasher>(&self, state: &mut H) { for channel in self.iter() { channel.hash(state); } } } impl<T> ExactSizeBuf for Interleaved<T> { fn frames(&self) -> usize { self.frames } } impl<T> Buf for Interleaved<T> { fn frames_hint(&self) -> Option<usize> { Some(self.frames) } fn channels(&self) -> usize { self.channels } } impl<T> Channels<T> for Interleaved<T> { fn channel(&self, channel: usize) -> audio_core::Channel<'_, T> { audio_core::Channel::interleaved(&self.data, self.channels, channel) } } impl<T> ResizableBuf for Interleaved<T> where T: Sample, { fn resize(&mut self, frames: usize) { Self::resize(self, frames); } fn resize_topology(&mut self, channels: usize, frames: usize) { Self::resize(self, frames); Self::resize_channels(self, channels); } } impl<T> InterleavedBuf for Interleaved<T> where T: Sample, { fn reserve_frames(&mut self, frames: usize) { self.inner_reserve_cap(frames); } fn set_topology(&mut self, channels: usize, frames: usize) { let new_len = channels.saturating_mul(frames); assert! { new_len <= self.data.capacity(), "current buffer with capacity {} doesn't fit the requested topology {}:{}", self.data.capacity(), channels, frames }; // Safety: all entrypoints to Interleaved assure that `data` is // initialized up until `cap`, so updating the length is safe. unsafe { self.data.set_len(new_len); } self.channels = channels; self.frames = frames; } } impl<T> ChannelsMut<T> for Interleaved<T> where T: Copy, { fn channel_mut(&mut self, channel: usize) -> audio_core::ChannelMut<'_, T> { audio_core::ChannelMut::interleaved(&mut self.data, self.channels, channel) } fn copy_channels(&mut self, from: usize, to: usize) { // Safety: We're making sure not to access any mutable buffers which // are not initialized. unsafe { crate::utils::copy_channels_interleaved( self.data.as_mut_ptr(), self.channels, self.frames, from, to, ) } } } impl<'a, T> IntoIterator for &'a Interleaved<T> { type IntoIter = Iter<'a, T>; type Item = <Self::IntoIter as Iterator>::Item; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, T> IntoIterator for &'a mut Interleaved<T> { type IntoIter = IterMut<'a, T>; type Item = <Self::IntoIter as Iterator>::Item; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } impl<T> AsInterleaved<T> for Interleaved<T> { fn as_interleaved(&self) -> &[T] { self.as_slice() } } impl<T> AsInterleavedMut<T> for Interleaved<T> { fn as_interleaved_mut(&mut self) -> &mut [T] { self.as_slice_mut() } fn as_interleaved_mut_ptr(&mut self) -> *mut T { self.data.as_mut_ptr() } }
mod platform; mod version; pub use block::Block; pub use entry::Entry; pub use header::Header; pub use patch::Patch; pub use platform::Platform; pub use region::Region; pub use version::Version; pub(crate) mod block; mod entry; pub mod files; mod header; pub mod index; mod patch; mod region; pub mod decrypt; pub mod decompress; pub const HASH_LENGTH: usize = 0x00_14; pub const TAG_LENGTH: usize = 0x00_10; pub const MAGIC_NUMBER: u32 = 0x28_11_41_FD; pub const BUILD_STRING_LENGTH: usize = 0x20; pub const RSA_SIGNATURE_LENGTH: usize = 0x100; pub type BuildString = [u32; BUILD_STRING_LENGTH]; pub type RsaSignature = [u8; RSA_SIGNATURE_LENGTH]; pub type Id = u16; pub type Epoch = u32; pub type AuthenticationTag = [u8; TAG_LENGTH]; pub type Hash = [u8; HASH_LENGTH]; pub type EntryTable = [Entry; 1]; pub type BlockTable = [Block; 1]; pub type MagicNumber = u32; pub type Offset = u32; pub type Count = u32;
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type IImageScannerFormatConfiguration = *mut ::core::ffi::c_void; pub type IImageScannerSourceConfiguration = *mut ::core::ffi::c_void; pub type ImageScanner = *mut ::core::ffi::c_void; pub type ImageScannerAutoConfiguration = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ImageScannerAutoCroppingMode(pub i32); impl ImageScannerAutoCroppingMode { pub const Disabled: Self = Self(0i32); pub const SingleRegion: Self = Self(1i32); pub const MultipleRegion: Self = Self(2i32); } impl ::core::marker::Copy for ImageScannerAutoCroppingMode {} impl ::core::clone::Clone for ImageScannerAutoCroppingMode { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ImageScannerColorMode(pub i32); impl ImageScannerColorMode { pub const Color: Self = Self(0i32); pub const Grayscale: Self = Self(1i32); pub const Monochrome: Self = Self(2i32); pub const AutoColor: Self = Self(3i32); } impl ::core::marker::Copy for ImageScannerColorMode {} impl ::core::clone::Clone for ImageScannerColorMode { fn clone(&self) -> Self { *self } } pub type ImageScannerFeederConfiguration = *mut ::core::ffi::c_void; pub type ImageScannerFlatbedConfiguration = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ImageScannerFormat(pub i32); impl ImageScannerFormat { pub const Jpeg: Self = Self(0i32); pub const Png: Self = Self(1i32); pub const DeviceIndependentBitmap: Self = Self(2i32); pub const Tiff: Self = Self(3i32); pub const Xps: Self = Self(4i32); pub const OpenXps: Self = Self(5i32); pub const Pdf: Self = Self(6i32); } impl ::core::marker::Copy for ImageScannerFormat {} impl ::core::clone::Clone for ImageScannerFormat { fn clone(&self) -> Self { *self } } pub type ImageScannerPreviewResult = *mut ::core::ffi::c_void; #[repr(C)] pub struct ImageScannerResolution { pub DpiX: f32, pub DpiY: f32, } impl ::core::marker::Copy for ImageScannerResolution {} impl ::core::clone::Clone for ImageScannerResolution { fn clone(&self) -> Self { *self } } pub type ImageScannerScanResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ImageScannerScanSource(pub i32); impl ImageScannerScanSource { pub const Default: Self = Self(0i32); pub const Flatbed: Self = Self(1i32); pub const Feeder: Self = Self(2i32); pub const AutoConfigured: Self = Self(3i32); } impl ::core::marker::Copy for ImageScannerScanSource {} impl ::core::clone::Clone for ImageScannerScanSource { fn clone(&self) -> Self { *self } }
use async_graphql::*; #[tokio::test] pub async fn test_interface_simple_object() { #[derive(SimpleObject)] struct MyObj { id: i32, title: String, } #[derive(Interface)] #[graphql(field(name = "id", type = "&i32"))] enum Node { MyObj(MyObj), } struct Query; #[Object] impl Query { async fn node(&self) -> Node { MyObj { id: 33, title: "haha".to_string(), } .into() } } let query = r#"{ node { ... on Node { id } } }"#; let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "node": { "id": 33, } }) ); } #[tokio::test] pub async fn test_interface_simple_object2() { #[derive(SimpleObject)] struct MyObj { id: i32, title: String, } #[derive(Interface)] #[graphql(field(name = "id", type = "&i32"))] enum Node { MyObj(MyObj), } struct Query; #[Object] impl Query { async fn node(&self) -> Node { MyObj { id: 33, title: "haha".to_string(), } .into() } } let query = r#"{ node { ... on Node { id } } }"#; let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "node": { "id": 33, } }) ); } #[tokio::test] pub async fn test_multiple_interfaces() { struct MyObj; #[Object] impl MyObj { async fn value_a(&self) -> i32 { 1 } async fn value_b(&self) -> i32 { 2 } async fn value_c(&self) -> i32 { 3 } } #[derive(Interface)] #[graphql(field(name = "value_a", type = "i32"))] enum InterfaceA { MyObj(MyObj), } #[derive(Interface)] #[graphql(field(name = "value_b", type = "i32"))] enum InterfaceB { MyObj(MyObj), } struct Query; #[Object] impl Query { async fn my_obj(&self) -> InterfaceB { MyObj.into() } } let schema = Schema::build(Query, EmptyMutation, EmptySubscription) .register_output_type::<InterfaceA>() // `InterfaceA` is not directly referenced, so manual registration is required. .finish(); let query = r#"{ myObj { ... on InterfaceA { valueA } ... on InterfaceB { valueB } ... on MyObj { valueC } } }"#; assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "myObj": { "valueA": 1, "valueB": 2, "valueC": 3, } }) ); } #[tokio::test] pub async fn test_multiple_objects_in_multiple_interfaces() { struct MyObjOne; #[Object] impl MyObjOne { async fn value_a(&self) -> i32 { 1 } async fn value_b(&self) -> i32 { 2 } async fn value_c(&self) -> i32 { 3 } } struct MyObjTwo; #[Object] impl MyObjTwo { async fn value_a(&self) -> i32 { 1 } } #[derive(Interface)] #[graphql(field(name = "value_a", type = "i32"))] enum InterfaceA { MyObjOne(MyObjOne), MyObjTwo(MyObjTwo), } #[derive(Interface)] #[graphql(field(name = "value_b", type = "i32"))] enum InterfaceB { MyObjOne(MyObjOne), } struct Query; #[Object] impl Query { async fn my_obj(&self) -> Vec<InterfaceA> { vec![MyObjOne.into(), MyObjTwo.into()] } } let schema = Schema::build(Query, EmptyMutation, EmptySubscription) .register_output_type::<InterfaceB>() // `InterfaceB` is not directly referenced, so manual registration is required. .finish(); let query = r#"{ myObj { ... on InterfaceA { valueA } ... on InterfaceB { valueB } ... on MyObjOne { valueC } } }"#; assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "myObj": [{ "valueA": 1, "valueB": 2, "valueC": 3, }, { "valueA": 1 }] }) ); } #[tokio::test] pub async fn test_interface_field_result() { struct MyObj; #[Object] impl MyObj { async fn value(&self) -> FieldResult<i32> { Ok(10) } } #[derive(Interface)] #[graphql(field(name = "value", type = "i32"))] enum Node { MyObj(MyObj), } struct Query; #[Object] impl Query { async fn node(&self) -> Node { MyObj.into() } } let query = r#"{ node { ... on Node { value } } }"#; let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "node": { "value": 10, } }) ); } #[tokio::test] pub async fn test_interface_field_method() { struct A; #[Object] impl A { #[graphql(name = "created_at")] pub async fn created_at(&self) -> i32 { 1 } } struct B; #[Object] impl B { #[graphql(name = "created_at")] pub async fn created_at(&self) -> i32 { 2 } } #[derive(Interface)] #[graphql(field(name = "created_at", method = "created_at", type = "i32"))] enum MyInterface { A(A), B(B), } struct Query; #[Object] impl Query { async fn test(&self) -> MyInterface { A.into() } } let query = "{ test { created_at } }"; let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "test": { "created_at": 1, } }) ); } #[tokio::test] pub async fn test_interface_implement_other_interface() { #[derive(Interface)] #[graphql(field(name = "id", type = "ID"))] pub enum Entity { Company(Company), Organization(Organization), } #[derive(Interface)] #[graphql(field(name = "id", type = "ID"))] pub enum Node { Entity(Entity), } pub struct Company {} #[Object] impl Company { pub async fn id(&self) -> ID { "88".into() } } pub struct Organization {} #[Object] impl Organization { pub async fn id(&self) -> ID { "99".into() } } struct Query; #[Object] impl Query { async fn company(&self) -> Node { Entity::Company(Company {}).into() } async fn organization(&self) -> Node { Entity::Organization(Organization {}).into() } } let query = r#" { company { id } organization { id } } "#; let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "company": { "id": "88", }, "organization": { "id": "99", } }) ); } #[tokio::test] pub async fn test_issue_330() { #[derive(Interface)] #[graphql(field( desc = "The code represented as a number.", name = "number", type = "String" ))] pub enum Code { Barcode(Barcode), Qrcode(Qrcode), } pub struct Barcode(String); #[Object] impl Barcode { pub async fn number(&self) -> String { format!("barcode:{}", self.0) } } pub struct Qrcode(String); #[Object] impl Qrcode { pub async fn number(&self) -> String { format!("qrcode:{}", self.0) } } #[derive(Interface)] #[graphql(field(desc = "The article number.", name = "number", type = "Code"))] pub enum Article { Book(Book), } pub struct Book { code: String, } #[Object] impl Book { pub async fn number(&self) -> Barcode { Barcode(self.code.clone()) } } struct Query; #[Object] impl Query { pub async fn book(&self) -> Article { Book { code: "123456".to_string(), } .into() } } let schema = Schema::new(Query, EmptyMutation, EmptySubscription); assert_eq!( schema .execute("{ book { number { number } } }") .await .into_result() .unwrap() .data, value!({ "book": { "number": { "number": "barcode:123456" } } }) ); }
use gimli::X86_64; use crate::registers::Registers; type UnwindPayload<'a> = &'a mut dyn FnMut(Registers); pub fn registers<F>(mut f: F) where F: FnMut(Registers) { let mut f = &mut f as UnwindPayload; unsafe { unwind_trampoline(&mut f) }; } #[allow(improper_ctypes)] // trampoline just forwards the ptr extern "C" { #[cfg(not(feature = "asm"))] pub fn unwind_trampoline(payload: *mut UnwindPayload); #[cfg(not(feature = "asm"))] fn unwind_lander(regs: *const LandingRegisters); } #[cfg(feature = "asm")] #[naked] pub unsafe extern fn unwind_trampoline(_payload: *mut UnwindPayload) { asm!(" movq %rsp, %rsi .cfi_def_cfa rsi, 8 pushq %rbp .cfi_offset rbp, -16 pushq %rbx pushq %r12 pushq %r13 pushq %r14 pushq %r15 movq %rsp, %rdx subq 0x08, %rsp .cfi_def_cfa rsp, 0x40 call unwind_recorder addq 0x38, %rsp .cfi_def_cfa rsp, 8 ret "); ::std::hint::unreachable_unchecked(); } #[cfg(feature = "asm")] #[naked] unsafe extern fn unwind_lander(_regs: *const LandingRegisters) { asm!(" movq %rdi, %rsp popq %rax popq %rbx popq %rcx popq %rdx popq %rdi popq %rsi popq %rbp popq %r8 popq %r9 popq %r10 popq %r11 popq %r12 popq %r13 popq %r14 popq %r15 movq 0(%rsp), %rsp ret // HYPERSPACE JUMP :D "); ::std::hint::unreachable_unchecked(); } #[repr(C)] struct LandingRegisters { rax: u64, rbx: u64, rcx: u64, rdx: u64, rdi: u64, rsi: u64, rbp: u64, r8: u64, r9: u64, r10: u64, r11: u64, r12: u64, r13: u64, r14: u64, r15: u64, rsp: u64, // rflags? cs,fs,gs? } #[repr(C)] pub struct SavedRegs { pub r15: u64, pub r14: u64, pub r13: u64, pub r12: u64, pub rbx: u64, pub rbp: u64, } #[no_mangle] pub unsafe extern "C" fn unwind_recorder(payload: *mut UnwindPayload, stack: u64, saved_regs: *mut SavedRegs) { let payload = &mut *payload; let saved_regs = &*saved_regs; let mut registers = Registers::default(); registers[X86_64::RBX] = Some(saved_regs.rbx); registers[X86_64::RBP] = Some(saved_regs.rbp); registers[X86_64::RSP] = Some(stack + 8); registers[X86_64::R12] = Some(saved_regs.r12); registers[X86_64::R13] = Some(saved_regs.r13); registers[X86_64::R14] = Some(saved_regs.r14); registers[X86_64::R15] = Some(saved_regs.r15); registers[X86_64::RA] = Some(*(stack as *const u64)); payload(registers); } pub unsafe fn land(regs: &Registers) { let mut lr = LandingRegisters { rax: regs[X86_64::RAX].unwrap_or(0), rbx: regs[X86_64::RBX].unwrap_or(0), rcx: regs[X86_64::RCX].unwrap_or(0), rdx: regs[X86_64::RDX].unwrap_or(0), rdi: regs[X86_64::RDI].unwrap_or(0), rsi: regs[X86_64::RSI].unwrap_or(0), rbp: regs[X86_64::RBP].unwrap_or(0), r8: regs[X86_64::R8 ].unwrap_or(0), r9: regs[X86_64::R9 ].unwrap_or(0), r10: regs[X86_64::R10].unwrap_or(0), r11: regs[X86_64::R11].unwrap_or(0), r12: regs[X86_64::R12].unwrap_or(0), r13: regs[X86_64::R13].unwrap_or(0), r14: regs[X86_64::R14].unwrap_or(0), r15: regs[X86_64::R15].unwrap_or(0), rsp: regs[X86_64::RSP].unwrap(), }; lr.rsp -= 8; *(lr.rsp as *mut u64) = regs[X86_64::RA].unwrap(); unwind_lander(&lr); }