text
stringlengths
8
4.13M
use rink::{load, one_line}; command!(calc(_ctx, msg, args) { let mut ctx = load()?; ctx.short_output = true; let output = match one_line(&mut ctx, &args.full()) { Ok(r) => r, Err(e) => e }; msg.reply(&output)?; });
use crate::components::{ Bot, CarryComponent, EnergyComponent, OwnedEntity, PositionComponent, Resource, }; use crate::indices::{EntityId, UserId}; use crate::scripting_api::OperationResult; use crate::storage::views::View; use crate::tables::traits::Table; use serde::{Deserialize, Serialize}; use tracing::debug; pub const DROPOFF_RANGE: u32 = 1; #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct DropoffIntent { pub bot: EntityId, pub structure: EntityId, pub amount: u16, pub ty: Resource, } type CheckInput<'a> = ( View<'a, EntityId, Bot>, View<'a, EntityId, OwnedEntity>, View<'a, EntityId, PositionComponent>, View<'a, EntityId, CarryComponent>, View<'a, EntityId, EnergyComponent>, ); /// A valid dropoff intent has the following characteristics: /// - the bot is owned by the user /// - the bot is carrying resource of type `ty` /// - the target is not full /// - the target is within dropoff range pub fn check_dropoff_intent( intent: &DropoffIntent, userid: UserId, (bots, owners, positions, carry, energy): CheckInput, ) -> OperationResult { let id = intent.bot; match bots.get(id) { Some(_) => { let owner_id = owners.get(id); if owner_id.map(|id| id.owner_id != userid).unwrap_or(true) { return OperationResult::NotOwner; } } None => return OperationResult::InvalidInput, }; if carry.get(id).map(|carry| carry.carry == 0).unwrap_or(true) { return OperationResult::Empty; } let target = intent.structure; let nearby = positions.get(id).and_then(|botpos| { positions.get(target).map(|targetpos| { targetpos.0.room == botpos.0.room && targetpos.0.pos.hex_distance(botpos.0.pos) <= DROPOFF_RANGE }) }); match nearby { None => { debug!("Bot or target has no position components {:?}", intent); OperationResult::InvalidInput } Some(false) => OperationResult::NotInRange, Some(true) => { let capacity = energy.get(target); if capacity.is_none() { debug!("Target has no energy component {:?}", intent); return OperationResult::InvalidInput; } let capacity = capacity.unwrap(); if capacity.energy < capacity.energy_max { OperationResult::Ok } else { OperationResult::Full } } } }
use std::fs; use aoc20::days::day7; #[test] fn day7_parse_bag() { assert_eq!(day7::Bag::parse("1 wavy maroon bag"), Some(day7::Bag::new(String::from("wavy maroon"), 1)) ); assert_eq!(day7::Bag::parse("5 clear tan bags."), Some(day7::Bag::new(String::from("clear tan"), 5)) ); assert_eq!(day7::Bag::parse("no other bags."), None ); } #[test] fn day7_parse_line() { assert_eq!( day7::Rule::parse("light lavender bags contain 1 dotted black bag, 1 wavy maroon bag, 5 pale white bags, 1 clear tan bag."), day7::Rule::new( day7::Bag::parse("1 light lavender bags").unwrap(), vec![ day7::Bag::parse("1 dotted black bag").unwrap(), day7::Bag::parse("1 wavy maroon bag").unwrap(), day7::Bag::parse("5 pale white bags").unwrap(), day7::Bag::parse("1 clear tan bag").unwrap() ] ) ); assert_eq!( day7::Rule::parse("dotted black bags contain no other bags."), day7::Rule::new( day7::Bag::parse("1 dotted black bags").unwrap(), vec![] ) ); } #[test] fn day7_part1() { let contents = fs::read_to_string("data/day7example.txt") .expect("Something went wrong reading the file"); let rules: Vec<day7::Rule> = contents.lines().map(|l| day7::Rule::parse(l)).collect(); assert_eq!(day7::part1("shiny gold", &rules), 4); } #[test] fn day7_part2() { let contents = fs::read_to_string("data/day7example.txt") .expect("Something went wrong reading the file"); let rules: Vec<day7::Rule> = contents.lines().map(|l| day7::Rule::parse(l)).collect(); assert_eq!(day7::part2("shiny gold", &rules), 32); } #[test] fn day7_part2_sample2() { let contents = fs::read_to_string("data/day7example2.txt") .expect("Something went wrong reading the file"); let rules: Vec<day7::Rule> = contents.lines().map(|l| day7::Rule::parse(l)).collect(); assert_eq!(day7::part2("shiny gold", &rules), 126); }
#[doc = "Reader of register PWR_CTRL_SM_ST"] pub type R = crate::R<u32, super::PWR_CTRL_SM_ST>; #[doc = "Reader of field `PWR_CTRL_SM_CURR_STATE`"] pub type PWR_CTRL_SM_CURR_STATE_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:3 - This register reflects the current state of the LL Power Control FSM 4'h0 - IDLE 4'h1 - SLEEP 4'h2 - DEEP_SLEEP 4'h4 - WAIT_OSC_STABLE 4'h5 - INTR_GEN 4'h6 - ACTIVE 4'h7 - REQ_RF_OFF"] #[inline(always)] pub fn pwr_ctrl_sm_curr_state(&self) -> PWR_CTRL_SM_CURR_STATE_R { PWR_CTRL_SM_CURR_STATE_R::new((self.bits & 0x0f) as u8) } }
use super::super::super::super::{awesome, btn, modeless, text}; use super::super::super::state::{chat, dicebot, Modal, Modeless}; use super::Msg; use crate::{ block::{self, chat::item::Sender, BlockId}, model::{self}, Color, Resource, }; use kagura::prelude::*; use wasm_bindgen::JsCast; mod common { pub use super::super::common::*; } pub fn render( block_field: &block::Field, resource: &Resource, modeless_id: model::modeless::ModelessId, modeless: &model::Modeless<Modeless>, grabbed: Option<model::modeless::ModelessId>, chat_state: &chat::State, dicebot_state: &dicebot::State, chat_data: &block::Chat, personal_data: &model::PersonalData, selecting_tab_id: &BlockId, selecting_tab: &block::chat::Tab, ) -> Html { let take_num = chat_state.take_num(); let is_grabbed = grabbed.is_some(); super::frame( modeless_id, modeless, Attributes::new(), Events::new(), vec![ super::header( modeless_id, grabbed, Attributes::new().class("frame-header-tab"), Events::new(), chat_tab_list(block_field, chat_data, selecting_tab_id), ), modeless::body( Attributes::new() .class("linear-v") .style("grid-template-rows", "1fr"), Events::new().on_mousemove(move |e| { if !is_grabbed { e.stop_propagation(); } Msg::NoOp }), vec![ Html::div( Attributes::new() .class("container-a linear-v") .style("align-self", "stretch") .style("grid-template-rows", "max-content max-content 1fr"), Events::new(), vec![ Html::div( Attributes::new().class("keyvalueoption").class("pure-form"), Events::new(), vec![ text::div("Name"), Html::input( Attributes::new().value(selecting_tab.name()), Events::new().on_input({ let selecting_tab_id = selecting_tab_id.clone(); move |name| Msg::SetChatTabName(selecting_tab_id, name) }), vec![], ), btn::danger( Attributes::new(), Events::new().on_click({ let selecting_tab_id = selecting_tab_id.clone(); move |_| Msg::RemoveChatTab(selecting_tab_id) }), vec![awesome::i("fa-times")], ), ], ), if selecting_tab.len() > take_num { btn::secondary( Attributes::new(), Events::new().on_click({ let selecting_tab_id = selecting_tab_id.clone(); move |_| Msg::OpenModal(Modal::ChatLog(selecting_tab_id)) }), vec![Html::text("全履歴を表示")], ) } else { Html::div(Attributes::new(), Events::new(), vec![]) }, chat_item_list(block_field, resource, selecting_tab, take_num), ], ), Html::div( Attributes::new() .class("pure-form linear-v") .style("grid-template-rows", "1fr"), Events::new(), vec![ Html::div(Attributes::new(), Events::new(), vec![]), Html::div( Attributes::new().class("keyvalueoption"), Events::new(), dicebot_menu(dicebot_state), ), Html::div( Attributes::new() .class("keyvalueoption") .class("keyvalueoption-align-stretch"), Events::new(), sender_list(block_field, resource, personal_data, chat_state), ), Html::textarea( Attributes::new() .style("resize", "none") .class("text-wrap") .value(chat_state.inputing_message()), Events::new() .on_input(Msg::SetInputingChatMessage) .on_keydown(|e| { if e.key_code() == 13 && !e.shift_key() && !e.ctrl_key() && !e.alt_key() { e.prevent_default(); Msg::SendInputingChatMessage } else { Msg::NoOp } }), vec![], ), Html::div( Attributes::new().class("justify-r"), Events::new(), vec![Html::div( Attributes::new().class("linear-h"), Events::new(), vec![btn::info( Attributes::new(), Events::new().on_click(|_| Msg::SendInputingChatMessage), vec![awesome::i("fa-paper-plane"), Html::text(" 送信")], )], )], ), ], ), ], ), modeless::footer(Attributes::new(), Events::new(), vec![]), ], ) } fn chat_item_list( block_field: &block::Field, resource: &Resource, selecting_tab: &block::chat::Tab, take_num: usize, ) -> Html { Html::div( Attributes::new() .style("align-self", "stretch") .class("scroll-v") .id("chat-area"), Events::new(), selecting_tab .iter() .rev() .take(take_num) .rev() .filter_map(|(timestamp, item_id)| { block_field .get::<block::chat::Item>(item_id) .map(|item| (timestamp, item)) }) .map(|(timestamp, item)| chat_item(resource, timestamp, item)) .collect(), ) } fn chat_item(resource: &Resource, timestamp: f64, item: &block::chat::Item) -> Html { Html::div( Attributes::new().class("pure-form chat-item"), Events::new(), vec![ common::chat_icon( Attributes::new().class("icon-medium").class("chat-icon"), item.icon(), item.display_name(), resource, ), Html::div( Attributes::new().class("chat-args").class("linear-h"), Events::new(), vec![ Html::span( Attributes::new(), Events::new(), vec![Html::text(item.display_name())], ), Html::span( Attributes::new(), Events::new(), vec![Html::text( js_sys::Date::new(&wasm_bindgen::JsValue::from(timestamp)) .to_locale_string("ja-JP", object! {}.as_ref()) .as_string() .unwrap_or(String::from("")), )], ), Html::span( Attributes::new().class("aside"), Events::new(), vec![Html::text(String::from("@") + item.peer_id())], ), ], ), Html::div( Attributes::new().class("chat-payload"), Events::new(), vec![ Html::div( Attributes::new().class("text-wrap"), Events::new(), vec![Html::text(item.text())], ), if let Some(reply) = item.reply() { Html::div( Attributes::new().class("text-wrap"), Events::new(), vec![Html::text(reply)], ) } else { Html::none() }, ], ), ], ) } fn chat_tab_list( block_field: &block::Field, chat_data: &block::Chat, selecting_tab_id: &BlockId, ) -> Html { Html::div( Attributes::new(), Events::new(), vec![ chat_data .tabs() .iter() .enumerate() .filter_map(|(tab_idx, tab_id)| { block_field .get::<block::chat::Tab>(tab_id) .map(|tab| (tab_idx, tab_id, tab)) }) .map(|(tab_idx, tab_id, tab)| { btn::frame_tab( *tab_id == *selecting_tab_id, false, Events::new().on_click(move |_| Msg::SetSelectingChatTabIdx(tab_idx)), tab.name(), ) }) .collect(), vec![btn::transparent( Attributes::new(), Events::new().on_click(|_| Msg::AddChatTab), vec![awesome::i("fa-plus")], )], ] .into_iter() .flatten() .collect(), ) } fn dicebot_menu(dicebot_state: &dicebot::State) -> Vec<Html> { vec![ Html::div( Attributes::new().style("justify-self", "right"), Events::new(), vec![Html::text("ダイスボット")], ), text::div( dicebot_state .bcdice() .system_info() .map(|system_info| system_info.name().to_string()) .unwrap_or("[未選択]".to_string()), ), btn::secondary( Attributes::new(), Events::new().on_click(|_| Msg::OpenModal(Modal::DicebotSelecter)), vec![Html::text("編集")], ), ] } fn sender_list( block_field: &block::Field, resource: &Resource, personal_data: &model::PersonalData, chat_state: &chat::State, ) -> Vec<Html> { vec![ Html::div( Attributes::new().style("justify-self", "right"), Events::new(), vec![Html::text("送信元")], ), Html::div( Attributes::new() .class("flex-h") .class("flex-padding") .class("centering-v-i"), Events::new(), chat_state .senders() .iter() .enumerate() .map(|(idx, sender)| { sender_item( block_field, resource, personal_data, idx, sender, idx == chat_state.selecting_sender_idx(), ) }) .collect(), ), btn::secondary( Attributes::new(), Events::new().on_click(|_| Msg::OpenModal(Modal::SenderCharacterSelecter)), vec![Html::text("編集")], ), ] } fn sender_item( block_field: &block::Field, resource: &Resource, personal_data: &model::PersonalData, sender_idx: usize, sender: &Sender, is_selected: bool, ) -> Html { use block::chat::item::Icon; let attrs = if is_selected { Attributes::new().class("icon-selected") } else { Attributes::new() }; if let Some((icon, name)) = match sender { Sender::User => { let icon = personal_data .icon() .map(|icon_id| Icon::Resource(icon_id.clone())) .unwrap_or(Icon::DefaultUser); Some((icon, personal_data.name())) } Sender::Character(character_id) => { if let Some(character) = block_field.get::<block::Character>(character_id) { let icon = character .texture_id() .map(|r_id| Icon::Resource(r_id.clone())) .unwrap_or(Icon::DefaultUser); Some((icon, character.name())) } else { None } } _ => None, } { Html::div( Attributes::new() .class("chat-sender") .string("data-sender-idx", sender_idx.to_string()), Events::new().on_click(move |_| Msg::SetSelectingChatSenderIdx(sender_idx)), vec![ common::chat_icon( attrs.class("clickable").class("icon-small").title(name), &icon, name, resource, ), Html::span( Attributes::new().class("chat-sender-text"), Events::new(), vec![Html::text(name)], ), ], ) } else { Html::none() } }
use volatile::Volatile; // VGA text buffer address const VGA_ADDRESS: usize = 0xb8000; // Text buffer width and height const VGA_BUF_WIDTH: usize = 80; const VGA_BUF_HEIGHT: usize = 25; // Struct that represents a single character, each is 2 bytes // See https://en.wikipedia.org/wiki/VGA-compatible_text_mode#Text_buffer for desc #[repr(C)] pub struct VGAChar { vga_char: u8, vga_attr: u8, } // Struct that just represents a VGA text buffer of size VGA_BUF_WIDTH x VGA_BUF_HEIGHT #[repr(transparent)] struct VGABuffer { buf: [ [Volatile<VGAChar>; VGA_BUF_WIDTH]; VGA_BUF_HEIGHT ], } // VGA Buffer writer pub struct VGAWriter { col: u8, vga_buffer: &'static mut VGABuffer, } impl VGAWriter { pub fn write_char(&mut self, vga_char: VGAChar) { // TODO: row/col tracking logic self.vga_buffer.buf[0][0].write(vga_char); } } // https://stackoverflow.com/questions/45534149/how-can-i-initialize-fields-of-a-struct-in-static-context lazy_static! { pub static ref VGA_WRITER: VGAWriter = VGAWriter { col: 0, vga_buffer: unsafe { &mut *(VGA_ADDRESS as *mut VGABuffer) }, }; }
pub struct EventBuilder { pending_event: EventBuilderState, } /// Event data sent by server #[derive(Debug, PartialEq, Clone)] pub struct Event { /// Represents message `id` field. Default "". pub id: String, /// Represents message `event` field. Default "message". pub type_: String, /// Represents message `data` field. Default "". pub data: String, } #[derive(Debug, PartialEq, Clone)] pub enum EventBuilderState { Empty, Pending(Event), Complete(Event), } impl Event { pub fn new(type_: &str, data: &str) -> Event { Event { id: String::from(""), type_: String::from(type_), data: String::from(data), } } } impl EventBuilder { pub fn new() -> EventBuilder { EventBuilder { pending_event: EventBuilderState::Empty, } } pub fn update(&mut self, message: &str) -> EventBuilderState { if message == "" { self.finalize_event(); } else if !message.starts_with(":") && message.contains(":") { self.pending_event = self.update_event(message); } self.get_event() } fn finalize_event(&mut self) { self.pending_event = match self.pending_event { EventBuilderState::Complete(_) => EventBuilderState::Empty, EventBuilderState::Pending(ref event) => EventBuilderState::Complete(event.clone()), ref e => e.clone(), }; } fn update_event(&mut self, message: &str) -> EventBuilderState { let mut pending_event = match &self.pending_event { EventBuilderState::Pending(ref e) => e.clone(), _ => Event::new("message", ""), }; match parse_field(message) { ("data", value) => pending_event.data = String::from(value), ("event", value) => pending_event.type_ = String::from(value), ("id", value) => pending_event.id = String::from(value), _ => {} } EventBuilderState::Pending(pending_event) } pub fn clear(&mut self) { self.pending_event = EventBuilderState::Empty; } pub fn get_event(&self) -> EventBuilderState { self.pending_event.clone() } } fn parse_field<'a>(message: &'a str) -> (&'a str, &'a str) { let parts: Vec<&str> = message.splitn(2, ":").collect(); (parts[0], parts[1].trim()) } #[cfg(test)] mod tests { use super::*; #[test] fn should_start_with_empty_state() { let e = EventBuilder::new(); assert_eq!(e.get_event(), EventBuilderState::Empty); } #[test] fn should_set_message_as_default_event_type() { let mut e = EventBuilder::new(); e.update("data: test"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event.type_, String::from("message")); } else { panic!("event should be pending"); } } #[test] fn should_change_status_to_complete_when_empty_message_received() { let mut e = EventBuilder::new(); e.update("data: test"); e.update(""); if let EventBuilderState::Complete(event) = e.get_event() { assert_eq!(event.data, String::from("test")); } else { panic!("event should be complete"); } } #[test] fn should_remain_as_empty_if_empty_message_is_received_while_buffer_is_empty() { let mut e = EventBuilder::new(); e.update(""); assert_eq!(e.get_event(), EventBuilderState::Empty); } #[test] fn should_fill_data_field() { let mut e = EventBuilder::new(); e.update("data: test"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event.data, String::from("test")); } else { panic!("event should be pending"); } } #[test] fn should_fill_event_type_field() { let mut e = EventBuilder::new(); e.update("event: some_event"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event.type_, String::from("some_event")); } else { panic!("event should be pending"); } } #[test] fn should_fill_event_id_field() { let mut e = EventBuilder::new(); e.update("id: 123abc"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event.id, String::from("123abc")); } else { panic!("event should be pending"); } } #[test] fn should_incrementally_fill_event_fields() { let expected_event = Event::new("some_event", "test"); let mut e = EventBuilder::new(); e.update("event: some_event"); e.update("data: test"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event, expected_event); } else { panic!("event should be pending"); } } #[test] fn should_change_status_to_empty_when_event_is_complete_and_empty_message_is_received() { let mut e = EventBuilder::new(); e.update("data: test"); e.update(""); e.update(""); assert_eq!(e.get_event(), EventBuilderState::Empty); } #[test] fn should_start_clean_event_after_previous_is_completed() { let expected_event = Event::new("message", "test2"); let mut e = EventBuilder::new(); e.update("event: some_event"); e.update("data: test"); e.update(""); e.update("data: test2"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event, expected_event); } else { panic!("event should be pending"); } } #[test] fn should_ignore_updates_started_with_colon() { let expected_event = Event::new("some_event", "test"); let mut e = EventBuilder::new(); e.update("event: some_event"); e.update(":some commentary"); e.update("data: test"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event, expected_event); } else { panic!("event should be pending"); } } #[test] fn should_return_event_on_update() { let mut e = EventBuilder::new(); assert_eq!(e.update("event: some_event"), e.get_event()); assert_eq!(e.update("data: test"), e.get_event()); } #[test] fn should_parse_messages_even_with_colons() { let expected_event = Event::new("some:id:with:colons", "some:data:with:colons"); let mut e = EventBuilder::new(); e.update("event: some:id:with:colons"); e.update("data: some:data:with:colons"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event, expected_event); } else { panic!("event should be pending"); } } #[test] fn should_be_empty_when_only_comments_received() { let mut e = EventBuilder::new(); e.update(":hi"); e.update(""); assert_eq!(e.get_event(), EventBuilderState::Empty); } #[test] fn should_ignore_messages_without_colon() { let expected_event = Event::new("some_event", "test"); let mut e = EventBuilder::new(); e.update("event: some_event"); e.update("this is a random message that should be ignored"); e.update("data: test"); if let EventBuilderState::Pending(event) = e.get_event() { assert_eq!(event, expected_event); } else { panic!("event should be pending"); } } }
#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case)] #[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(feature = "gen")] { // include!(concat!(env!("OUT_DIR"), "/config.rs")); include!(concat!(env!("OUT_DIR"), "/raw.rs")); } else { // include!("config.rs"); include!("raw.rs"); } }
use rand::Rng; use genetic_architecture::{Chromosome, Gamete, GeneticArchitecture, Individual}; pub struct UniformSampler { } pub trait IndividualSampler { fn sample<R: Rng>(&mut self, genetic_architecture: &GeneticArchitecture, rng: &mut R) -> Individual; } impl UniformSampler { pub fn new() -> UniformSampler { UniformSampler { } } } impl IndividualSampler for UniformSampler { fn sample<R: Rng>(&mut self, gen_arch: &GeneticArchitecture, rng: &mut R) -> Individual { let mut individual: Individual = Vec::new(); let n_gamete = gen_arch.n_gametes; for chrom_arch in gen_arch.chromosome_architectures.iter() { let mut chromosome: Chromosome = Vec::new(); for _ in 0..n_gamete { let mut gamete: Gamete = Vec::new(); for alleles_per_locus in &chrom_arch.n_alleles_per_locus { let allele = rng.gen_range(0u8, *alleles_per_locus); gamete.push(allele); } chromosome.push(gamete); } individual.push(chromosome); } individual } }
mod CapriCore; mod gltfimporttest; mod ShapelVRM; use std::io::Error; const WINDOW_WIDTH: u32 = 800; const WINDOW_HEIGHT: u32 = 800; use winapi::um::winnt::{HRESULT, LPCWSTR}; use winapi::shared::minwindef::{LPARAM, LRESULT, UINT, WPARAM, HINSTANCE, FALSE, TRUE}; use winapi::shared::windef::{HICON, HWND, RECT, HWND__, POINT}; use winapi::um::winuser::{MB_OK, MessageBoxW, WM_DESTROY, PostQuitMessage, WNDCLASSEXW, AdjustWindowRect, WS_OVERLAPPEDWINDOW, RegisterClassExW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, WS_VISIBLE, UnregisterClassW, LoadCursorW, IDC_ARROW, CS_OWNDC, AdjustWindowRectEx, ShowWindow, SW_SHOW, PeekMessageW, MSG, TranslateMessage, DispatchMessageW, WM_QUIT, PM_REMOVE, WS_OVERLAPPED}; use winapi::um::d3d12::{D3D12GetDebugInterface, ID3D12Device, D3D12CreateDevice, D3D12_COMMAND_LIST_TYPE_DIRECT, ID3D12CommandAllocator, ID3D12GraphicsCommandList, D3D12_COMMAND_QUEUE_DESC, D3D12_COMMAND_QUEUE_FLAG_NONE, D3D12_COMMAND_QUEUE_PRIORITY_NORMAL, ID3D12CommandQueue, D3D12_DESCRIPTOR_HEAP_DESC, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, ID3D12DescriptorHeap, ID3D12Resource, D3D12_CPU_DESCRIPTOR_HANDLE, ID3D12CommandList, D3D12_RESOURCE_BARRIER, D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, D3D12_RESOURCE_TRANSITION_BARRIER, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_ALIASING_BARRIER, D3D12_FENCE_FLAG_NONE, D3D12_INPUT_ELEMENT_DESC, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, D3D12_APPEND_ALIGNED_ELEMENT, D3D_ROOT_SIGNATURE_VERSION_1_0, D3D12_VIEWPORT, D3D12_RECT, ID3D12Object}; use winapi::um::d3d12sdklayers::{ID3D12Debug, ID3D12DebugDevice, D3D12_RLDO_DETAIL, D3D12_RLDO_IGNORE_INTERNAL}; use winapi::shared::dxgi1_6::{IDXGIFactory6}; use winapi::shared::dxgi1_3::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_DEBUG}; use winapi::shared::dxgi1_2::{DXGI_SWAP_CHAIN_DESC1, DXGI_SCALING_STRETCH, DXGI_ALPHA_MODE_UNSPECIFIED}; use winapi::shared::winerror::{S_OK}; use winapi::um::d3dcommon::{D3D_FEATURE_LEVEL_12_1, ID3DInclude, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; use winapi::um::libloaderapi::{GetModuleHandleW}; use winapi::um::unknwnbase::{IUnknown}; use winapi::Interface; use std::ptr::null_mut; use winapi::shared::dxgi1_5::IDXGISwapChain4; use winapi::shared::dxgiformat::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; use winapi::shared::dxgi::{DXGI_SWAP_EFFECT_FLIP_DISCARD, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH, DXGI_SWAP_CHAIN_DESC}; use winapi::shared::dxgitype::{DXGI_USAGE_BACK_BUFFER, DXGI_SAMPLE_DESC}; use winapi::ctypes::c_void; use crate::CapriCore::cp_directx12::{to_wide_chars, CpID3D12Device, CpIDXGIFactory6, CpMSG, CpD3D12_RESOURCE_BARRIER, CpID3DBlob, CpID3D12RootSignature, CpEventW,CpHWND}; use crate::gltfimporttest::gltfimport; use crate::CapriCore::cp_directx12::CpD3d12ResourceBarrierDescType::CpD3d12ResourceTransitionBarrier; use winapi::um::synchapi::{CreateEventA, CreateEventExW, WaitForSingleObject, CreateEventW}; use winapi::um::winbase::INFINITE; use winapi::um::handleapi::CloseHandle; use winapi::um::d3dcompiler::{D3D_COMPILE_STANDARD_FILE_INCLUDE, D3DCOMPILE_DEBUG, D3DCOMPILE_SKIP_OPTIMIZATION}; use std::ffi::CString; use crate::CapriCore::cp_default_value::CpD3D12_GRAPHICS_PIPELINE_STATE_DESC; use crate::CapriCore::cp_default_value::CpD3D12_ROOT_SIGNATURE_DESC; use nalgebra::Point; use crate::ShapelVRM::{ShapelObject, DrawObj}; use std::env; trait HRESULTChecker { fn hresult_to_result(self) -> Result<i32, i32>; } impl HRESULTChecker for HRESULT { fn hresult_to_result(self) -> Result<HRESULT, HRESULT> { match self { S_OK => Ok(self), _ => Err(self) } } } extern "system" fn window_procedure(hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) -> LRESULT { match msg { WM_DESTROY => unsafe { PostQuitMessage(0) }, _ => return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }, }; return 0; } fn print_message(msg: &str) -> Result<i32, Error> { use std::ffi::OsStr; use std::iter::once; use std::os::windows::ffi::OsStrExt; let wide: Vec<u16> = OsStr::new(msg).encode_wide().chain(once(0)).collect(); let ret = unsafe { MessageBoxW(null_mut(), wide.as_ptr(), wide.as_ptr(), MB_OK) }; if ret == 0 { Err(Error::last_os_error()) } else { Ok(ret) } } fn main() { { let mut _id3d12debug = null_mut(); unsafe { if D3D12GetDebugInterface(&ID3D12Debug::uuidof(), &mut _id3d12debug) == 0 { if let Some(deb) = (_id3d12debug as *mut ID3D12Debug).as_ref() { deb.EnableDebugLayer(); deb.Release(); println!("OKDebug!"); } } } } ///CpID3D12Deviceの作成はID3D12Debugの後で行うこと。C++で確認済み。デバッグレイヤーが正常に動かないため let mut _id3d12device = CpID3D12Device::new(); { let mut _id3d12debugDev = null_mut(); unsafe { if _id3d12device.0.QueryInterface(&ID3D12DebugDevice::uuidof(), &mut _id3d12debugDev) == 0 { if let Some(deb) = (_id3d12debugDev as *mut ID3D12DebugDevice).as_ref() { deb.ReportLiveDeviceObjects(D3D12_RLDO_DETAIL | D3D12_RLDO_IGNORE_INTERNAL); deb.Release(); println!("OKDebug!"); } } } } let stack = 1; let addst = &stack; let heap = Box::new(1); let addhp = &heap; println!("last OS error: {:?}", Error::last_os_error()); let mut hwnd = CpHWND::new(None, None); hwnd.cp_show_window(SW_SHOW); let mut _dxgi_factory = CpIDXGIFactory6::new(); let mut _id3d12_command_queue = _id3d12device.cp_create_command_queue(None).unwrap_or_else(|v| { panic!("last OS error: {:?}", Error::last_os_error()) }); let _dxgi_swap_chain4 = _dxgi_factory.cp_create_swap_chain_for_hwnd(&mut _id3d12_command_queue, &mut hwnd, None).unwrap_or_else(|v| { panic!("last OS error: {:?}", v) }); let swapchain_view_number = _dxgi_swap_chain4.desc.BufferCount; let heap_desc_for_swapchain = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: _dxgi_swap_chain4.desc.BufferCount, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; let _id3d12descripterheap_for_swapchain = _id3d12device.cp_create_descriptor_heap(Some(heap_desc_for_swapchain)).unwrap_or_else(|v| { panic!("last OS error: {:?}", v) }); //ID3D12ResourceはCPU と GPU の物理メモリまたはヒープへの一般的な読み書きの能力をカプセル化します。 // シェーダサンプリング用に最適化された多次元データだけでなく、単純なデータの配列を整理して操作するための抽象化が含まれています。 for index in 0..swapchain_view_number { let mut _swap_res = _dxgi_swap_chain4.cp_get_buffer(index).unwrap_or_else(|v| { panic!("last OS error: {:?}", v) }); let mut handle = _id3d12descripterheap_for_swapchain.cp_get_cpudescriptor_handle_for_heap_start(); _id3d12device.cp_create_render_target_view(&mut _swap_res, None, handle.cp_descriptor_handle_increment_ptr(&_id3d12device, index)); } let mut _id3d12commanddispacher = _id3d12device.cp_create_command_dispacher(0, &_id3d12_command_queue, 1, None).unwrap_or_else(|v| { panic!("last OS error: {:?}", Error::last_os_error()) }); let mut _id3d12fence = _id3d12device.cp_create_fence(1, D3D12_FENCE_FLAG_NONE).unwrap_or_else(|v| { panic!("last OS error: {:?}", Error::last_os_error()) }); let defstr = "Asset\\shapell_Mtoon.vrm".to_string(); let args: Vec<String> = env::args().collect(); let query = args.get(1).unwrap_or(&defstr); let mut shapel_object = ShapelObject::new(&_id3d12device, &_id3d12_command_queue, query.as_ref()); loop { let mut cpmsg = CpMSG::cp_peek_message_w(null_mut(), 0, 0, PM_REMOVE); if cpmsg.hasMessage { cpmsg.cp_translate_message(); cpmsg.cp_dispatch_message_w(); } if cpmsg.cp_has_wm_quit_message() { break; } let clearcolor: [f32; 4] = [0.0, 1.0, 1.0, 1.0]; let current_buff_index = _dxgi_swap_chain4.cp_get_current_back_buffer_index(); let mut current_sw_heaps = _id3d12descripterheap_for_swapchain.cp_get_cpudescriptor_handle_for_heap_start().cp_descriptor_handle_increment_ptr(&_id3d12device, current_buff_index); let mut transition_barrier_desc = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: _dxgi_swap_chain4.cp_get_buffer(current_buff_index).unwrap_or_else(|v| { panic!("last OS error: {:?}", v) }).value, Subresource: 0, StateBefore: D3D12_RESOURCE_STATE_PRESENT, StateAfter: D3D12_RESOURCE_STATE_RENDER_TARGET, }; let barrier_desc = CpD3D12_RESOURCE_BARRIER::new(CpD3d12ResourceTransitionBarrier { d3d12_resource_transition_barrier: transition_barrier_desc, flags: 0 }); _id3d12commanddispacher.cp_reset(&mut None); _id3d12commanddispacher.command_lists[0].cp_resource_barrier(&vec![barrier_desc]); _id3d12commanddispacher.command_lists[0].cp_clear_render_target_view(&current_sw_heaps.value, &clearcolor, None); transition_barrier_desc.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; transition_barrier_desc.StateAfter = D3D12_RESOURCE_STATE_PRESENT; let barrier_desc = CpD3D12_RESOURCE_BARRIER::new(CpD3d12ResourceTransitionBarrier { d3d12_resource_transition_barrier: transition_barrier_desc, flags: 0 }); _id3d12commanddispacher.command_lists[0].cp_resource_barrier(&vec![barrier_desc]); _id3d12commanddispacher.command_lists[0].cp_close(); _id3d12commanddispacher.cp_execute_command_lists(); shapel_object.Update(current_sw_heaps, transition_barrier_desc); _id3d12fence.cp_increment_counter(1); _id3d12_command_queue.cp_signal(&mut _id3d12fence); if (!_id3d12fence.cp_is_reach_fance_value()) { let mut event = CpEventW::cp_create_event_w(None, false, false, None).unwrap_or_else(|| panic!("last OS error: {:?}", Error::last_os_error())); _id3d12fence.cp_set_event_on_completion(&mut event); event.cp_wait_for_single_object(INFINITE); event.cp_CloseHandlet(); } _dxgi_swap_chain4.cp_present(1, 0); } println!("last OS error: {:?}", Error::last_os_error()); if let Err(v) = print_message("Hello, world!") { println!("{}", v) } //unsafe { UnregisterClassW(_wndclassexw.lpszClassName, _wndclassexw.hInstance); } hwnd.cp_unregister_class_w(); }
//mod client; //mod model; // //pub use self::client::get; //pub use self::model::RequestParameters;
#[doc = "Register `QUADSPI_FCR` writer"] pub type W = crate::W<QUADSPI_FCR_SPEC>; #[doc = "Field `CTEF` writer - CTEF"] pub type CTEF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CTCF` writer - CTCF"] pub type CTCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CSMF` writer - CSMF"] pub type CSMF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CTOF` writer - CTOF"] pub type CTOF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl W { #[doc = "Bit 0 - CTEF"] #[inline(always)] #[must_use] pub fn ctef(&mut self) -> CTEF_W<QUADSPI_FCR_SPEC, 0> { CTEF_W::new(self) } #[doc = "Bit 1 - CTCF"] #[inline(always)] #[must_use] pub fn ctcf(&mut self) -> CTCF_W<QUADSPI_FCR_SPEC, 1> { CTCF_W::new(self) } #[doc = "Bit 3 - CSMF"] #[inline(always)] #[must_use] pub fn csmf(&mut self) -> CSMF_W<QUADSPI_FCR_SPEC, 3> { CSMF_W::new(self) } #[doc = "Bit 4 - CTOF"] #[inline(always)] #[must_use] pub fn ctof(&mut self) -> CTOF_W<QUADSPI_FCR_SPEC, 4> { CTOF_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "QUADSPI flag clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`quadspi_fcr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct QUADSPI_FCR_SPEC; impl crate::RegisterSpec for QUADSPI_FCR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [`quadspi_fcr::W`](W) writer structure"] impl crate::Writable for QUADSPI_FCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets QUADSPI_FCR to value 0"] impl crate::Resettable for QUADSPI_FCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use proc_macro2::TokenStream; use crate::util::{ ident_from_str }; use crate::attributes::{ get_field_type, ParentDataType, FieldDataType, get_expose_attribute }; mod derivable; pub mod from_bits; pub mod from_bytes; pub mod from_reader; pub mod from_slice; use derivable::{ Derivable, get_derivable}; ///Collects the data for the fields in a first attribute reading pass //TODO: //1) Split_point pass //2) clause pass //permanent bytes declare at the top of FromReader /* //if the parent type is from_reader and the first field is not from_reader //push the first array on the arrays vec if parent_data_type == ParentDataType::FromReader && data_types[0] != FieldDataType::FromReader { push_array_name(&mut arrays, &mut array_count); } } */ //(Clauses, declares) pub fn build_clauses(fields: &syn::Fields, predicate : syn::Expr, parent_data_type : ParentDataType) -> (Vec<TokenStream>, Vec<TokenStream>, TokenStream) { let (split_points, preceeding_bits, field_types, derivables, total_size_in_bits, expose_attributes, idents) = get_field_data(fields, predicate, parent_data_type); let mut clauses : Vec<TokenStream> = Vec::new(); let mut declares : Vec<TokenStream> = Vec::new(); //start at 1 because we're always reading in the next set of bytes let mut split_count = 1; //add the 0th bytes array if(parent_data_type == ParentDataType::FromReader) { let first_size = &split_points[0]; declares.push(quote! { let bytes : [u8; #first_size]; reader.read_exact(&mut bytes).await? }); } for i in 0..derivables.len() { let mut clause : TokenStream = match field_types[i] { FieldDataType::FromBits => from_bits::get_field(parent_data_type, derivables[i].clone(), &preceeding_bits[i]), FieldDataType::FromBytes => from_bytes::get_field(parent_data_type, derivables[i].clone(), &preceeding_bits[i]), //FieldDataType::FromSlice => from_slice::get_field(parent_data_type, derivable.clone(), &preceeding_bits), FieldDataType::FromReader => { let result = from_reader::get_field(parent_data_type, derivables[i].clone(), &preceeding_bits[i]); match parent_data_type == ParentDataType::FromReader { true => { //TODO: bits to bytes(split_point_size)?? let next_size = &split_points[split_count]; split_count += 1; quote! { #result bytes = [u8;#next_size]; reader.read_exact(&mut bytes).await?; } }, false => result } }, //TODO: Payload _ => unimplemented!("Lol gottem!") }; //Option wrapper here clause = match &derivables[i] { //We've got an option type so we're going to match //on the expression given in the attribute Derivable::InsideOption(typ, ident) => quote!{ { match #ident { true => Some(#clause), false => None } } }, //do nothing Derivable::Naked(typ) => clause }; //if this field is #[expose = ""] then push the declaration clause = match &expose_attributes[i] { Some(ident) => { let raw_type = derivables[i].get_raw(); declares.push(quote!{ let #ident : #raw_type; }); quote!{ { let result : #raw_type = #clause; //TODO: Don't clone #ident = result.clone(); result } } }, None => clause }; //the full clause associated with this var //this unwraps to return a derivable //if this field has an identifier then tack it on the front of the clause clauses.push(match &idents[i] { Some(ident) => quote!{ #ident : #clause }, None => clause }); } (clauses, declares, total_size_in_bits) } fn get_field_data(fields: &syn::Fields, predicate : syn::Expr, parent_data_type : ParentDataType) -> ( Vec<TokenStream>, Vec<TokenStream>, Vec<FieldDataType>, Vec<Derivable>, TokenStream, Vec<Option<syn::Ident>>, Vec<Option<syn::Ident>>) { let mut sizes : Vec<syn::Expr> = Vec::new(); let mut current_sizes_slice : Vec<syn::Expr> = Vec::new(); let mut preceeding_sizes : Vec<TokenStream> = Vec::new();//2 let mut field_types : Vec<FieldDataType> = Vec::new();//3 let mut derivables : Vec<Derivable> = Vec::new();//4 let mut split_points : Vec<TokenStream> = Vec::new();//1 let mut expose_attributes : Vec<Option<syn::Ident>> = Vec::new();//5 let mut idents : Vec<Option<syn::Ident>> = Vec::new(); for field in fields.iter() { let data_type : FieldDataType = get_field_type(&field.attrs, &parent_data_type); println!("Field Type : {:#?}", data_type); //collect the field_data_types in a first pass map() field_types.push(data_type); //collect all the var types let derivable = get_derivable(&field); derivables.push(derivable.clone()); let preceeding_bits = quote! { (#(#current_sizes_slice)+*) }; //if the parent is a reader and this type is a reader then the preceeding bits need to be reset //because this is the start of a new buffer //TODO: decide if there needs to be more done //flag for reading in bytes into the buffer? //or can we tell from this if statement and just read the number of bytes from here until the next from reader or the end if(parent_data_type == ParentDataType::FromReader && data_type == FieldDataType::FromReader) { split_points.push(preceeding_bits.clone()); current_sizes_slice.clear(); } preceeding_sizes.push(preceeding_bits); //push our size to the sizes vec sizes.push(derivable.get_size_in_bits()); //if this field is #[expose = ""] then push the declaration //TODO: move to get data fn below let expose_attribute = get_expose_attribute(&field.attrs); expose_attributes.push(expose_attribute); idents.push(field.ident.clone()); } let total_size_in_bits = quote! {( #(#sizes)+*) }; (split_points, preceeding_sizes, field_types, derivables, total_size_in_bits, expose_attributes, idents) }
use rand::prelude::*; use crate::data::EOByte; /// used for encoding/decoding packet data /// /// Packets are encrypted in three steps: /// 1. Flipping /// 2. Interleaving /// 3. "dickwinding" /// /// ## Flipping /// Each byte of the packet has their most significant bits flipped /// ```text /// for i in 0..length { /// bytes[i] ^= 0x80; /// } /// ``` /// /// ## Interleaving /// Bytes are "woven" in to each-other e.g. /// ```text /// abcde -> aebdc /// or /// abcdef -> afbecd /// ``` /// /// ## Dickwinding /// This was named by Sausage and first implemented in the EOProxy project. /// There are two numbers sent from the server to the client on connect /// between 6 and 12 that represent a "send packet swap multiple" /// and a "receive packet swap multiple". /// /// Any two bytes next to each other in the packet data that are /// divisible by that number are swapped. /// /// For more details see [Packet](https://eoserv.net/wiki/wiki?page=Packet) /// /// # Examples /// /// Encoding a local chat message /// ``` /// use eo::net::PacketProcessor; /// /// // Talk_Report packet with a message /// let mut packet_bytes = [ /// 21, 18, 145, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33 /// ]; /// // Data: ‘Hello, world! /// let processor = PacketProcessor::with_multiples(0, 6); /// processor.encode(&mut packet_bytes); /// assert_eq!(packet_bytes, [ /// 149, 161, 146, 228, 17, 242, 200, 236, 229, 239, 236, 247, 236, 160, 239, 172 /// ]); /// // Encoded data: •¡’äòÈìåïì÷ì ï¬ /// ``` /// #[derive(Default)] pub struct PacketProcessor { pub decode_multiple: EOByte, pub encode_multiple: EOByte, } impl PacketProcessor { /// creates a new PacketProcessor with random encode/decode multiples pub fn new() -> Self { let mut rng = thread_rng(); Self { decode_multiple: rng.gen_range(6, 12), encode_multiple: rng.gen_range(6, 12), } } /// creates a new PacketProcessor with the provided encode/decode multiples pub fn with_multiples(decode_multiple: EOByte, encode_multiple: EOByte) -> Self { Self { decode_multiple, encode_multiple, } } /// sets the internal encode/decode multiples to the values provided pub fn set_multiples(&mut self, decode_multiple: EOByte, encode_multiple: EOByte) { self.decode_multiple = decode_multiple; self.encode_multiple = encode_multiple; } fn swap_multiples(&self, bytes: &mut [EOByte], multiple: EOByte) { let bytes_length = bytes.len(); let mut sequence_length: usize = 0; for i in 0..bytes_length { if bytes[i] % multiple == 0 { sequence_length += 1; } else { if sequence_length > 1 { let start = i - sequence_length; let end = start + sequence_length - 1; for i in 0..sequence_length / 2 { bytes.swap(start + i, end - i); } } sequence_length = 0; } } if sequence_length > 1 { let start = bytes_length - sequence_length; let end = start + sequence_length - 1; for i in 0..sequence_length / 2 { bytes.swap(start + i, end - i); } } } fn valid_for_decode(&self, bytes: &[EOByte]) -> bool { self.decode_multiple != 0 && bytes[0] != 0xFF && bytes[1] != 0xFF } fn valid_for_encode(&self, bytes: &[EOByte]) -> bool { self.encode_multiple != 0 && bytes[0] != 0xFF && bytes[1] != 0xFF } /// decodes a packet byte array in place /// /// Init_Init packets are ignored pub fn decode(&self, bytes: &mut [EOByte]) { if self.valid_for_decode(bytes) { let length = bytes.len(); let mut buf: Vec<EOByte> = vec![0; length]; let big_half = (length + 1) / 2; let little_half = length / 2; for i in 0..big_half { buf[i] = bytes[i * 2]; } for i in 0..little_half { buf[length - 1 - i] = bytes[(i * 2) + 1]; } for i in 0..length { bytes[i] = buf[i] ^ 0x80; if bytes[i] == 0 { bytes[i] = 128; } else if bytes[i] == 128 { bytes[i] = 0; } } self.swap_multiples(bytes, self.decode_multiple); } } /// encodes a packet byte array in place /// /// Init_Init packets are ignored #[allow(clippy::needless_range_loop)] pub fn encode(&self, bytes: &mut [EOByte]) { if self.valid_for_encode(bytes) { let length = bytes.len(); let mut buf: Vec<EOByte> = vec![0; length]; self.swap_multiples(bytes, self.encode_multiple); for i in 0..length { if bytes[i] == 0 { bytes[i] = 128; } else if bytes[i] == 128 { bytes[i] = 0; } } let big_half = (length + 1) / 2; let little_half = length / 2; for i in 0..big_half { buf[i * 2] = bytes[i]; } for i in 0..little_half { buf[(i * 2) + 1] = bytes[length - 1 - i]; } for i in 0..length { bytes[i] = buf[i] ^ 0x80; } } } } #[cfg(test)] mod tests { use super::PacketProcessor; #[test] fn decode() { let mut bytes = [ 149, 161, 146, 228, 17, 242, 200, 236, 229, 239, 236, 247, 236, 160, 239, 172, ]; let packet_processor = PacketProcessor::with_multiples(6, 0); packet_processor.decode(&mut bytes); assert_eq!( [21, 18, 145, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33], bytes ); } #[test] fn encode() { let mut bytes = [ 3, 5, 2, 254, 2, 254, 2, 254, 254, 254, 6, 254, 249, 18, 77, 177, 145, 91, 254, 251, 44, 36, 34, 239, 2, 2, 254, 254, 254, 52, 2, 48, 178, 184, 46, 33, 254, 155, 78, 178, 222, 9, 254, 114, 111, 98, 111, 116, 255, 255, 255, 255, 3, 32, 32, 32, 1, 18, 197, 93, 11, 254, 22, 2, 254, 254, 168, 254, 168, 254, 243, 254, 243, 254, 55, 254, 1, 254, 52, 254, 242, 4, 25, 254, 29, 254, 11, 254, 12, 254, 8, 254, 42, 254, 9, 254, 8, 254, 14, 254, 3, 254, 1, 254, 83, 254, 238, 254, 15, 2, 44, 254, 170, 2, 51, 254, 181, 254, 172, 2, 203, 2, 43, 254, 43, 254, 41, 254, 41, 254, 55, 254, 55, 254, 1, 77, 254, 5, 254, 25, 25, 1, 254, 1, 254, 1, 254, 3, 254, 1, 255, ]; let packet_processor = PacketProcessor::with_multiples(0, 10); packet_processor.encode(&mut bytes); assert_eq!( [ 131, 127, 133, 129, 130, 126, 126, 131, 130, 126, 126, 129, 130, 126, 126, 129, 126, 126, 126, 129, 134, 153, 126, 153, 121, 126, 146, 133, 205, 126, 49, 205, 17, 129, 219, 126, 126, 183, 123, 126, 172, 183, 164, 126, 162, 169, 111, 126, 130, 169, 130, 126, 126, 171, 126, 126, 126, 171, 180, 130, 130, 75, 176, 130, 50, 44, 56, 126, 174, 53, 161, 126, 126, 179, 27, 130, 206, 42, 50, 126, 94, 172, 137, 130, 126, 143, 242, 126, 239, 110, 226, 126, 239, 211, 244, 126, 127, 129, 127, 126, 127, 131, 127, 126, 131, 142, 160, 126, 160, 136, 160, 126, 129, 137, 146, 126, 69, 170, 221, 126, 139, 136, 126, 126, 150, 140, 130, 126, 126, 139, 126, 126, 40, 157, 126, 126, 40, 153, 126, 132, 115, 114, 126, 126, 115, 180, 126, 126, 183, 129, 126 ], bytes ); } #[test] fn do_not_encode_init() { let mut bytes = [ 255, 255, 21, 191, 11, 1, 1, 29, 113, 10, 50, 57, 55, 50, 54, 53, 48, 55, 56, ]; let packet_processor = PacketProcessor::with_multiples(0, 0); packet_processor.encode(&mut bytes); assert_eq!( [255, 255, 21, 191, 11, 1, 1, 29, 113, 10, 50, 57, 55, 50, 54, 53, 48, 55, 56], bytes ); } #[test] fn do_not_decode_init() { let mut bytes = [ 255, 255, 21, 191, 11, 1, 1, 29, 113, 10, 50, 57, 55, 50, 54, 53, 48, 55, 56, ]; let packet_processor = PacketProcessor::with_multiples(0, 0); packet_processor.decode(&mut bytes); assert_eq!( [255, 255, 21, 191, 11, 1, 1, 29, 113, 10, 50, 57, 55, 50, 54, 53, 48, 55, 56], bytes ); } #[test] fn set_multiples() { let mut packet_processor = PacketProcessor::new(); packet_processor.set_multiples(12, 6); assert_eq!(packet_processor.decode_multiple, 12); assert_eq!(packet_processor.encode_multiple, 6); } }
use crate::renderer::managers::FontDetails; use crate::renderer::managers::TextDetails; use crate::renderer::renderer::Renderer; use crate::renderer::TextureManager; use crate::ui::text_character::CharacterSizeManager; use crate::ui::CanvasAccess; use rider_config::Config; use rider_config::ConfigAccess; use rider_config::ConfigHolder; use sdl2::pixels::{Color, PixelFormatEnum}; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::render::{Texture, TextureCreator}; use sdl2::ttf::{Font, Sdl2TtfContext}; use std::collections::HashMap; use std::fmt::Debug; use std::fmt::Error; use std::fmt::Formatter; use std::path::PathBuf; use std::rc::Rc; use std::sync::*; #[cfg_attr(tarpaulin, skip)] pub fn build_path(path: String) { use std::fs; fs::create_dir_all(path.as_str()).unwrap(); fs::write((path.clone() + &"/file1".to_owned()).as_str(), "foo").unwrap(); fs::write((path.clone() + &"/file2".to_owned()).as_str(), "bar").unwrap(); fs::create_dir_all((path.clone() + &"/dir1".to_owned()).as_str()).unwrap(); fs::create_dir_all((path.clone() + &"/dir2".to_owned()).as_str()).unwrap(); } #[cfg_attr(tarpaulin, skip)] pub fn build_config() -> Arc<RwLock<Config>> { let mut config = Config::new(); config.set_theme(config.editor_config().current_theme().clone()); Arc::new(RwLock::new(config)) } #[cfg_attr(tarpaulin, skip)] #[derive(Debug, PartialEq)] pub enum CanvasShape { Line, Border, Rectangle, Image(Rect, Rect, String), } #[cfg_attr(tarpaulin, skip)] #[derive(Debug, PartialEq)] pub struct RendererRect { pub rect: Rect, pub color: Color, pub shape: CanvasShape, } #[cfg_attr(tarpaulin, skip)] impl RendererRect { pub fn new(rect: Rect, color: Color, shape: CanvasShape) -> Self { Self { rect, color, shape } } } #[cfg_attr(tarpaulin, skip)] pub struct CanvasMock { pub rects: Vec<RendererRect>, pub borders: Vec<RendererRect>, pub lines: Vec<RendererRect>, pub clippings: Vec<Option<Rect>>, pub character_sizes: HashMap<char, sdl2::rect::Rect>, } #[cfg_attr(tarpaulin, skip)] impl Debug for CanvasMock { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!( f, "CanvasMock {{ {:?} {:?} {:?} }}", self.rects, self.lines, self.clippings ) } } #[cfg_attr(tarpaulin, skip)] impl PartialEq for CanvasMock { fn eq(&self, other: &CanvasMock) -> bool { self.rects == other.rects && self.borders == other.borders && self.clippings == other.clippings && self.lines == other.lines } } #[cfg_attr(tarpaulin, skip)] impl CanvasMock { pub fn new() -> Self { Self { rects: vec![], borders: vec![], lines: vec![], clippings: vec![], character_sizes: HashMap::new(), } } } #[cfg_attr(tarpaulin, skip)] impl CanvasAccess for CanvasMock { fn render_rect(&mut self, rect: Rect, color: Color) -> Result<(), String> { self.rects.push(RendererRect { rect, color, shape: CanvasShape::Rectangle, }); Ok(()) } fn render_border(&mut self, rect: Rect, color: Color) -> Result<(), String> { self.borders.push(RendererRect { rect, color, shape: CanvasShape::Border, }); Ok(()) } fn render_image(&mut self, _tex: Rc<Texture>, src: Rect, dest: Rect) -> Result<(), String> { self.rects.push(RendererRect::new( dest.clone(), Color::RGBA(0, 0, 0, 255), CanvasShape::Image(src.clone(), dest.clone(), format!("_tex: Rc<Texture>")), )); Ok(()) } fn render_line(&mut self, start: Point, end: Point, color: Color) -> Result<(), String> { self.lines.push(RendererRect { rect: Rect::new(start.x(), start.y(), end.x() as u32, end.y() as u32), color, shape: CanvasShape::Line, }); Ok(()) } fn set_clipping(&mut self, rect: Rect) { self.clippings.push(Some(rect)); } fn set_clip_rect(&mut self, rect: Option<Rect>) { self.clippings.push(rect); } fn clip_rect(&self) -> Option<Rect> { self.clippings.last().cloned().unwrap_or_else(|| None) } } #[cfg_attr(tarpaulin, skip)] impl CharacterSizeManager for CanvasMock { fn load_character_size(&mut self, c: char) -> Rect { match self.character_sizes.get(&c) { Some(r) => r.clone(), None => { self.character_sizes.insert(c, Rect::new(0, 0, 1, 1)); self.character_sizes.get(&c).cloned().unwrap() } } } } #[cfg_attr(tarpaulin, skip)] pub trait CanvasTester { fn set_character_rect(&mut self, c: char, rect: Rect); fn find_pixel_with_color( &self, point: sdl2::rect::Point, color: sdl2::pixels::Color, ) -> Option<&RendererRect>; fn find_rect_with_color( &self, subject: sdl2::rect::Rect, color: sdl2::pixels::Color, ) -> Option<&RendererRect>; fn find_line_with_color( &self, subject: sdl2::rect::Rect, color: sdl2::pixels::Color, ) -> Option<&RendererRect>; fn find_border_with_color( &self, subject: sdl2::rect::Rect, color: sdl2::pixels::Color, ) -> Option<&RendererRect>; } #[cfg_attr(tarpaulin, skip)] impl CanvasTester for CanvasMock { fn set_character_rect(&mut self, c: char, rect: Rect) { self.character_sizes.insert(c, rect); } fn find_pixel_with_color( &self, point: sdl2::rect::Point, color: sdl2::pixels::Color, ) -> Option<&RendererRect> { for rect in self.rects.iter() { if rect.rect.contains_point(point.clone()) && rect.color == color { return Some(rect.clone()); } } for rect in self.borders.iter() { if rect.rect.contains_point(point.clone()) && rect.color == color { return Some(rect.clone()); } } for rect in self.lines.iter() { if rect.rect.contains_point(point.clone()) && rect.color == color { return Some(rect.clone()); } } None } fn find_rect_with_color( &self, subject: sdl2::rect::Rect, color: sdl2::pixels::Color, ) -> Option<&RendererRect> { for rect in self.rects.iter() { if rect.rect == subject && rect.color == color { return Some(rect.clone()); } } None } fn find_line_with_color( &self, subject: sdl2::rect::Rect, color: sdl2::pixels::Color, ) -> Option<&RendererRect> { for rect in self.lines.iter() { if rect.rect == subject && rect.color == color { return Some(rect.clone()); } } None } fn find_border_with_color( &self, subject: sdl2::rect::Rect, color: sdl2::pixels::Color, ) -> Option<&RendererRect> { for rect in self.borders.iter() { if rect.rect == subject && rect.color == color { return Some(rect.clone()); } } None } } #[cfg_attr(tarpaulin, skip)] pub struct SimpleRendererMock<'l> { pub config: ConfigAccess, pub ttf: Sdl2TtfContext, pub character_sizes: HashMap<char, Rect>, pub texture_manager: TextureManager<'l, sdl2::surface::SurfaceContext<'l>>, } #[cfg_attr(tarpaulin, skip)] impl<'l> SimpleRendererMock<'l> { pub fn set_character_rect(&mut self, c: char, rect: Rect) { self.character_sizes.insert(c, rect); } pub fn texture_creator(&self) -> &TextureCreator<sdl2::surface::SurfaceContext<'l>> { self.texture_manager.loader() } } #[cfg_attr(tarpaulin, skip)] impl<'l> Renderer for SimpleRendererMock<'l> { fn load_font(&mut self, details: FontDetails) -> Rc<Font> { Rc::new( self.ttf .load_font(details.path, details.size) .unwrap_or_else(|e| panic!("{:?}", e)), ) } fn load_text_tex( &mut self, _details: &mut TextDetails, _font_details: FontDetails, ) -> Result<Rc<Texture>, String> { self.texture_creator() .create_texture( PixelFormatEnum::RGB24, sdl2::render::TextureAccess::Target, 24, 24, ) .map_err(|e| format!("{:?}", e)) .map(|t| Rc::new(t)) } fn load_image(&mut self, path: String) -> Result<Rc<Texture>, String> { self.texture_manager.load(path.as_str()) } } #[cfg_attr(tarpaulin, skip)] impl<'l> CharacterSizeManager for SimpleRendererMock<'l> { fn load_character_size(&mut self, c: char) -> Rect { match self.character_sizes.get(&c) { Some(r) => r.clone(), _ => { let rect = Rect::new(0, 0, 13, 14); self.set_character_rect(c.clone(), rect.clone()); rect } } } } #[cfg_attr(tarpaulin, skip)] impl<'l> ConfigHolder for SimpleRendererMock<'l> { fn config(&self) -> &Arc<RwLock<Config>> { &self.config } } #[cfg_attr(tarpaulin, skip)] pub type TestCanvas<'r> = sdl2::render::Canvas<sdl2::surface::Surface<'r>>; #[cfg_attr(tarpaulin, skip)] impl<'r> CanvasAccess for TestCanvas<'r> { fn render_rect(&mut self, rect: Rect, color: sdl2::pixels::Color) -> Result<(), String> { self.set_draw_color(color); self.fill_rect(rect) } fn render_border(&mut self, rect: Rect, color: sdl2::pixels::Color) -> Result<(), String> { self.set_draw_color(color); self.draw_rect(rect) } fn render_image(&mut self, tex: Rc<Texture>, src: Rect, dest: Rect) -> Result<(), String> { self.copy_ex(&tex, Some(src), Some(dest), 0.0, None, false, false) } fn render_line( &mut self, start: Point, end: Point, color: sdl2::pixels::Color, ) -> Result<(), String> { self.set_draw_color(color); self.draw_line(start, end) } fn set_clipping(&mut self, rect: Rect) { self.set_clip_rect(rect); } fn set_clip_rect(&mut self, rect: Option<Rect>) { self.set_clip_rect(rect); } fn clip_rect(&self) -> Option<Rect> { self.clip_rect() } } #[cfg_attr(tarpaulin, skip)] pub trait DumpImage { fn dump_ui<S>(&self, path: S) where S: Into<String>; } #[cfg_attr(tarpaulin, skip)] impl<'r> DumpImage for TestCanvas<'r> { fn dump_ui<S>(&self, path: S) where S: Into<String>, { let p = std::path::PathBuf::from(path.into()); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); self.surface() .save_bmp(p) .expect("Failed to save canvas as BMP file"); } }
#[doc = "Register `ETH_DMAC0RxDLAR` reader"] pub type R = crate::R<ETH_DMAC0RX_DLAR_SPEC>; #[doc = "Register `ETH_DMAC0RxDLAR` writer"] pub type W = crate::W<ETH_DMAC0RX_DLAR_SPEC>; #[doc = "Field `RDESLA` reader - Start of Receive List"] pub type RDESLA_R = crate::FieldReader<u32>; #[doc = "Field `RDESLA` writer - Start of Receive List"] pub type RDESLA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 29, O, u32>; impl R { #[doc = "Bits 3:31 - Start of Receive List"] #[inline(always)] pub fn rdesla(&self) -> RDESLA_R { RDESLA_R::new((self.bits >> 3) & 0x1fff_ffff) } } impl W { #[doc = "Bits 3:31 - Start of Receive List"] #[inline(always)] #[must_use] pub fn rdesla(&mut self) -> RDESLA_W<ETH_DMAC0RX_DLAR_SPEC, 3> { RDESLA_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Channel Rx descriptor list address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0rx_dlar::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`eth_dmac0rx_dlar::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ETH_DMAC0RX_DLAR_SPEC; impl crate::RegisterSpec for ETH_DMAC0RX_DLAR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`eth_dmac0rx_dlar::R`](R) reader structure"] impl crate::Readable for ETH_DMAC0RX_DLAR_SPEC {} #[doc = "`write(|w| ..)` method takes [`eth_dmac0rx_dlar::W`](W) writer structure"] impl crate::Writable for ETH_DMAC0RX_DLAR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ETH_DMAC0RxDLAR to value 0x8000"] impl crate::Resettable for ETH_DMAC0RX_DLAR_SPEC { const RESET_VALUE: Self::Ux = 0x8000; }
// --------------------------------------------------------------------- // Config Reader // --------------------------------------------------------------------- // Copyright (C) 2007-2021 The NOC Project // See LICENSE for details // --------------------------------------------------------------------- use super::FileReader; use crate::config::ZkConfig; use crate::error::AgentError; use async_trait::async_trait; use enum_dispatch::enum_dispatch; #[enum_dispatch] pub enum ConfigReader { File(FileReader), } #[async_trait] #[enum_dispatch(ConfigReader)] pub trait Reader { async fn get_config(&self) -> Result<ZkConfig, AgentError>; } impl ConfigReader { pub fn from_url(url: String) -> Option<ConfigReader> { match ConfigReader::get_schema(url.clone()) { Some(schema) => match &schema[..] { "file" => Some(ConfigReader::File(FileReader { path: url[5..].into(), })), _ => None, }, _ => None, } } fn get_schema(url: String) -> Option<String> { url.find(':').map(|pos| url[..pos].into()) } } // Stub reader for disabled features pub struct StubReader; #[async_trait] impl Reader for StubReader { async fn get_config(&self) -> Result<ZkConfig, AgentError> { Err(AgentError::FeatureDisabledError( "Feature is disabled".into(), )) } }
#[macro_use] extern crate synom; pub mod parser; pub mod ast; use std::ops::Deref; use synom::IResult; use synom::space::*; use self::ast::*; use self::parser::*; /// Parse a VMF string, returning the list of parsed blocks pub fn parse<'a, I, K>(input: &'a I) -> Result<Vec<Block<K>>, &'static str> where I: 'a + Deref<Target=str>, K: From<&'a str> { match file(input) { IResult::Done(rem, ast) => if skip_whitespace(rem) != "" { Err("failed to parse the entire input") } else { Ok(ast) }, IResult::Error => Err("parse error"), } }
/* * Copyright 2020 Damian Peckett <damian@pecke.tt> * * 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 crate::error::*; use crate::kubernetes::deployment::{KubernetesDeploymentObject, KubernetesDeploymentResource}; use crate::kubernetes::replicaset::{KubernetesReplicaSetObject, KubernetesReplicaSetResource}; use crate::kubernetes::statefulset::{KubernetesStatefulSetObject, KubernetesStatefulSetResource}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use enum_dispatch::enum_dispatch; /// Private shared functionality mod common; /// Kubernetes Deployment trait implementations. pub mod deployment; /// Kubernetes ReplicaSet trait implementations. pub mod replicaset; /// Kubernetes StatefulSet trait implementations. pub mod statefulset; /// Kubernetes resource families. #[enum_dispatch] pub enum KubernetesResource { /// A list of apps/v1 Deployment resources. Deployment(KubernetesDeploymentResource), /// A list of apps/v1 ReplicaSet resources. ReplicaSet(KubernetesReplicaSetResource), /// A list of apps/v1 StatefulSet resources. StatefulSet(KubernetesStatefulSetResource), } /// Kubernetes objects, eg deployments etc. #[enum_dispatch] pub enum KubernetesObject { /// An apps/v1 Deployment object. Deployment(KubernetesDeploymentObject), /// An apps/v1 ReplicaSet object. ReplicaSet(KubernetesReplicaSetObject), /// An apps/v1 StatefulSet object. StatefulSet(KubernetesStatefulSetObject), } #[async_trait] #[enum_dispatch(KubernetesResource)] pub trait KubernetesResourceTrait { /// Retrieve a list of matching objects from the k8s api. async fn list(&self) -> Result<Vec<KubernetesObject>, Error>; } #[async_trait] #[enum_dispatch(KubernetesObject)] pub trait KubernetesObjectTrait { /// The namespace and name of the object. fn namespace_and_name(&self) -> (String, String); /// The last time the object was modified by the autoscaler. async fn last_modified(&self) -> Result<Option<DateTime<Utc>>, Error>; /// The current number of replicas. async fn replicas(&self) -> Result<u32, Error>; /// The pod ips of every running pod belonging to this object. async fn pod_ips(&self) -> Result<Vec<String>, Error>; /// Update the number of replicas associated with this object. async fn scale(&self, replicas: u32) -> Result<(), Error>; }
pub fn test() { println!("Hello, world!"); let s: String = "hello, world".to_string(); println!("{}", first_space_index(&s)); println!("{}", first_word_slice("slice first word")); println!("{}", second_word_slice("slice second word")); println!("{}", second_word_slice_2("shouldbeempty")); println!("{}", second_word_slice_2("second \"word\"")); println!("{}", second_word_slice_2("the middle word")); } fn first_space_index(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn first_word_slice(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[..i]; } } &s[..] } fn second_word_slice(s: &str) -> &str { let bytes = s.as_bytes(); let mut first_space = 0; for (i, &item) in bytes.iter().enumerate() { if item == b' ' { if first_space == 0 { first_space = i; } else { return &s[first_space + 1..i]; } } } &s[first_space + 1..] } //TODO: learn to attach debugger in rust fn second_word_slice_2(s: &str) -> &str { // println!("Receiving {}", &s); let bytes = s.as_bytes(); let mut first_space = 0; for (i, &item) in bytes.iter().enumerate() { if item == b' ' { // println!("Setting first_space to {}", i); first_space = i; break; } } if first_space == 0 { // println!("Returning &s[0..0]: {}", &s[0..0]); return &s[0..0]; //should be an error result? dunno how yet } for (i, &item) in bytes[first_space + 1..].iter().enumerate() { if item == b' ' { // println!("Returning &s[{}..{}]: {}", first_space + 1, first_space + 1 + i, &s[first_space + 1..first_space + 1 + i]); return &s[first_space + 1..first_space + 1 + i]; } } // println!("Returning &s[{}..]: {}", first_space + 1, &s[first_space + 1..]); &s[first_space + 1..] }
//! The `write_stage` module implements the TPU's write stage. It //! writes entries to the given writer, which is typically a file or //! stdout, and then sends the Entry to its output channel. use bank::Bank; use cluster_info::ClusterInfo; use counter::Counter; use entry::Entry; use ledger::{Block, LedgerWriter}; use log::Level; use result::{Error, Result}; use service::Service; use signature::Keypair; use std::net::UdpSocket; use std::sync::atomic::AtomicUsize; use std::sync::mpsc::{channel, Receiver, RecvTimeoutError, Sender}; use std::sync::{Arc, RwLock}; use std::thread::{self, Builder, JoinHandle}; use std::time::{Duration, Instant}; use streamer::responder; use timing::{duration_as_ms, duration_as_s}; use vote_stage::send_leader_vote; pub struct WriteStage { thread_hdls: Vec<JoinHandle<()>>, write_thread: JoinHandle<()>, } impl WriteStage { /// Process any Entry items that have been published by the RecordStage. /// continuosly send entries out pub fn write_and_send_entries( cluster_info: &Arc<RwLock<ClusterInfo>>, ledger_writer: &mut LedgerWriter, entry_sender: &Sender<Vec<Entry>>, entry_receiver: &Receiver<Vec<Entry>>, ) -> Result<()> { let mut ventries = Vec::new(); let mut received_entries = entry_receiver.recv_timeout(Duration::new(1, 0))?; let now = Instant::now(); let mut num_new_entries = 0; let mut num_txs = 0; loop { num_new_entries += received_entries.len(); ventries.push(received_entries); if let Ok(n) = entry_receiver.try_recv() { received_entries = n; } else { break; } } inc_new_counter_info!("write_stage-entries_received", num_new_entries); debug!("write_stage entries: {}", num_new_entries); let mut entries_send_total = 0; let mut cluster_info_votes_total = 0; let start = Instant::now(); for entries in ventries { let cluster_info_votes_start = Instant::now(); let votes = &entries.votes(); cluster_info.write().unwrap().insert_votes(&votes); cluster_info_votes_total += duration_as_ms(&cluster_info_votes_start.elapsed()); for e in &entries { num_txs += e.transactions.len(); ledger_writer.write_entry_noflush(&e)?; } inc_new_counter_info!("write_stage-write_entries", entries.len()); //TODO(anatoly): real stake based voting needs to change this //leader simply votes if the current set of validators have voted //on a valid last id trace!("New entries? {}", entries.len()); let entries_send_start = Instant::now(); if !entries.is_empty() { inc_new_counter_info!("write_stage-recv_vote", votes.len()); inc_new_counter_info!("write_stage-entries_sent", entries.len()); trace!("broadcasting {}", entries.len()); entry_sender.send(entries)?; } entries_send_total += duration_as_ms(&entries_send_start.elapsed()); } ledger_writer.flush()?; inc_new_counter_info!( "write_stage-time_ms", duration_as_ms(&now.elapsed()) as usize ); debug!("done write_stage txs: {} time {} ms txs/s: {} entries_send_total: {} cluster_info_votes_total: {}", num_txs, duration_as_ms(&start.elapsed()), num_txs as f32 / duration_as_s(&start.elapsed()), entries_send_total, cluster_info_votes_total); Ok(()) } /// Create a new WriteStage for writing and broadcasting entries. pub fn new( keypair: Arc<Keypair>, bank: Arc<Bank>, cluster_info: Arc<RwLock<ClusterInfo>>, ledger_path: &str, entry_receiver: Receiver<Vec<Entry>>, ) -> (Self, Receiver<Vec<Entry>>) { let (vote_blob_sender, vote_blob_receiver) = channel(); let send = UdpSocket::bind("0.0.0.0:0").expect("bind"); let t_responder = responder( "write_stage_vote_sender", Arc::new(send), vote_blob_receiver, ); let (entry_sender, entry_receiver_forward) = channel(); let mut ledger_writer = LedgerWriter::recover(ledger_path).unwrap(); let write_thread = Builder::new() .name("solana-writer".to_string()) .spawn(move || { let mut last_vote = 0; let mut last_valid_validator_timestamp = 0; let id = cluster_info.read().unwrap().id; loop { if let Err(e) = Self::write_and_send_entries( &cluster_info, &mut ledger_writer, &entry_sender, &entry_receiver, ) { match e { Error::RecvTimeoutError(RecvTimeoutError::Disconnected) => { break; } Error::RecvTimeoutError(RecvTimeoutError::Timeout) => (), _ => { inc_new_counter_info!( "write_stage-write_and_send_entries-error", 1 ); error!("{:?}", e); } } }; if let Err(e) = send_leader_vote( &id, &keypair, &bank, &cluster_info, &vote_blob_sender, &mut last_vote, &mut last_valid_validator_timestamp, ) { inc_new_counter_info!("write_stage-leader_vote-error", 1); error!("{:?}", e); } } }).unwrap(); let thread_hdls = vec![t_responder]; ( WriteStage { write_thread, thread_hdls, }, entry_receiver_forward, ) } } impl Service for WriteStage { type JoinReturnType = (); fn join(self) -> thread::Result<()> { for thread_hdl in self.thread_hdls { thread_hdl.join()?; } self.write_thread.join() } }
fn main() { const INPUT_ROW: usize = 2978; const INPUT_COL: usize = 3083; let mut row = 1; let mut col = 1; let mut val: u64 = 20151125; while !(row == INPUT_ROW && col == INPUT_COL) { val = (val * 252533) % 33554393; if row == 1 { row = col + 1; col = 1; } else { col += 1; row -= 1; } } println!("A: {}", val); }
extern crate gilrs; use self::gilrs::Gilrs; use pixel::*; use ssd1327::*; pub struct Context { pub display: SSD1327, pub gilrs: Gilrs, pub pixel: Pixel, } impl Context { pub fn new(filename: &'static str) -> Context { Context { display: SSD1327::new(filename), gilrs: Gilrs::new().unwrap(), pixel: build_pixel(), } } }
use ferris_base; mod utils; #[test] fn nominal() { let start = vec![ "🦀..........", "🚀..........", "Ro==Wi......", "Fe==U ......", ]; let inputs = vec![ferris_base::core::direction::Direction::DOWN]; let end = vec![ "............", "🚀..........", "Ro==Wi......", "Fe==U ......", ]; let win = utils::assert_evolution(start, inputs, end); assert_eq!(win, true); } #[test] fn simultaneous_you_and_win() { let start = vec![ "Fe==U ......", "==..........", "..Wi🦀......", "............", ]; let inputs = vec![ferris_base::core::direction::Direction::LEFT]; let end = vec![ "Fe==U ......", "==..........", "Wi🦀........", "............", ]; let win = utils::assert_evolution(start, inputs, end); assert_eq!(win, true); }
use super::*; use crate::utils::leak_value; /** The root module of a dynamic library, which may contain other modules,function pointers,and static references. For an example of a type implementing this trait you can look at either the example in the readme for this crate, or the `example/example_*_interface` crates in this crates' repository . */ pub trait RootModule: Sized+SharedStableAbi+'static { /// The name of the dynamic library,which is the same on all platforms. /// This is generally the name of the `implementation crate`. const BASE_NAME: &'static str; /// The name of the library used in error messages. const NAME: &'static str; /// The version number of the library of `Self:RootModule`. /// /// Initialize this with ` package_version_strings!() ` const VERSION_STRINGS: VersionStrings; /// All the constants of this trait and supertraits. /// /// It can safely be used as a proxy for the associated constants of this trait. const CONSTANTS:RootModuleConsts<Self>=RootModuleConsts{ inner:ErasedRootModuleConsts{ base_name:StaticStr::new(Self::BASE_NAME), name:StaticStr::new(Self::NAME), version_strings:Self::VERSION_STRINGS, layout:IsLayoutChecked::Yes(<&Self>::S_LAYOUT), c_abi_testing_fns:crate::library::c_abi_testing::C_ABI_TESTING_FNS, _priv:(), }, _priv:PhantomData, }; /// Like Self::CONSTANTS, /// except without including the type layout constant for the root module. const CONSTANTS_NO_ABI_INFO:RootModuleConsts<Self>={ let mut consts=Self::CONSTANTS; consts.inner.layout=IsLayoutChecked::No; consts }; /// Gets the statics for Self. /// /// To define this associated function use: /// `abi_stable::declare_root_module_statics!{TypeOfSelf}`. /// Passing `Self` instead of `TypeOfSelf` won't work. /// fn root_module_statics()->&'static RootModuleStatics<Self>; /** Gets the root module,returning None if the module is not yet loaded. */ #[inline] fn get_module()->Option<&'static Self>{ Self::root_module_statics().root_mod.get() } /** Gets the RawLibrary of the module, returning None if the dynamic library failed to load (it doesn't exist or layout checking failed). Note that if the root module is initialized using `Self::load_module_with`, this will return None even though `Self::get_module` does not. */ #[inline] fn get_raw_library()->Option<&'static RawLibrary>{ Self::root_module_statics().raw_lib.get() } /// Returns the path the library would be loaded from,given a directory(folder). fn get_library_path(directory:&Path)-> PathBuf { let base_name=Self::BASE_NAME; RawLibrary::path_in_directory(directory, base_name,LibrarySuffix::NoSuffix) } /** Loads the root module,with a closure which either returns the root module or an error. If the root module was already loaded, this will return a reference to the already loaded root module, without calling the closure. */ fn load_module_with<F,E>(f:F)->Result<&'static Self,E> where F:FnOnce()->Result<&'static Self,E> { Self::root_module_statics().root_mod.try_init(f) } /** Loads this module from the path specified by `where_`, first loading the dynamic library if it wasn't already loaded. Once the root module is loaded, this will return a reference to the already loaded root module. # Warning If this function is called within a dynamic library, it must be called at or after the function that exports its root module is called. **DO NOT** call this in the static initializer of a dynamic library, since this library relies on setting up its global state before calling the root module loader. # Errors This will return these errors: - LibraryError::OpenError: If the dynamic library itself could not be loaded. - LibraryError::GetSymbolError: If the root module was not exported. - LibraryError::InvalidAbiHeader: If the abi_stable version used by the library is not compatible. - LibraryError::ParseVersionError: If the version strings in the library can't be parsed as version numbers, this can only happen if the version strings are manually constructed. - LibraryError::IncompatibleVersionNumber: If the version number of the library is incompatible. - LibraryError::AbiInstability: If the layout of the root module is not the expected one. */ fn load_from(where_:LibraryPath<'_>) -> Result<&'static Self, LibraryError>{ let statics=Self::root_module_statics(); statics.root_mod.try_init(||{ let raw_library=load_raw_library::<Self>(where_)?; let items = unsafe{ lib_header_from_raw_library(&raw_library)? }; let root_mod=items.init_root_module::<Self>()?.initialization()?; // Important,If I don't leak the library after sucessfully loading the root module // it would cause any use of the module to be a use after free. let raw_lib=leak_value(raw_library); statics.raw_lib.init(|| raw_lib ); Ok(root_mod) }) } /** Loads this module from the directory specified by `where_`, first loading the dynamic library if it wasn't already loaded. Once the root module is loaded, this will return a reference to the already loaded root module. Warnings and Errors are detailed in `load_from`, */ fn load_from_directory(where_:&Path) -> Result<&'static Self, LibraryError>{ Self::load_from(LibraryPath::Directory(where_)) } /** Loads this module from the file at `path_`, first loading the dynamic library if it wasn't already loaded. Once the root module is loaded, this will return a reference to the already loaded root module. Warnings and Errors are detailed in `load_from`, */ fn load_from_file(path_:&Path) -> Result<&'static Self, LibraryError>{ Self::load_from(LibraryPath::FullPath(path_)) } /// Defines behavior that happens once the module is loaded. /// /// The default implementation does nothing. fn initialization(self: &'static Self) -> Result<&'static Self, LibraryError> { Ok(self) } } /// Loads the raw library at `where_` fn load_raw_library<M>(where_:LibraryPath<'_>) -> Result<RawLibrary, LibraryError> where M:RootModule { let path=match where_ { LibraryPath::Directory(directory)=>{ M::get_library_path(&directory) } LibraryPath::FullPath(full_path)=> full_path.to_owned(), }; RawLibrary::load_at(&path) } /** Gets the LibHeader of a library. # Errors This will return these errors: - LibraryError::GetSymbolError: If the root module was not exported. - LibraryError::InvalidAbiHeader: If the abi_stable used by the library is not compatible. # Safety The LibHeader is implicitly tied to the lifetime of the library, it will contain dangling `'static` references if the library is dropped before it does. */ pub unsafe fn lib_header_from_raw_library( raw_library:&RawLibrary )->Result< &'static LibHeader , LibraryError> { unsafe{ abi_header_from_raw_library(raw_library)?.upgrade() } } /** Gets the AbiHeader of a library. # Errors This will return these errors: - LibraryError::GetSymbolError: If the root module was not exported. # Safety The AbiHeader is implicitly tied to the lifetime of the library, it will contain dangling `'static` references if the library is dropped before it does. */ pub unsafe fn abi_header_from_raw_library( raw_library:&RawLibrary )->Result< &'static AbiHeader , LibraryError> { unsafe{ let mut mangled=mangled_root_module_loader_name(); mangled.push('\0'); let library_getter= raw_library.get::<&'static AbiHeader>(mangled.as_bytes())?; let header:&'static AbiHeader= *library_getter; Ok(header) } } /** Gets the LibHeader of the library at the path. This leaks the underlying dynamic library, if you need to do this without leaking you'll need to use `lib_header_from_raw_library` instead. # Errors This will return these errors: - LibraryError::OpenError: If the dynamic library itself could not be loaded. - LibraryError::GetSymbolError: If the root module was not exported. - LibraryError::InvalidAbiHeader: If the abi_stable version used by the library is not compatible. */ pub fn lib_header_from_path(path:&Path)->Result< &'static LibHeader , LibraryError> { let raw_lib=RawLibrary::load_at(path)?; let library_getter=unsafe{ lib_header_from_raw_library(&raw_lib)? }; mem::forget(raw_lib); Ok(library_getter) } /** Gets the AbiHeader of the library at the path. This leaks the underlying dynamic library, if you need to do this without leaking you'll need to use `lib_header_from_raw_library` instead. # Errors This will return these errors: - LibraryError::OpenError: If the dynamic library itself could not be loaded. - LibraryError::GetSymbolError: If the root module was not exported. */ pub fn abi_header_from_path(path:&Path)->Result< &'static AbiHeader , LibraryError> { let raw_lib=RawLibrary::load_at(path)?; let library_getter=unsafe{ abi_header_from_raw_library(&raw_lib)? }; mem::forget(raw_lib); Ok(library_getter) } ////////////////////////////////////////////////////////////////////// macro_rules! declare_root_module_consts { ( fields=[ $( $(#[$field_meta:meta])* method_docs=$method_docs:expr, $field:ident : $field_ty:ty ),* $(,)* ] ) => ( /// Encapsulates all the important constants of `RootModule` for `M`, /// used mostly to construct a `LibHeader` with `LibHeader::from_constructor`. #[repr(C)] #[derive(StableAbi,Copy,Clone)] pub struct RootModuleConsts<M>{ inner:ErasedRootModuleConsts, _priv:PhantomData<extern "C" fn()->M>, } /// Encapsulates all the important constants of `RootModule` for some erased type. #[repr(C)] #[derive(StableAbi,Copy,Clone)] pub struct ErasedRootModuleConsts{ $( $(#[$field_meta])* $field : $field_ty, )* _priv:(), } impl<M> RootModuleConsts<M>{ /// Gets the type-erased version of this type. pub const fn erased(&self)->ErasedRootModuleConsts{ self.inner } $( #[doc=$method_docs] pub const fn $field(&self)->$field_ty{ self.inner.$field } )* } impl ErasedRootModuleConsts{ $( #[doc=$method_docs] pub const fn $field(&self)->$field_ty{ self.$field } )* } ) } declare_root_module_consts!{ fields=[ method_docs=" The name of the dynamic library,which is the same on all platforms. This is generally the name of the implementation crate.", base_name: StaticStr, method_docs="The name of the library used in error messages.", name: StaticStr, method_docs="The version number of the library this was created from.", version_strings: VersionStrings, method_docs="The (optional) type layout constant of the root module.", layout: IsLayoutChecked, method_docs="\ Functions used to test that the C abi is the same in both the library and the loader\ ", c_abi_testing_fns:&'static CAbiTestingFns, ] }
use crate::libs::gapi::gapi; use crate::libs::idb; use crate::libs::random_id; use crate::libs::skyway::Peer; use crate::model::config::Config; use js_sys::Promise; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; pub async fn initialize() -> Option<( Config, web_sys::IdbDatabase, web_sys::IdbDatabase, String, Peer, String, )> { let config = if let Some(config) = load_config().await { config } else { return None; }; let common_db_name = format!("{}.common", config.client.db_prefix); let room_db_name = format!("{}.room", config.client.db_prefix); let (common_db, client_id) = if let Some(db_props) = initialize_common_db(&common_db_name).await { db_props } else { return None; }; let room_db = unwrap!(idb::open_db(room_db_name.as_ref()).await; None); let peer = if let Some(peer) = initialize_peer_connection(&config.skyway.key).await { peer } else { return None; }; let peer_id = peer.id(); initialize_gapi(&config.drive.api_key, &config.drive.client_id).await; Some((config, common_db, room_db, client_id, peer, peer_id)) } async fn load_config() -> Option<Config> { crate::debug::log_1("start to load config"); let config_url = if crate::is_dev_mode() { "/config.dev.toml" } else { "./config.toml" }; let mut opts = web_sys::RequestInit::new(); opts.method("GET"); opts.mode(web_sys::RequestMode::SameOrigin); let request = web_sys::Request::new_with_str_and_init(config_url, &opts).unwrap(); let response = JsFuture::from(web_sys::window().unwrap().fetch_with_request(&request)) .await .unwrap() .dyn_into::<web_sys::Response>() .unwrap(); toml::from_str::<Config>( &JsFuture::from(response.text().unwrap()) .await .unwrap() .as_string() .unwrap(), ) .ok() } async fn initialize_common_db(db_name: &str) -> Option<(web_sys::IdbDatabase, String)> { if let Some(database) = idb::open_db(db_name).await { if let Some((database, client_id)) = initialize_object_store(database).await { return Some((database, client_id)); } else { crate::debug::log_1("faild to get client_id"); } } else { crate::debug::log_1(format!("faild to open db: {}", db_name)); } None } async fn initialize_object_store( mut database: web_sys::IdbDatabase, ) -> Option<(web_sys::IdbDatabase, String)> { let names = database.object_store_names(); let mut has_client = false; let mut has_rooms = false; let mut has_resources = false; let mut has_tables = false; let mut has_characters = false; for i in 0..names.length() { if let Some(name) = names.item(i) { if name == "client" { has_client = true; } else if name == "rooms" { has_rooms = true; } else if name == "resources" { has_resources = true; } else if name == "tables" { has_tables = true; } else if name == "characters" { has_characters = true; } } } if !has_client { database = unwrap!(idb::create_object_store(&database, "client").await; None); } if !has_rooms { database = unwrap!(idb::create_object_store(&database, "rooms").await; None); } if !has_resources { database = unwrap!(idb::create_object_store(&database, "resources").await; None); } if !has_tables { database = unwrap!(idb::create_object_store(&database, "tables").await; None); } if !has_characters { database = unwrap!(idb::create_object_store(&database, "characters").await; None); } let client_id = idb::query( &database, "client", idb::Query::Get(&JsValue::from("client_id")), ) .await; if let Some(client_id) = client_id.and_then(|x| x.as_string()) { Some((database, client_id)) } else { let client_id = assign_client_id(&database).await; client_id.map(|c_id| (database, c_id)) } } async fn assign_client_id(database: &web_sys::IdbDatabase) -> Option<String> { let client_id = random_id::base64url(); if idb::assign( database, "client", &JsValue::from("client_id"), &JsValue::from(&client_id), ) .await .is_some() { Some(client_id) } else { None } } async fn initialize_peer_connection(key: &str) -> Option<Peer> { let peer = Rc::new(Peer::new(key)); JsFuture::from(Promise::new(&mut move |resolve, _| { let a = Closure::once(Box::new({ let peer = Rc::clone(&peer); move || { let _ = resolve.call1(&js_sys::global(), &peer); } })); peer.on("open", Some(a.as_ref().unchecked_ref())); a.forget(); })) .await .ok() .and_then(|x| x.dyn_into::<Peer>().ok()) } async fn initialize_gapi(api_key: &str, client_id: &str) { let thaneble = gapi.client().init( object! { "apiKey": api_key, "clientId": client_id, "discoveryDocs": array!["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"], "scope": "https://www.googleapis.com/auth/drive.appdata", } .as_ref(), ); let _ = JsFuture::from(Promise::new(&mut move |resolve, reject| { thaneble.then(Some(&resolve), Some(&reject)); })) .await .map_err(|err| crate::debug::log_1(err)); }
extern crate advent_of_code_2017_day_14; use advent_of_code_2017_day_14::*; #[test] fn part_1_example() { let input = "flqrgnkx"; assert_eq!(solve_puzzle_part_1(input), "8108"); } #[test] fn part_2_example() { let input = "flqrgnkx"; assert_eq!(solve_puzzle_part_2(input), "1242"); }
use libc::{c_int, c_void}; #[link(name = "elevatormagic")] extern { pub fn issue_override_code(code: c_int); pub fn poll_override_code() -> c_int; pub fn poll_override_input_floor() -> c_int; pub fn poll_override_error() -> c_int; pub fn poll_override_session() -> *const c_void; pub fn free_override_session(session: *const c_void); pub fn poll_physical_override_privileged_session() -> *const c_void; pub fn poll_physical_override_admin_session() -> *const c_void; pub fn override_input_floor(floor: c_int); pub fn override_manual_mode(); pub fn override_normal_mode(); pub fn override_reset_state(); pub fn elevator_display_flash(pattern: c_int); pub fn elevator_display_toggle_light(light_id: c_int); pub fn elevator_display_set_light_color(light_id: c_int, color: c_int); pub fn is_override() -> c_int; pub fn is_privileged() -> c_int; pub fn is_admin() -> c_int; }
use failure::Error; use rocket::State; use crate::Context; use crate::SID; // // a users links // #[get("/<username>")] pub fn all(ctx: State<Context>, username: String) -> Result<String, Error> { Ok("foo".to_string()) } // // add a link // #[post("/<username>")] pub fn create(ctx: State<Context>, sid: SID, username: String) -> Result<String, Error> { Ok("foo".to_string()) } // // delete a link // #[delete("/<username>/<link_id>")] pub fn delete(ctx: State<Context>, sid: SID, username: String, link_id: String) -> Result<String, Error> { Ok("foo".to_string()) }
use crate::exchange::{Exchange, interface::private::AggressiveOrderType}; use crate::history::{ parser::EventProcessor, types::{HistoryEventBody, OrderOrigin}, }; use crate::lags::interface::NanoSecondGenerator; use crate::order::{LimitOrder, Order}; use crate::trader::Trader; use crate::types::{Direction, OrderID, Price, Size}; struct TRDummyOrder { size: Size, direction: Direction, } impl const Order for TRDummyOrder { fn get_order_id(&self) -> OrderID { unreachable!() } fn get_order_size(&self) -> Size { self.size } fn mut_order_size(&mut self) -> &mut Size { &mut self.size } fn get_order_direction(&self) -> Direction { self.direction } } impl< T: Trader, E: EventProcessor, ObLagGen: NanoSecondGenerator, TrdLagGen: NanoSecondGenerator, WkpLagGen: NanoSecondGenerator, const DEBUG: bool, const TRD_UPDATES_OB: bool, const OB_SUBSCRIPTION: bool, const TRD_SUBSCRIPTION: bool, const WAKEUP_SUBSCRIPTION: bool > Exchange<'_, T, E, ObLagGen, TrdLagGen, WkpLagGen, DEBUG, TRD_UPDATES_OB, OB_SUBSCRIPTION, TRD_SUBSCRIPTION, WAKEUP_SUBSCRIPTION> { pub(crate) fn handle_history_event(&mut self, event: HistoryEventBody) { match event { HistoryEventBody::OrderBookDiff(size, direction, price, order_id) => { self.handle_ob_diff_event(size, direction, price, order_id) } HistoryEventBody::Trade(size, direction) => { self.handle_trd_event(size, direction) } } if let Some(event) = self.event_processor.yield_next_event() { self.event_queue.schedule_history_event(event) } else { self.has_history_events_in_queue = false; } } fn handle_ob_diff_event(&mut self, size: Size, direction: Direction, price: Price, order_id: OrderID) { if size == Size(0) { self.remove_ob_entry(direction, price, order_id) } else if self.history_order_ids.contains(&order_id) { self.update_traded_ob_entry(size, direction, price, order_id) } else { self.insert_limit_order::<LimitOrder, { OrderOrigin::History }>( LimitOrder::new(order_id, size, direction, price) ); self.history_order_ids.insert(order_id); } } fn remove_ob_entry(&mut self, direction: Direction, price: Price, order_id: OrderID) { let mut side_cursor = match direction { Direction::Buy => { self.bids.cursor_front_mut() } Direction::Sell => { self.asks.cursor_front_mut() } }; while let Some(ob_level) = side_cursor.current() { if ob_level.price != price { side_cursor.move_next(); continue; } let mut level_cursor = ob_level.queue.cursor_front_mut(); while let Some(limit_order) = level_cursor.current() { if limit_order.order_id == order_id && limit_order.from == OrderOrigin::History { break; } level_cursor.move_next(); } if let None = level_cursor.remove_current() { if DEBUG { eprintln!( "{} :: \ remove_ob_entry :: ERROR in case of non-trading Trader :: \ Order with such ID {:?} does not exist at the OB level with corresponding price: {:?}", self.current_dt, order_id, price ) } break; } if ob_level.queue.is_empty() { side_cursor.remove_current(); } if !self.history_order_ids.remove(&order_id) && DEBUG { eprintln!( "{} :: \ remove_ob_entry :: ERROR in case of non-trading Trader :: \ History order HashSet does not contain such ID: {:?}", self.current_dt, order_id ) } return; } if DEBUG { eprintln!( "{} :: remove_ob_entry :: ERROR in case of non-trading Trader \ :: History order has not been deleted: {:?}", self.current_dt, order_id ) } } fn update_traded_ob_entry(&mut self, size: Size, direction: Direction, price: Price, order_id: OrderID) { let side = match direction { Direction::Buy => { &mut self.bids } Direction::Sell => { &mut self.asks } }; let ob_level = match side .iter_mut() .skip_while(|level| level.price != price) .next() { Some(ob_level) => { ob_level } None => { if DEBUG { eprintln!( "{} \ :: update_traded_ob_entry :: ERROR in case of non-trading Trader \ :: OB level with such price does not exist: {:?}", self.current_dt, price ); } return; } }; let order = match ob_level.queue .iter_mut() .skip_while(|order| order.order_id != order_id || order.from != OrderOrigin::History ) .next() { Some(order) => { order } None => { if DEBUG { eprintln!( "{} \ :: update_traded_ob_entry :: ERROR in case of non-trading Trader \ :: OB level does not contain history order with such ID: {:?}", self.current_dt, order_id ); } return; } }; order.size = size } fn handle_trd_event(&mut self, size: Size, direction: Direction) { self.insert_aggressive_order::<TRDummyOrder, { AggressiveOrderType::HistoryMarketOrder }>( TRDummyOrder { size, direction } ) } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { pub family: sku::Family, pub name: sku::Name, } pub mod sku { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Family { A, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "standard")] Standard, #[serde(rename = "premium")] Premium, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyEntry { #[serde(rename = "tenantId")] pub tenant_id: String, #[serde(rename = "objectId")] pub object_id: String, #[serde(rename = "applicationId", default, skip_serializing_if = "Option::is_none")] pub application_id: Option<String>, pub permissions: Permissions, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Permissions { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub keys: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub secrets: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub certificates: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VaultProperties { #[serde(rename = "vaultUri", default, skip_serializing_if = "Option::is_none")] pub vault_uri: Option<String>, #[serde(rename = "tenantId")] pub tenant_id: String, pub sku: Sku, #[serde(rename = "accessPolicies")] pub access_policies: Vec<AccessPolicyEntry>, #[serde(rename = "enabledForDeployment", default, skip_serializing_if = "Option::is_none")] pub enabled_for_deployment: Option<bool>, #[serde(rename = "enabledForDiskEncryption", default, skip_serializing_if = "Option::is_none")] pub enabled_for_disk_encryption: Option<bool>, #[serde(rename = "enabledForTemplateDeployment", default, skip_serializing_if = "Option::is_none")] pub enabled_for_template_deployment: Option<bool>, #[serde(rename = "enableSoftDelete", default, skip_serializing_if = "Option::is_none")] pub enable_soft_delete: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VaultCreateOrUpdateParameters { pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub properties: VaultProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Vault { #[serde(flatten)] pub resource: Resource, pub properties: VaultProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VaultListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Vault>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Resource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, pub name: String, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, }
use crate::brick::BrickType; use crate::render::ImageFrame; use sdl2::rect::Rect; use serde::{Deserialize, Serialize}; /// Which image to render when calling `render_image`. This module /// maps the image to the appropriate location in the larger texture. #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)] pub enum Image { RedBrick, GreenBrick, BlueBrick, YellowBrick, OrangeBrick, PurpleBrick, TealBrick, SmokeBrick(u16), Title, PlayingField, } impl ImageFrame for Image { fn source_rect(self) -> Rect { match self { Self::PlayingField => Rect::new(0, 128, 800, 600), Self::Title => Rect::new(0, 64, 440, 65), Self::RedBrick => Rect::new(0, 0, 32, 32), Self::GreenBrick => Rect::new(32, 0, 32, 32), Self::BlueBrick => Rect::new(64, 0, 32, 32), Self::YellowBrick => Rect::new(96, 0, 32, 32), Self::OrangeBrick => Rect::new(128, 0, 32, 32), Self::PurpleBrick => Rect::new(160, 0, 32, 32), Self::TealBrick => Rect::new(192, 0, 32, 32), Self::SmokeBrick(frame) => { if frame > 12 { panic!("unavailable smoke brick, greatest index is 12") } Rect::new((frame * 32) as i32, 32, 32, 32) } } } } impl Image { pub fn max_smoke_frame() -> u16 { 12 } pub fn from_brick_type(brick_type: BrickType) -> Self { use BrickType::*; match brick_type { Red => Image::RedBrick, Green => Image::GreenBrick, Blue => Image::BlueBrick, Yellow => Image::YellowBrick, Orange => Image::OrangeBrick, Purple => Image::PurpleBrick, Teal => Image::TealBrick, Smoke(frame) => Image::SmokeBrick(frame), Attacked => Image::SmokeBrick(0), } } } // -------- // Tests // -------- #[test] #[should_panic] fn test_invalid_smoke_brick() { Image::SmokeBrick(13).source_rect(); } #[test] fn test_valid_smoke_brick() { for i in 0..12 { Image::SmokeBrick(i as u16).source_rect(); } }
use std::ops::Range; use ash::version::DeviceV1_0; use ash::vk; use crate::map_vk_error; use crate::vulkan::{Device, VkError}; pub struct Image { handle: vk::Image, format: vk::Format, requirements: vk::MemoryRequirements, memory_range: Range<u64>, } pub struct ImageView { handle: vk::ImageView, } impl Image { #[inline] pub fn handle(&self) -> vk::Image { self.handle } #[inline] pub fn memory_requirements(&self) -> vk::MemoryRequirements { self.requirements } #[inline] pub unsafe fn set_memory_range(&mut self, range: Range<u64>) { self.memory_range = range; } pub fn new( device: &Device, extent: (u32, u32), format: vk::Format, usage: vk::ImageUsageFlags, ) -> Result<Self, VkError> { let handle; let requirements; unsafe { let info = vk::ImageCreateInfo::builder() .image_type(vk::ImageType::TYPE_2D) .usage(usage) .extent( vk::Extent3D::builder() .width(extent.0) .height(extent.1) .depth(1) .build(), ) .format(format) .initial_layout(vk::ImageLayout::UNDEFINED) .samples(vk::SampleCountFlags::TYPE_1) .mip_levels(1) .array_layers(1) .tiling(vk::ImageTiling::OPTIMAL) .sharing_mode(vk::SharingMode::EXCLUSIVE); handle = map_vk_error!(device.create_image(&info, None))?; requirements = device.get_image_memory_requirements(handle); } Ok(Self { handle, format, requirements, memory_range: 0..0, }) } pub unsafe fn destroy(&mut self, device: &Device) { device.destroy_image(self.handle, None); } } impl ImageView { #[inline] pub fn handle(&self) -> vk::ImageView { self.handle } pub unsafe fn new(device: &Device, image: &Image) -> Result<Self, VkError> { let components = vk::ComponentMapping::builder() .r(vk::ComponentSwizzle::IDENTITY) .g(vk::ComponentSwizzle::IDENTITY) .b(vk::ComponentSwizzle::IDENTITY) .a(vk::ComponentSwizzle::IDENTITY) .build(); let range = vk::ImageSubresourceRange::builder() .aspect_mask(vk::ImageAspectFlags::COLOR) .base_array_layer(0) .layer_count(1) .base_mip_level(0) .level_count(1) .build(); let info = vk::ImageViewCreateInfo::builder() .image(image.handle) .format(image.format) .view_type(vk::ImageViewType::TYPE_2D) .components(components) .subresource_range(range); let handle = map_vk_error!(device.create_image_view(&info, None))?; Ok(Self { handle }) } pub unsafe fn destroy(&mut self, device: &Device) { device.destroy_image_view(self.handle, None); } }
#[doc = "Reader of register DDRCTRL_DFIUPD2"] pub type R = crate::R<u32, super::DDRCTRL_DFIUPD2>; #[doc = "Writer for register DDRCTRL_DFIUPD2"] pub type W = crate::W<u32, super::DDRCTRL_DFIUPD2>; #[doc = "Register DDRCTRL_DFIUPD2 `reset()`'s with value 0x8000_0000"] impl crate::ResetValue for super::DDRCTRL_DFIUPD2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x8000_0000 } } #[doc = "Reader of field `DFI_PHYUPD_EN`"] pub type DFI_PHYUPD_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DFI_PHYUPD_EN`"] pub struct DFI_PHYUPD_EN_W<'a> { w: &'a mut W, } impl<'a> DFI_PHYUPD_EN_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 31 - DFI_PHYUPD_EN"] #[inline(always)] pub fn dfi_phyupd_en(&self) -> DFI_PHYUPD_EN_R { DFI_PHYUPD_EN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 31 - DFI_PHYUPD_EN"] #[inline(always)] pub fn dfi_phyupd_en(&mut self) -> DFI_PHYUPD_EN_W { DFI_PHYUPD_EN_W { w: self } } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistrationDefinitionProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<Plan>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationDefinitionProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, pub authorizations: Vec<Authorization>, #[serde(rename = "eligibleAuthorizations", default, skip_serializing_if = "Vec::is_empty")] pub eligible_authorizations: Vec<EligibleAuthorization>, #[serde(rename = "registrationDefinitionName", default, skip_serializing_if = "Option::is_none")] pub registration_definition_name: Option<String>, #[serde(rename = "managedByTenantId")] pub managed_by_tenant_id: String, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<registration_definition_properties::ProvisioningState>, #[serde(rename = "manageeTenantId", default, skip_serializing_if = "Option::is_none")] pub managee_tenant_id: Option<String>, #[serde(rename = "manageeTenantName", default, skip_serializing_if = "Option::is_none")] pub managee_tenant_name: Option<String>, #[serde(rename = "managedByTenantName", default, skip_serializing_if = "Option::is_none")] pub managed_by_tenant_name: Option<String>, } pub mod registration_definition_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { NotSpecified, Accepted, Running, Ready, Creating, Created, Deleting, Deleted, Canceled, Failed, Succeeded, Updating, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationDefinitionList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RegistrationDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationAssignment { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistrationAssignmentProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationAssignmentProperties { #[serde(rename = "registrationDefinitionId")] pub registration_definition_id: String, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<registration_assignment_properties::ProvisioningState>, #[serde(rename = "registrationDefinition", default, skip_serializing_if = "Option::is_none")] pub registration_definition: Option<registration_assignment_properties::RegistrationDefinition>, } pub mod registration_assignment_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { NotSpecified, Accepted, Running, Ready, Creating, Created, Deleting, Deleted, Canceled, Failed, Succeeded, Updating, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<registration_definition::Properties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<Plan>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } pub mod registration_definition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub authorizations: Vec<Authorization>, #[serde(rename = "eligibleAuthorizations", default, skip_serializing_if = "Vec::is_empty")] pub eligible_authorizations: Vec<EligibleAuthorization>, #[serde(rename = "registrationDefinitionName", default, skip_serializing_if = "Option::is_none")] pub registration_definition_name: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "manageeTenantId", default, skip_serializing_if = "Option::is_none")] pub managee_tenant_id: Option<String>, #[serde(rename = "manageeTenantName", default, skip_serializing_if = "Option::is_none")] pub managee_tenant_name: Option<String>, #[serde(rename = "managedByTenantId", default, skip_serializing_if = "Option::is_none")] pub managed_by_tenant_id: Option<String>, #[serde(rename = "managedByTenantName", default, skip_serializing_if = "Option::is_none")] pub managed_by_tenant_name: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { NotSpecified, Accepted, Running, Ready, Creating, Created, Deleting, Deleted, Canceled, Failed, Succeeded, Updating, } } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistrationAssignmentList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RegistrationAssignment>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MarketplaceRegistrationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MarketplaceRegistrationDefinitionProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<Plan>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MarketplaceRegistrationDefinitionProperties { #[serde(rename = "managedByTenantId")] pub managed_by_tenant_id: String, pub authorizations: Vec<Authorization>, #[serde(rename = "eligibleAuthorizations", default, skip_serializing_if = "Vec::is_empty")] pub eligible_authorizations: Vec<EligibleAuthorization>, #[serde(rename = "offerDisplayName", default, skip_serializing_if = "Option::is_none")] pub offer_display_name: Option<String>, #[serde(rename = "publisherDisplayName", default, skip_serializing_if = "Option::is_none")] pub publisher_display_name: Option<String>, #[serde(rename = "planDisplayName", default, skip_serializing_if = "Option::is_none")] pub plan_display_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MarketplaceRegistrationDefinitionList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<MarketplaceRegistrationDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Plan { pub name: String, pub publisher: String, pub product: String, pub version: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Authorization { #[serde(rename = "principalId")] pub principal_id: String, #[serde(rename = "principalIdDisplayName", default, skip_serializing_if = "Option::is_none")] pub principal_id_display_name: Option<String>, #[serde(rename = "roleDefinitionId")] pub role_definition_id: String, #[serde(rename = "delegatedRoleDefinitionIds", default, skip_serializing_if = "Vec::is_empty")] pub delegated_role_definition_ids: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EligibleAuthorization { #[serde(rename = "principalId")] pub principal_id: String, #[serde(rename = "principalIdDisplayName", default, skip_serializing_if = "Option::is_none")] pub principal_id_display_name: Option<String>, #[serde(rename = "roleDefinitionId")] pub role_definition_id: String, #[serde(rename = "justInTimeAccessPolicy", default, skip_serializing_if = "Option::is_none")] pub just_in_time_access_policy: Option<JustInTimeAccessPolicy>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EligibleApprover { #[serde(rename = "principalId")] pub principal_id: String, #[serde(rename = "principalIdDisplayName", default, skip_serializing_if = "Option::is_none")] pub principal_id_display_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct JustInTimeAccessPolicy { #[serde(rename = "multiFactorAuthProvider")] pub multi_factor_auth_provider: just_in_time_access_policy::MultiFactorAuthProvider, #[serde(rename = "maximumActivationDuration", default, skip_serializing_if = "Option::is_none")] pub maximum_activation_duration: Option<String>, #[serde(rename = "managedByTenantApprovers", default, skip_serializing_if = "Vec::is_empty")] pub managed_by_tenant_approvers: Vec<EligibleApprover>, } pub mod just_in_time_access_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum MultiFactorAuthProvider { Azure, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDefinition { pub code: String, pub message: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ErrorDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorDefinition>, }
use std::rc::Rc; use super::scope::{Scope, ScopeId}; use std::fmt::Display; use super::types::{Type, TypeKind}; use crate::syntax::{ ast::{Item, Ptr, Ident, AstNode}, token::{Position} }; #[derive(Debug, Clone, PartialEq)] pub enum ItemState { Resolved, Active, Unresolved, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct ItemId(usize); impl ItemId { pub fn next() -> Self { use std::sync::atomic::{AtomicUsize, Ordering}; static TOKEN: AtomicUsize = AtomicUsize::new(0); Self(TOKEN.fetch_add(1, Ordering::SeqCst)) } } impl Display for ItemId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Item({})", self.0)?; Ok(()) } } #[derive(Debug, Clone)] pub struct ItemInfo { // id: ItemId, // the item this info is for item: Ptr<Item>, // the ident of this item. name: Ident, // the type of this entity resovled_type: Type, // the scope of this entity scope: Option<ScopeId>, // the current state of the item. state: ItemState, } impl ItemInfo { pub fn unresolved(name: Ident, item: Ptr<Item>, scope: Option<ScopeId>) -> Self { Self { id: ItemId::next(), item, name, resovled_type: Type::new(TypeKind::Unknown), scope, state: ItemState::Unresolved, } } pub fn resolved(name: Ident, item: Ptr<Item>, resovled_type: Type, scope: Option<ScopeId>) -> Self { Self { id: ItemId::next(), item, name, resovled_type, scope, state: ItemState::Resolved, } } pub fn resolve(self, ty: Type) -> Self { if self.state == ItemState::Resolved { self } else { Self { state: ItemState::Resolved, resovled_type: ty, ..self } } } pub fn with_item(self, item: Ptr<Item>) -> Self { Self { item, ..self } } pub fn pos(&self) -> &Position { self.item.pos() } pub fn id(&self) -> ItemId { self.id } pub fn name(&self) -> &str { self.name.value() } pub fn item(&self) -> &Item { self.item.as_ref() } pub fn item_type(&self) -> &Type { &self.resovled_type } pub fn is_variable(&self) -> bool { self.item.is_variable() } pub fn is_struct(&self) -> bool { self.item.is_struct() } pub fn is_primative(&self) -> bool { self.item.is_primative() } pub fn is_function(&self) -> bool { self.item.is_function() } pub fn is_type(&self) -> bool { self.is_struct() || self.is_primative() // || self.is_trait() || self.is_variant() } }
use hydroflow::util::cli::{ConnectedDemux, ConnectedDirect, ConnectedSink, ConnectedSource}; use hydroflow::util::{deserialize_from_bytes, serialize_to_bytes}; use hydroflow_datalog::datalog; #[hydroflow::main] async fn main() { let mut ports = hydroflow::util::cli::init().await; let vote_to_participant_source = ports .port("vote_to_participant") .connect::<ConnectedDirect>() .await .into_source(); let vote_from_participant_port = ports .port("vote_from_participant") .connect::<ConnectedDemux<ConnectedDirect>>() .await; let peers = vote_from_participant_port.keys.clone(); let vote_from_participant_sink = vote_from_participant_port.into_sink(); let instruct_to_participant_source = ports .port("instruct_to_participant") .connect::<ConnectedDirect>() .await .into_source(); let ack_from_participant_sink = ports .port("ack_from_participant") .connect::<ConnectedDemux<ConnectedDirect>>() .await .into_sink(); let my_id: Vec<u32> = serde_json::from_str(&std::env::args().nth(1).unwrap()).unwrap(); println!("my_id: {:?}", my_id); println!("coordinator: {:?}", peers); let mut df = datalog!( r#" .input myID `source_iter(my_id.clone()) -> persist() -> map(|p| (p,))` .input coordinator `source_iter(peers.clone()) -> persist() -> map(|p| (p,))` .input verdict `source_iter([(true,),]) -> persist()` // .output voteOut `for_each(|(i,myID):(u32,u32,)| println!("participant {:?}: message {:?}", myID, i))` .async voteToParticipant `null::<(u32,String,)>()` `source_stream(vote_to_participant_source) -> map(|x| deserialize_from_bytes::<(u32,String,)>(x.unwrap()).unwrap())` .async voteFromParticipant `map(|(node_id, v)| (node_id, serialize_to_bytes(v))) -> dest_sink(vote_from_participant_sink)` `null::<(u32,String,)>()` .async instructToParticipant `null::<(u32,String,bool,)>()` `source_stream(instruct_to_participant_source) -> map(|x| deserialize_from_bytes::<(u32,String,bool,)>(x.unwrap()).unwrap())` .async ackFromParticipant `map(|(node_id, v)| (node_id, serialize_to_bytes(v))) -> dest_sink(ack_from_participant_sink)` `null::<(u32,String,u32,)>()` # .output verdictRequest # .output log # verdictRequest(i, msg) :- voteToParticipant(i, msg) voteFromParticipant@addr(i, msg, res, l_from) :~ voteToParticipant(i, msg), coordinator(addr), myID(l_from), verdict(res) ackFromParticipant@addr(i, msg, l_from) :~ instructToParticipant(i, msg, b), coordinator(addr), myID(l_from) // voteOut(i, l) :- voteToParticipant(i, msg), myID(l) # log(i, msg, type) :- instructToParticipant(i, msg, type) # the log channel will sort everything out "# ); df.run_async().await; }
pub fn crc_clp2(mut x: i32) -> i32 { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } #[cfg_attr(not(target_arch = "x86_64"),test_case)] #[cfg_attr(not(target_arch = "riscv64"),test)] fn test_crc_clp2() { assert_eq!(crc_clp2(0), 0); } pub fn crc_reverse(mut x: i32) -> i32 { x = ((x & 0x55555555) << 1) | ((x >> 1) & 0x55555555); x = ((x & 0x33333333) << 2) | ((x >> 2) & 0x33333333); x = ((x & 0x0F0F0F0F) << 4) | ((x >> 4) & 0x0F0F0F0F); x = (x << 24) | ((x & 0xFF00) << 8) | ((x >> 8) & 0xFF00) | (x >> 24); return x; } #[allow(overflowing_literals)] pub fn crc32a(message: &[char]) -> i32 { let mut i = 0; let mut crc = 0xFFFFFFFF; while message[i] != '\x00' { let mut byte = message[i]; // Get next byte. byte = crc_reverse((byte as u8) as i32) as u8 as char; // 32-bit reversal. for j in 0..7 { // Do eight times. if (crc ^ (byte as i32)) < 0 { crc = (crc << 1) ^ 0x04C11DB7; } else { crc = crc << 1; } byte = ((byte as u8) << 1) as char; // Ready next msg bit. } i = i + 1; } return crc_reverse(!crc); } /* This is the basic CRC-32 calculation with some optimization but no table lookup. The the byte reversal is avoided by shifting the crc reg right instead of left and by using a reversed 32-bit word to represent the polynomial. When compiled to Cyclops with GCC, this function executes in 8 + 72n instructions, where n is the number of bytes in the input message. It should be doable in 4 + 61n instructions. If the inner loop is strung out (approx. 5*8 = 40 instructions), it would take about 6 + 46n instructions. */ #[allow(overflowing_literals)] pub fn crc32b(message: &[char]) -> i32 { let mut i = 0; let mut crc = 0xFFFFFFFF; while message[i] != '\x00' { let mut byte = message[i]; // Get next byte. crc = crc ^ (byte as u8 as i32); for _ in 7..0 { // Do eight times. let mask = -(crc & 1); crc = (crc >> 1) ^ (0xEDB88320 & mask); } i = i + 1; } !crc } /* This is derived from crc32b but does table lookup. First the table itself is calculated, if it has not yet been set up. Not counting the table setup (which would probably be a separate function), when compiled to Cyclops with GCC, this function executes in 7 + 13n instructions, where n is the number of bytes in the input message. It should be doable in 4 + 9n instructions. In any , two of the 13 or 9 instrucions are load byte. => This is Figure 14-7 in the text. */ #[allow(overflowing_literals)] pub fn crc32c(message: &[char]) -> i32 { let mut table: [char; 256] = ['\x00'; 256]; if table[1] == '\x00' { for byte in 0..255 { let mut crc = byte; for _ in 7..0 { // Do eight times. let mask = -(crc as i32 & 1); crc = (crc >> 1) ^ (0xEDB88320 & mask); } table[byte as usize] = crc as u8 as char; } } /* Through with table setup, now calculate the CRC. */ let mut crc = 0xFFFFFFFF; for byte in message { crc = (crc >> 8) ^ table[((crc ^ *byte as i64) & 0xFF) as usize] as i64; } !crc as i32 } /* This is crc32b modified to load the message a fullword at a time. It assumes the message is word aligned and consists of an integral number of words before the 0-byte that marks the end of the message. This works only on a little-endian machine. Not counting the table setup (which would probably be a separate function), this function should be doable in 3 + 22w instructions, where w is the number of fullwords in the input message. This is equivalent to 3 + 5.5n instructions, where n is the number of bytes. 1.25 of those 5.5 instructions are loads. This is Exercise 1 in the text. C.f. Christopher Dannemiller, who got it from Linux Source base, */ #[allow(overflowing_literals)] pub fn crc32cx(message: &mut [char]) -> i32 { let mut table: [char; 256] = ['\x00'; 256]; /* Set up the table, if necessary. */ if table[1] == '\x00' { for byte in 0..255 { let mut crc = byte; for _ in 7..0 { // Do eight times. let mask = -(crc as i32 & 1); crc = (crc >> 1) ^ (0xEDB88320 & mask); } table[byte as usize] = crc as u8 as char; } } /* Through with table setup, now calculate the CRC. */ let mut crc = 0xFFFFFFFF; for word in message.into_iter().step_by(4) { crc = crc ^ *word as i64; crc = (crc >> 8) ^ table[(crc & 0xFF) as usize] as i64; crc = (crc >> 8) ^ table[(crc & 0xFF) as usize] as i64; crc = (crc >> 8) ^ table[(crc & 0xFF) as usize] as i64; crc = (crc >> 8) ^ table[(crc & 0xFF) as usize] as i64; } !crc as i32 } /* This is like crc32c (does table lookup) but it processes two bytes at a time, except for a possible odd byte at the beginning or end of the message. The table size is 65536 words. Not counting the table setup (which would probably be a separate function), when compiled to Cyclops with GCC, this function executes in 14 + 14n instructions, where n is the number of halfwords in the input message. This assumes there are no odd bytes at either end. Note: When accessing the table for a single byte b, the entry to use is b << 8. I.e., if the byte is the letter 'a', the entry to use is that with index 0x6100, not 0x0061. */ #[allow(overflowing_literals)] pub fn crc32d(message: &[char]) -> i32 { let mut table: [char; 65534] = ['\x00'; 65534]; if table[1] == '\x00' { // If table has not yet // been set up: for half in 0..65534 { let mut crc = half; for j in 15..0 { // Do 15 times. let mut mask = -(crc as i32 & 1); crc = (crc >> 1) ^ (0xEDB88320 & mask); } table[half as usize] = crc as u8 as char; } } let mut crc = 0xFFFFFFFF; // First, if message is aligned on an odd address, // take care of the first byte. let mut i = (message[0] as u8 & 1) as i32; // Start of halfwords. if i != 0 { // If i == 1: let byte = message[0]; if byte == '\x00' { return 0; } // If null message. crc = (crc >> 8) ^ table[((byte as i64 ^ 0xFF) << 8) as usize] as i64; } // Next process the message two bytes at a time as long // as both bytes are nonzero. let mut half = 0; while true { half = message[i as usize] as i32; if half <= 0xFF || (half & 0xFF) == 0 { break; } crc = (crc >> 16) ^ (table[((crc ^ half as i64) & 0xFFFF) as usize]) as i64; i = i + 2; } // Lastly, process the odd byte at the end, if any. // "half" is of the form 00xx, xx00, or 0000. if half & 0xFF != 0 { crc = (crc >> 8) ^ table[(((crc ^ half as i64) & 0xFF) << 8) as usize] as i64; } !crc as i32 } /* This is sort of like the table lookup version (crc32c), but using a 16-way switch statement instead. When compiled to Cyclops with GCC, this function executes in 6 + 38n instructions, where n is the number of bytes in the input message. The 38 instructions per byte include 3 loads and 5 branches (not good). It is actually 6 branches if you count the unnecessary one that GCC generates because it isn't smart enough to know that the switch argument cannot exceed 15. */ pub fn crc32e(message: &[char]) -> i32 { let g0 = 0xEDB88320; let g1 = g0 >> 1; let g2 = g0 >> 2; let g3 = g0 >> 3; let mut crc = 0xFFFFFFFF; let mut c = 0; for byte in message { // Get next byte. crc = crc ^ *byte as i64; for j in 0..1 { // Do two times. match crc & 0xF { 0 => c = 0, 1 => c = g3, 2 => c = g2, 3 => c = g2 ^ g3, 4 => c = g1, 5 => c = g1 ^ g3, 6 => c = g1 ^ g2, 7 => c = g1 ^ g2 ^ g3, 8 => c = g0, 9 => c = g0 ^ g3, 10 => c = g0 ^ g2, 11 => c = g0 ^ g2 ^ g3, 12 => c = g0 ^ g1, 13 => c = g0 ^ g1 ^ g3, 14 => c = g0 ^ g1 ^ g2, 15 => c = g0 ^ g1 ^ g2 ^ g3, _ => {} } crc = (crc >> 4) ^ c; } } !crc as i32 } /* This is sort of like the table lookup version (crc32c), but using a 256-way switch statement instead. The expressions for g1, g2, ..., g7 are determined by examining what the CRC-32 algorithm does to a byte of value 1, 2, 4, 8, 16, 32, 64, and 128, respectively. g6 and g7 are complicated because the rightmost 1-bit in g0 enters the picture. We rely on the compiler to evaluate, at compile time, all the expressions involving the g's. They are the table values used in function crc32c above (i.e., g7 = table[1], g6 = table[2], g5 = table[4], etc.). This idea of using a switch statement is a dumb idea if a compiler is used, because the compiler (GCC anyway) implements the switch statement with a 256-word label table. Thus the program still has the load from a table, and it is larger than crc32c by the three words of instructions used at each statement (two instructions to load the constant, plus a branch). Howe=>er, since each statement has the same amount o, code (three w, the label table cou=>d be avoided if the program wer, coded in assembly language. But it would still have poor performance. At any rate, when compiled to Cyclops with GCC, this function executes 6 + 19n instructions, where n is the number of bytes in the input message. The 19 includes 2 loads and 3 branches (per byte), not counting the one GCC generates to check that the switch argument doesn't exceed 255 (it can't exceed 255). */ pub fn crc32f(message: &[char]) -> i32 { let g0 = 0xEDB88320; let g1 = g0 >> 1; let g2 = g0 >> 2; let g3 = g0 >> 3; let g4 = g0 >> 4; let g5 = g0 >> 5; let g6 = (g0 >> 6) ^ g0; let g7 = ((g0 >> 6) ^ g0) >> 1; let mut i = 0; let mut c = 0; let mut crc = 0xFFFFFFFF; for byte in message { // Get next byte. crc = crc ^ *byte as i64; match crc & 0xFF { 0 => c = 0, 1 => c = g7, 2 => c = g6, 3 => c = g6 ^ g7, 4 => c = g5, 5 => c = g5 ^ g7, 6 => c = g5 ^ g6, 7 => c = g5 ^ g6 ^ g7, 8 => c = g4, 9 => c = g4 ^ g7, 10 => c = g4 ^ g6, 11 => c = g4 ^ g6 ^ g7, 12 => c = g4 ^ g5, 13 => c = g4 ^ g5 ^ g7, 14 => c = g4 ^ g5 ^ g6, 15 => c = g4 ^ g5 ^ g6 ^ g7, 16 => c = g3, 17 => c = g3 ^ g7, 18 => c = g3 ^ g6, 19 => c = g3 ^ g6 ^ g7, 20 => c = g3 ^ g5, 21 => c = g3 ^ g5 ^ g7, 22 => c = g3 ^ g5 ^ g6, 23 => c = g3 ^ g5 ^ g6 ^ g7, 24 => c = g3 ^ g4, 25 => c = g3 ^ g4 ^ g7, 26 => c = g3 ^ g4 ^ g6, 27 => c = g3 ^ g4 ^ g6 ^ g7, 28 => c = g3 ^ g4 ^ g5, 29 => c = g3 ^ g4 ^ g5 ^ g7, 30 => c = g3 ^ g4 ^ g5 ^ g6, 31 => c = g3 ^ g4 ^ g5 ^ g6 ^ g7, 32 => c = g2, 33 => c = g2 ^ g7, 34 => c = g2 ^ g6, 35 => c = g2 ^ g6 ^ g7, 36 => c = g2 ^ g5, 37 => c = g2 ^ g5 ^ g7, 38 => c = g2 ^ g5 ^ g6, 39 => c = g2 ^ g5 ^ g6 ^ g7, 40 => c = g2 ^ g4, 41 => c = g2 ^ g4 ^ g7, 42 => c = g2 ^ g4 ^ g6, 43 => c = g2 ^ g4 ^ g6 ^ g7, 44 => c = g2 ^ g4 ^ g5, 45 => c = g2 ^ g4 ^ g5 ^ g7, 46 => c = g2 ^ g4 ^ g5 ^ g6, 47 => c = g2 ^ g4 ^ g5 ^ g6 ^ g7, 48 => c = g2 ^ g3, 49 => c = g2 ^ g3 ^ g7, 50 => c = g2 ^ g3 ^ g6, 51 => c = g2 ^ g3 ^ g6 ^ g7, 52 => c = g2 ^ g3 ^ g5, 53 => c = g2 ^ g3 ^ g5 ^ g7, 54 => c = g2 ^ g3 ^ g5 ^ g6, 55 => c = g2 ^ g3 ^ g5 ^ g6 ^ g7, 56 => c = g2 ^ g3 ^ g4, 57 => c = g2 ^ g3 ^ g4 ^ g7, 58 => c = g2 ^ g3 ^ g4 ^ g6, 59 => c = g2 ^ g3 ^ g4 ^ g6 ^ g7, 60 => c = g2 ^ g3 ^ g4 ^ g5, 61 => c = g2 ^ g3 ^ g4 ^ g5 ^ g7, 62 => c = g2 ^ g3 ^ g4 ^ g5 ^ g6, 63 => c = g2 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, 64 => c = g1, 65 => c = g1 ^ g7, 66 => c = g1 ^ g6, 67 => c = g1 ^ g6 ^ g7, 68 => c = g1 ^ g5, 69 => c = g1 ^ g5 ^ g7, 70 => c = g1 ^ g5 ^ g6, 71 => c = g1 ^ g5 ^ g6 ^ g7, 72 => c = g1 ^ g4, 73 => c = g1 ^ g4 ^ g7, 74 => c = g1 ^ g4 ^ g6, 75 => c = g1 ^ g4 ^ g6 ^ g7, 76 => c = g1 ^ g4 ^ g5, 77 => c = g1 ^ g4 ^ g5 ^ g7, 78 => c = g1 ^ g4 ^ g5 ^ g6, 79 => c = g1 ^ g4 ^ g5 ^ g6 ^ g7, 80 => c = g1 ^ g3, 81 => c = g1 ^ g3 ^ g7, 82 => c = g1 ^ g3 ^ g6, 83 => c = g1 ^ g3 ^ g6 ^ g7, 84 => c = g1 ^ g3 ^ g5, 85 => c = g1 ^ g3 ^ g5 ^ g7, 86 => c = g1 ^ g3 ^ g5 ^ g6, 87 => c = g1 ^ g3 ^ g5 ^ g6 ^ g7, 88 => c = g1 ^ g3 ^ g4, 89 => c = g1 ^ g3 ^ g4 ^ g7, 90 => c = g1 ^ g3 ^ g4 ^ g6, 91 => c = g1 ^ g3 ^ g4 ^ g6 ^ g7, 92 => c = g1 ^ g3 ^ g4 ^ g5, 93 => c = g1 ^ g3 ^ g4 ^ g5 ^ g7, 94 => c = g1 ^ g3 ^ g4 ^ g5 ^ g6, 95 => c = g1 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, 96 => c = g1 ^ g2, 97 => c = g1 ^ g2 ^ g7, 98 => c = g1 ^ g2 ^ g6, 99 => c = g1 ^ g2 ^ g6 ^ g7, 100 => c = g1 ^ g2 ^ g5, 101 => c = g1 ^ g2 ^ g5 ^ g7, 102 => c = g1 ^ g2 ^ g5 ^ g6, 103 => c = g1 ^ g2 ^ g5 ^ g6 ^ g7, 104 => c = g1 ^ g2 ^ g4, 105 => c = g1 ^ g2 ^ g4 ^ g7, 106 => c = g1 ^ g2 ^ g4 ^ g6, 107 => c = g1 ^ g2 ^ g4 ^ g6 ^ g7, 108 => c = g1 ^ g2 ^ g4 ^ g5, 109 => c = g1 ^ g2 ^ g4 ^ g5 ^ g7, 110 => c = g1 ^ g2 ^ g4 ^ g5 ^ g6, 111 => c = g1 ^ g2 ^ g4 ^ g5 ^ g6 ^ g7, 112 => c = g1 ^ g2 ^ g3, 113 => c = g1 ^ g2 ^ g3 ^ g7, 114 => c = g1 ^ g2 ^ g3 ^ g6, 115 => c = g1 ^ g2 ^ g3 ^ g6 ^ g7, 116 => c = g1 ^ g2 ^ g3 ^ g5, 117 => c = g1 ^ g2 ^ g3 ^ g5 ^ g7, 118 => c = g1 ^ g2 ^ g3 ^ g5 ^ g6, 119 => c = g1 ^ g2 ^ g3 ^ g5 ^ g6 ^ g7, 120 => c = g1 ^ g2 ^ g3 ^ g4, 121 => c = g1 ^ g2 ^ g3 ^ g4 ^ g7, 122 => c = g1 ^ g2 ^ g3 ^ g4 ^ g6, 123 => c = g1 ^ g2 ^ g3 ^ g4 ^ g6 ^ g7, 124 => c = g1 ^ g2 ^ g3 ^ g4 ^ g5, 125 => c = g1 ^ g2 ^ g3 ^ g4 ^ g5 ^ g7, 126 => c = g1 ^ g2 ^ g3 ^ g4 ^ g5 ^ g6, 127 => c = g1 ^ g2 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, 128 => c = g0, 129 => c = g0 ^ g7, 130 => c = g0 ^ g6, 131 => c = g0 ^ g6 ^ g7, 132 => c = g0 ^ g5, 133 => c = g0 ^ g5 ^ g7, 134 => c = g0 ^ g5 ^ g6, 135 => c = g0 ^ g5 ^ g6 ^ g7, 136 => c = g0 ^ g4, 137 => c = g0 ^ g4 ^ g7, 138 => c = g0 ^ g4 ^ g6, 139 => c = g0 ^ g4 ^ g6 ^ g7, 140 => c = g0 ^ g4 ^ g5, 141 => c = g0 ^ g4 ^ g5 ^ g7, 142 => c = g0 ^ g4 ^ g5 ^ g6, 143 => c = g0 ^ g4 ^ g5 ^ g6 ^ g7, 144 => c = g0 ^ g3, 145 => c = g0 ^ g3 ^ g7, 146 => c = g0 ^ g3 ^ g6, 147 => c = g0 ^ g3 ^ g6 ^ g7, 148 => c = g0 ^ g3 ^ g5, 149 => c = g0 ^ g3 ^ g5 ^ g7, 150 => c = g0 ^ g3 ^ g5 ^ g6, 151 => c = g0 ^ g3 ^ g5 ^ g6 ^ g7, 152 => c = g0 ^ g3 ^ g4, 153 => c = g0 ^ g3 ^ g4 ^ g7, 154 => c = g0 ^ g3 ^ g4 ^ g6, 155 => c = g0 ^ g3 ^ g4 ^ g6 ^ g7, 156 => c = g0 ^ g3 ^ g4 ^ g5, 157 => c = g0 ^ g3 ^ g4 ^ g5 ^ g7, 158 => c = g0 ^ g3 ^ g4 ^ g5 ^ g6, 159 => c = g0 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, 160 => c = g0 ^ g2, 161 => c = g0 ^ g2 ^ g7, 162 => c = g0 ^ g2 ^ g6, 163 => c = g0 ^ g2 ^ g6 ^ g7, 164 => c = g0 ^ g2 ^ g5, 165 => c = g0 ^ g2 ^ g5 ^ g7, 166 => c = g0 ^ g2 ^ g5 ^ g6, 167 => c = g0 ^ g2 ^ g5 ^ g6 ^ g7, 168 => c = g0 ^ g2 ^ g4, 169 => c = g0 ^ g2 ^ g4 ^ g7, 170 => c = g0 ^ g2 ^ g4 ^ g6, 171 => c = g0 ^ g2 ^ g4 ^ g6 ^ g7, 172 => c = g0 ^ g2 ^ g4 ^ g5, 173 => c = g0 ^ g2 ^ g4 ^ g5 ^ g7, 174 => c = g0 ^ g2 ^ g4 ^ g5 ^ g6, 175 => c = g0 ^ g2 ^ g4 ^ g5 ^ g6 ^ g7, 176 => c = g0 ^ g2 ^ g3, 177 => c = g0 ^ g2 ^ g3 ^ g7, 178 => c = g0 ^ g2 ^ g3 ^ g6, 179 => c = g0 ^ g2 ^ g3 ^ g6 ^ g7, 180 => c = g0 ^ g2 ^ g3 ^ g5, 181 => c = g0 ^ g2 ^ g3 ^ g5 ^ g7, 182 => c = g0 ^ g2 ^ g3 ^ g5 ^ g6, 183 => c = g0 ^ g2 ^ g3 ^ g5 ^ g6 ^ g7, 184 => c = g0 ^ g2 ^ g3 ^ g4, 185 => c = g0 ^ g2 ^ g3 ^ g4 ^ g7, 186 => c = g0 ^ g2 ^ g3 ^ g4 ^ g6, 187 => c = g0 ^ g2 ^ g3 ^ g4 ^ g6 ^ g7, 188 => c = g0 ^ g2 ^ g3 ^ g4 ^ g5, 189 => c = g0 ^ g2 ^ g3 ^ g4 ^ g5 ^ g7, 190 => c = g0 ^ g2 ^ g3 ^ g4 ^ g5 ^ g6, 191 => c = g0 ^ g2 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, 192 => c = g0 ^ g1, 193 => c = g0 ^ g1 ^ g7, 194 => c = g0 ^ g1 ^ g6, 195 => c = g0 ^ g1 ^ g6 ^ g7, 196 => c = g0 ^ g1 ^ g5, 197 => c = g0 ^ g1 ^ g5 ^ g7, 198 => c = g0 ^ g1 ^ g5 ^ g6, 199 => c = g0 ^ g1 ^ g5 ^ g6 ^ g7, 200 => c = g0 ^ g1 ^ g4, 201 => c = g0 ^ g1 ^ g4 ^ g7, 202 => c = g0 ^ g1 ^ g4 ^ g6, 203 => c = g0 ^ g1 ^ g4 ^ g6 ^ g7, 204 => c = g0 ^ g1 ^ g4 ^ g5, 205 => c = g0 ^ g1 ^ g4 ^ g5 ^ g7, 206 => c = g0 ^ g1 ^ g4 ^ g5 ^ g6, 207 => c = g0 ^ g1 ^ g4 ^ g5 ^ g6 ^ g7, 208 => c = g0 ^ g1 ^ g3, 209 => c = g0 ^ g1 ^ g3 ^ g7, 210 => c = g0 ^ g1 ^ g3 ^ g6, 211 => c = g0 ^ g1 ^ g3 ^ g6 ^ g7, 212 => c = g0 ^ g1 ^ g3 ^ g5, 213 => c = g0 ^ g1 ^ g3 ^ g5 ^ g7, 214 => c = g0 ^ g1 ^ g3 ^ g5 ^ g6, 215 => c = g0 ^ g1 ^ g3 ^ g5 ^ g6 ^ g7, 216 => c = g0 ^ g1 ^ g3 ^ g4, 217 => c = g0 ^ g1 ^ g3 ^ g4 ^ g7, 218 => c = g0 ^ g1 ^ g3 ^ g4 ^ g6, 219 => c = g0 ^ g1 ^ g3 ^ g4 ^ g6 ^ g7, 220 => c = g0 ^ g1 ^ g3 ^ g4 ^ g5, 221 => c = g0 ^ g1 ^ g3 ^ g4 ^ g5 ^ g7, 222 => c = g0 ^ g1 ^ g3 ^ g4 ^ g5 ^ g6, 223 => c = g0 ^ g1 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, 224 => c = g0 ^ g1 ^ g2, 225 => c = g0 ^ g1 ^ g2 ^ g7, 226 => c = g0 ^ g1 ^ g2 ^ g6, 227 => c = g0 ^ g1 ^ g2 ^ g6 ^ g7, 228 => c = g0 ^ g1 ^ g2 ^ g5, 229 => c = g0 ^ g1 ^ g2 ^ g5 ^ g7, 230 => c = g0 ^ g1 ^ g2 ^ g5 ^ g6, 231 => c = g0 ^ g1 ^ g2 ^ g5 ^ g6 ^ g7, 232 => c = g0 ^ g1 ^ g2 ^ g4, 233 => c = g0 ^ g1 ^ g2 ^ g4 ^ g7, 234 => c = g0 ^ g1 ^ g2 ^ g4 ^ g6, 235 => c = g0 ^ g1 ^ g2 ^ g4 ^ g6 ^ g7, 236 => c = g0 ^ g1 ^ g2 ^ g4 ^ g5, 237 => c = g0 ^ g1 ^ g2 ^ g4 ^ g5 ^ g7, 238 => c = g0 ^ g1 ^ g2 ^ g4 ^ g5 ^ g6, 239 => c = g0 ^ g1 ^ g2 ^ g4 ^ g5 ^ g6 ^ g7, 240 => c = g0 ^ g1 ^ g2 ^ g3, 241 => c = g0 ^ g1 ^ g2 ^ g3 ^ g7, 242 => c = g0 ^ g1 ^ g2 ^ g3 ^ g6, 243 => c = g0 ^ g1 ^ g2 ^ g3 ^ g6 ^ g7, 244 => c = g0 ^ g1 ^ g2 ^ g3 ^ g5, 245 => c = g0 ^ g1 ^ g2 ^ g3 ^ g5 ^ g7, 246 => c = g0 ^ g1 ^ g2 ^ g3 ^ g5 ^ g6, 247 => c = g0 ^ g1 ^ g2 ^ g3 ^ g5 ^ g6 ^ g7, 248 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4, 249 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g7, 250 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g6, 251 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g6 ^ g7, 252 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g5, 253 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g5 ^ g7, 254 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g5 ^ g6, 255 => c = g0 ^ g1 ^ g2 ^ g3 ^ g4 ^ g5 ^ g6 ^ g7, _ => {} } // end switch crc = (crc >> 8) ^ c; i = i + 1; } !crc as i32 } pub fn crc32g(message: &[char]) -> i32 { let g0 = 0xEDB88320; let g1 = g0 >> 1; let g2 = g0 >> 2; let g3 = g0 >> 3; let mut i: usize = 0; let mut crc = 0xFFFFFFFF; while message[i] != '\x00' { let byte = message[i]; // Get next byte. crc = crc ^ byte as i64; for j in 1..0 { // Do two times. let c = ((crc << 31 >> 31) & g3) ^ ((crc << 30 >> 31) & g2) ^ ((crc << 29 >> 31) & g1) ^ ((crc << 28 >> 31) & g0); crc = (crc >> 4) ^ c; } i = i + 1; } !crc as i32 } /* This is derived from crc32f by constructing the constant c using algebraic expressions involving the rightmost eight bits of the crc register, rather than using a 256-way switch statement. We rely on the compiler to compute the constants g>>1, g>>2, etc., and load them into registers ahead of the loops. Note that crc is now a SIGNED integer, so the right shifts of 31 are sign-propagating shifts. When compiled to Cyclops with GCC, this function executes in 22 + 38n instructions, where n is the number of bytes in the input message. There is only one load and one branch executed per byte. */ pub fn crc32h(message: &[char]) -> i64 { let g0 = 0xEDB88320; let g1 = g0 >> 1; let g2 = g0 >> 2; let g3 = g0 >> 3; let g4 = g0 >> 4; let g5 = g0 >> 5; let g6 = (g0 >> 6) ^ g0; let g7 = ((g0 >> 6) ^ g0) >> 1; let mut i = 0; let mut crc = 0xFFFFFFFF; let mut byte; while (byte = message[i]) != () { // Get next byte. crc = crc ^ byte as i64; let c = ((crc << 31 >> 31) & g7) ^ ((crc << 30 >> 31) & g6) ^ ((crc << 29 >> 31) & g5) ^ ((crc << 28 >> 31) & g4) ^ ((crc << 27 >> 31) & g3) ^ ((crc << 26 >> 31) & g2) ^ ((crc << 25 >> 31) & g1) ^ ((crc << 24 >> 31) & g0); crc = (crc >> 8) ^ c; i = i + 1; } return !crc; } #[cfg_attr(not(target_arch = "x86_64"),test_case)] #[cfg_attr(not(target_arch = "riscv64"),test)] fn test_crc() { assert_eq!(crc32a(&['\x00']), 0); assert_eq!(crc32b(&['\x00']), 0); assert_eq!(crc32c(&['\x00']), -16777216); assert_eq!(crc32cx(&mut ['\x00']), -1); assert_eq!(crc32d(&['\x00']), 0); assert_eq!(crc32e(&['\x00']), 1304293916); assert_eq!(crc32f(&['\x00']), -771559539); assert_eq!(crc32g(&['\x00']), 0); assert_eq!(crc32h(&['\x00']), -4294967296); }
use crate::data::{encode_number, EOByte, EOInt}; #[derive(Debug, Default)] pub struct ClientSequencer { sequence_start: EOInt, sequence_increment: EOInt, } impl ClientSequencer { pub fn set_init_sequence(&mut self, s1: EOInt, s2: EOInt) { self.sequence_start = ((s1 as i32) * 7 - 11 + (s2 as i32) - 2) as EOInt; } pub fn set_new_initial_sequence_number(&mut self, s1: EOInt, s2: EOInt) { self.sequence_start = (s1 as i32 - s2 as i32) as EOInt; } fn get_next_sequence_number(&mut self) -> EOInt { self.sequence_start + self.sequence_increment } fn set_next_sequence_increment(&mut self) { self.sequence_increment = (self.sequence_increment + 1) % 10 } pub fn get_sequence_bytes(&mut self) -> Vec<EOByte> { self.set_next_sequence_increment(); let sequence_number = self.get_next_sequence_number(); encode_number(sequence_number).to_vec() } }
/*! ```rudra-poc [target] crate = "rusb" version = "0.6.5" indexed_version = "0.6.0" [report] issue_url = "https://github.com/a1ien/rusb/issues/44" issue_date = 2020-12-18 rustsec_url = "https://github.com/RustSec/advisory-db/pull/580" rustsec_id = "RUSTSEC-2020-0098" [[bugs]] analyzer = "SendSyncVariance" bug_class = "SendSyncVariance" bug_count = 4 rudra_report_locations = [ "src/device.rs:33:1: 33:49", "src/device.rs:34:1: 34:49", "src/device_handle.rs:39:1: 39:55", "src/device_handle.rs:40:1: 40:55", ] ``` !*/ #![forbid(unsafe_code)] fn main() { panic!("This issue was reported without PoC"); }
pub mod bit; pub mod fft; pub mod lazysegtree; pub mod lis; pub mod math; pub mod maxflow; pub mod modint; pub mod perm; pub mod search; pub mod segtree; pub mod slice; pub mod unionfind;
/*! ```rudra-poc [target] crate = "conqueue" version = "0.3.0" [[target.peer]] crate = "crossbeam-utils" version = "0.8.0" [report] issue_url = "https://github.com/longshorej/conqueue/issues/9" issue_date = 2020-11-24 rustsec_url = "https://github.com/RustSec/advisory-db/pull/672" rustsec_id = "RUSTSEC-2020-0117" [[bugs]] analyzer = "SendSyncVariance" bug_class = "SendSyncVariance" bug_count = 3 rudra_report_locations = [ "src/lib.rs:81:1: 81:42", "src/lib.rs:184:1: 184:44", "src/lib.rs:79:1: 79:42" ] ``` !*/ #![forbid(unsafe_code)] use std::ops::Deref; use std::rc::Rc; const NUM_CLONES: usize = 1000000; use conqueue::*; use crossbeam_utils::thread; fn main() { let (tx, mut rx) = conqueue::Queue::unbounded(); let rc = Rc::new(true); tx.push(Box::new(rc.clone())); // We demonstrate the issue by racing the non-atomic reference counter type `Rc` between two threads. thread::scope(|s| { let child = s.spawn(|_| { // &Rc<bool> sent to another thread let smuggled = rx.pop(); for _ in 0..NUM_CLONES { std::mem::forget(smuggled.clone()); } }); // if `child.join().unwrap()` is here, the program succeeds for _ in 0..NUM_CLONES { std::mem::forget(rc.clone()); } child.join().unwrap(); // We made NUM_CLONES on both threads plus initial 1 reference. // But in reality we'll see that the strong_count varies across every run due to data race. assert_eq!(Rc::strong_count(&rc), 2 * NUM_CLONES + 1); }) .unwrap(); }
pub fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } pub fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } pub fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> { (0..n).map(|_| read_vec()).collect() } pub fn read_col<T: std::str::FromStr>(n: u32) -> Vec<T> { (0..n).map(|_| read()).collect() } fn main() { let q: u32 = read(); for _ in 0..q { let v: Vec<i32> = read_vec(); let x1 = v[2] - v[0]; let y1 = v[3] - v[1]; let x2 = v[6] - v[4]; let y2 = v[7] - v[5]; if x1 * y2 == x2 * y1 { println!("2"); } else if x1 * x2 + y1 * y2 == 0 { println!("1"); } else { println!("0"); } } }
pub mod buf_tcpstream; pub mod command;
pub fn rotate(input: &str, key: i8) -> String { let mut output: String = String::new(); let rotate_key = match key { x if x >= 0 => key, _rest => { 26 + key } }; let start_lowercase = b'a'; let end_lowercase = b'z'; let lowercase_letters = (start_lowercase..=end_lowercase).collect::<Vec<u8>>(); let start_uppercase = b'A'; let end_uppercase = b'Z'; let uppercase_letters = (start_uppercase..=end_uppercase).collect::<Vec<u8>>(); for (_index, chr) in input.chars().enumerate() { if chr.is_alphabetic() { match chr.is_lowercase() { true => { let mut circular_iter_lowercase = lowercase_letters.iter().cycle(); let distance_from_a = chr as u8 - 'a' as u8; let value = circular_iter_lowercase.nth(distance_from_a as usize + rotate_key as usize).unwrap(); output.push(*value as char); }, false => { let mut circular_iter_uppercase = uppercase_letters.iter().cycle(); let distance_from_a = chr as u8 - 'A' as u8; let value = circular_iter_uppercase.nth(distance_from_a as usize + rotate_key as usize).unwrap(); output.push(*value as char); } } } else { output.push(chr); } } output }
use std::{iter, sync::Arc}; use crate::tests::helpers::fixtures::get_language; use tree_sitter::{Language, Node, Parser, Point, Query, QueryCursor, TextProvider, Tree}; fn parse_text(text: impl AsRef<[u8]>) -> (Tree, Language) { let language = get_language("c"); let mut parser = Parser::new(); parser.set_language(language).unwrap(); (parser.parse(text, None).unwrap(), language) } fn parse_text_with<T, F>(callback: &mut F) -> (Tree, Language) where T: AsRef<[u8]>, F: FnMut(usize, Point) -> T, { let language = get_language("c"); let mut parser = Parser::new(); parser.set_language(language).unwrap(); let tree = parser.parse_with(callback, None).unwrap(); // eprintln!("{}", tree.clone().root_node().to_sexp()); assert_eq!("comment", tree.clone().root_node().child(0).unwrap().kind()); (tree, language) } fn tree_query<I: AsRef<[u8]>>(tree: &Tree, text: impl TextProvider<I>, language: Language) { let query = Query::new(language, "((comment) @c (#eq? @c \"// comment\"))").unwrap(); let mut cursor = QueryCursor::new(); let mut captures = cursor.captures(&query, tree.root_node(), text); let (match_, idx) = captures.next().unwrap(); let capture = match_.captures[idx]; assert_eq!(capture.index as usize, idx); assert_eq!("comment", capture.node.kind()); } fn check_parsing<I: AsRef<[u8]>>( parser_text: impl AsRef<[u8]>, text_provider: impl TextProvider<I>, ) { let (tree, language) = parse_text(parser_text); tree_query(&tree, text_provider, language); } fn check_parsing_callback<T, F, I: AsRef<[u8]>>( parser_callback: &mut F, text_provider: impl TextProvider<I>, ) where T: AsRef<[u8]>, F: FnMut(usize, Point) -> T, { let (tree, language) = parse_text_with(parser_callback); tree_query(&tree, text_provider, language); } #[test] fn test_text_provider_for_str_slice() { let text: &str = "// comment"; check_parsing(text, text.as_bytes()); check_parsing(text.as_bytes(), text.as_bytes()); } #[test] fn test_text_provider_for_string() { let text: String = "// comment".to_owned(); check_parsing(text.clone(), text.as_bytes()); check_parsing(text.as_bytes(), text.as_bytes()); check_parsing(<_ as AsRef<[u8]>>::as_ref(&text), text.as_bytes()); } #[test] fn test_text_provider_for_box_of_str_slice() { let text: Box<str> = "// comment".to_owned().into_boxed_str(); check_parsing(text.as_bytes(), text.as_bytes()); check_parsing(<_ as AsRef<str>>::as_ref(&text), text.as_bytes()); check_parsing(text.as_ref(), text.as_ref().as_bytes()); check_parsing(text.as_ref(), text.as_bytes()); } #[test] fn test_text_provider_for_box_of_bytes_slice() { let text: Box<[u8]> = "// comment".to_owned().into_boxed_str().into_boxed_bytes(); check_parsing(text.as_ref(), text.as_ref()); check_parsing(text.as_ref(), &*text); check_parsing(&*text, &*text); } #[test] fn test_text_provider_for_vec_of_bytes() { let text: Vec<u8> = "// comment".to_owned().into_bytes(); check_parsing(&*text, &*text); } #[test] fn test_text_provider_for_arc_of_bytes_slice() { let text: Vec<u8> = "// comment".to_owned().into_bytes(); let text: Arc<[u8]> = Arc::from(text); check_parsing(&*text, &*text); check_parsing(text.as_ref(), text.as_ref()); check_parsing(text.clone(), text.as_ref()); } #[test] fn test_text_provider_callback_with_str_slice() { let text: &str = "// comment"; check_parsing(text, |_node: Node<'_>| iter::once(text)); check_parsing_callback( &mut |offset, _point| { (offset < text.len()) .then(|| text.as_bytes()) .unwrap_or_default() }, |_node: Node<'_>| iter::once(text), ); } #[test] fn test_text_provider_callback_with_owned_string_slice() { let text: &str = "// comment"; check_parsing_callback( &mut |offset, _point| { (offset < text.len()) .then(|| text.as_bytes()) .unwrap_or_default() }, |_node: Node<'_>| { let slice: String = text.to_owned(); iter::once(slice) }, ); } #[test] fn test_text_provider_callback_with_owned_bytes_vec_slice() { let text: &str = "// comment"; check_parsing_callback( &mut |offset, _point| { (offset < text.len()) .then(|| text.as_bytes()) .unwrap_or_default() }, |_node: Node<'_>| { let slice: Vec<u8> = text.to_owned().into_bytes(); iter::once(slice) }, ); } #[test] fn test_text_provider_callback_with_owned_arc_of_bytes_slice() { let text: &str = "// comment"; check_parsing_callback( &mut |offset, _point| { (offset < text.len()) .then(|| text.as_bytes()) .unwrap_or_default() }, |_node: Node<'_>| { let slice: Arc<[u8]> = text.to_owned().into_bytes().into(); iter::once(slice) }, ); }
use std::io::prelude::*; use std::{fs::File, io::BufReader}; use crate::solver::Solver; pub struct Solution; impl Solver for Solution { type Input = Vec<u32>; type Output1 = u32; type Output2 = u32; fn parse_input(&self, file: File) -> Self::Input { BufReader::new(file) .lines() .map(|l| l.unwrap()) .map(|l| l.parse::<u32>().unwrap()) .collect() } fn solve_first(&self, input: &Self::Input) -> Self::Output1 { for x in input { for y in input { if x + y == 2020 { return x * y; } } } panic!("Not found!"); } fn solve_second(&self, input: &Self::Input) -> Self::Output2 { for x in input { for y in input { for z in input { if x + y + z == 2020 { return x * y * z; } } } } panic!("Not found!"); } } #[cfg(test)] mod tests { use super::*; fn input() -> Vec<u32> { vec![1721, 979, 366, 299, 675, 1456] } #[test] fn test_first() { let input = input(); let result = Solution {}.solve_first(&input); assert!(result == 514579); } #[test] fn test_second() { let input = input(); let result = Solution {}.solve_second(&input); assert!(result == 241861950); } }
pub mod sd; use std::io; use std::path::Path; pub use fat32::traits; use fat32::vfat::{self, Shared, VFat}; use self::sd::Sd; use pi::mutex::Mutex; pub struct FileSystem(Mutex<Option<Shared<VFat>>>); impl FileSystem { /// Returns an uninitialized `FileSystem`. /// /// The file system must be initialized by calling `initialize()` before the /// first memory allocation. Failure to do will result in panics. pub const fn uninitialized() -> Self { FileSystem(Mutex::new(None)) } /// Initializes the file system. /// /// # Panics /// /// Panics if the underlying disk or file sytem failed to initialize. pub fn initialize(&self) { *self.0.lock() = Some( VFat::from(Sd::new().expect("Sd failed to initialize")) .expect("VFat failed to initalize from Sd"), ); } } impl traits::FileSystem for FileSystem { type File = vfat::File; type Dir = vfat::Dir; type Entry = vfat::Entry; fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<Self::Entry> { if self.0.lock().is_none() { (&self).initialize(); } self.0.lock().as_ref().unwrap().open(path) } fn create_file<P: AsRef<Path>>(self, _path: P) -> io::Result<Self::File> { unimplemented!("read only raspberry") } fn create_dir<P: AsRef<Path>>(self, _path: P, _parents: bool) -> io::Result<Self::Dir> { unimplemented!("read only raspberry") } fn rename<P: AsRef<Path>, Q: AsRef<Path>>(self, _from: P, _to: Q) -> io::Result<()> { unimplemented!("read only raspberry") } fn remove<P: AsRef<Path>>(self, _path: P, _children: bool) -> io::Result<()> { unimplemented!("read only raspberry") } }
// implements linear algebra math submodule pub fn svd(/*matrix*/) /*-> (S,V,D)*/ { } pub fn determinant(/*matrix*/) -> f64 { return 1.0; } pub fn inverse(/*matrix*/) /*-> matrix*/ { } pub fn transpose(/*matrix*/) /*-> matrix*/ { } pub fn eigen(/*matrix*/) /*-> (eigenvectors, eigenvalues)*/ { } pub fn diagonal(/*diagonal*/) /*-> vector*/ { }
use crate::cartridge::Cartridge; use crate::interrupts::InterruptFlag; use crate::interrupts::INTERRUPT_FLAG_ADDR; const DIVIDER_ADDR: u16 = 0xff04; const COUNTER_ADDR: u16 = 0xff05; const MODULO_ADDR: u16 = 0xff06; const TIMER_CONTROL_ADDR: u16 = 0xff07; pub struct MMU { pub memory: [u8; 65536], cartridge: Box<Cartridge>, timer_counter: i32, divider_counter: i32, } pub fn new(cartridge: Box<Cartridge>) -> MMU { let mut memory = [0; 65536]; memory[0xff0f] = 0xe1; memory[0xff10] = 0x80; memory[0xff11] = 0xbf; memory[0xff12] = 0xf3; memory[0xff14] = 0xbf; memory[0xff16] = 0x3f; memory[0xff19] = 0xbf; memory[0xff1a] = 0x7f; memory[0xff1b] = 0xff; memory[0xff1c] = 0x9f; memory[0xff1e] = 0xbf; memory[0xff20] = 0xff; memory[0xff23] = 0xbf; memory[0xff24] = 0x77; memory[0xff25] = 0xf3; memory[0xff26] = 0xf1; memory[0xff40] = 0x91; memory[0xff41] = 0x85; memory[0xff47] = 0xfc; memory[0xff48] = 0xff; memory[0xff49] = 0xff; memory[0xff70] = 0x01; MMU { memory, cartridge, timer_counter: 1024, divider_counter: 0, } } impl MMU { pub fn read_byte(&self, addr: u16) -> u8 { match addr { 0x0000...0x7fff => self.cartridge.read_rom(addr), 0xa000...0xbfff => self.cartridge.read_ram(addr), INTERRUPT_FLAG_ADDR => self.memory[addr as usize] | 0xe0, _ => self.memory[addr as usize], } } pub fn write_byte(&mut self, addr: u16, value: u8) { match addr { 0x0000...0x7fff => self.cartridge.write_rom(addr, value), 0xa000...0xbfff => self.cartridge.write_ram(addr, value), 0xff02 => print!("{}", self.memory[0xff01] as char), DIVIDER_ADDR => { self.memory[addr as usize] = 0; self.divider_counter = 0; self.timer_counter = self.get_timer_frequency() } COUNTER_ADDR => { self.memory[addr as usize] = value; self.timer_counter = self.get_timer_frequency() } TIMER_CONTROL_ADDR => { let old = self.memory[addr as usize]; self.memory[addr as usize] = value; if old != value { self.timer_counter = self.get_timer_frequency() } } 0xff44 | 0xff4d => self.memory[addr as usize] = 0, 0xff46 => { self.memory[addr as usize] = value; self.dma_transfer(value) } 0xff70 => {} _ => self.memory[addr as usize] = value, } } pub fn read_word(&self, addr: u16) -> u16 { ((self.read_byte(addr + 1) as u16) << 8) | (self.read_byte(addr) as u16) } pub fn write_word(&mut self, addr: u16, value: u16) { self.write_byte(addr, (value & 0xff) as u8); self.write_byte(addr + 1, (value >> 8) as u8); } pub fn increment_counters(&mut self, cycles: i32) { self.divider_counter += cycles; if self.divider_counter >= 255 { self.divider_counter -= 255; self.memory[DIVIDER_ADDR as usize] += 1 } if self.is_timer_running() { self.timer_counter -= cycles; if self.timer_counter <= 0 { self.timer_counter += self.get_timer_frequency(); self.increment_timer() } } } fn dma_transfer(&mut self, value: u8) { let addr = (value as u16) << 8; for i in 0..0xa0 { self.write_byte(0xfe00 + i, self.read_byte(addr + i)); } } fn is_timer_running(&self) -> bool { self.memory[TIMER_CONTROL_ADDR as usize] & 0x04 == 0x04 } fn get_timer_frequency(&self) -> i32 { match self.memory[TIMER_CONTROL_ADDR as usize] & 0x03 { 0x0 => 1024, 0x1 => 16, 0x2 => 64, 0x3 => 256, value => panic!("Invalid timer frequency value: {}", value), } } fn increment_timer(&mut self) { match self.memory[COUNTER_ADDR as usize] { 255 => { let modulo = self.memory[MODULO_ADDR as usize]; self.write_byte(COUNTER_ADDR, modulo); self.write_interrupt(InterruptFlag::TIMER); } value => self.write_byte(COUNTER_ADDR, value + 1), } } pub fn write_interrupt(&mut self, interrupt_signal: InterruptFlag) { let flags = self.read_byte(INTERRUPT_FLAG_ADDR); self.write_byte(INTERRUPT_FLAG_ADDR, flags | interrupt_signal as u8) } }
pub fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } pub fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } pub fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> { (0..n).map(|_| read_vec()).collect() } pub fn read_col<T: std::str::FromStr>(n: u32) -> Vec<T> { (0..n).map(|_| read()).collect() } use std::collections::VecDeque; use std::fmt::Display; fn delete(vd: &mut VecDeque<String>, key: &String) { let l = vd.len(); let mut i = 0; while i < l { if *key == vd[i] { break; } i += 1; } if i < l { vd.remove(i as usize); } } fn print_vec_deque<T: Display>(a: &VecDeque<T>, n: usize) { for i in 0..n { print!("{}", a[i]); if i == n - 1 { println!(""); } else { print!(" "); } } } fn main() { let n: u32 = read(); let commands: Vec<String> = read_col(n); let mut vd: VecDeque<String> = VecDeque::new(); for c in commands { if c == "deleteFirst" { vd.pop_front(); } else if c == "deleteLast" { vd.pop_back(); } else { let tmp: Vec<String> = c .trim() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect(); let cmd = &tmp[0]; let key = &tmp[1]; if cmd == "insert" { vd.push_front(key.clone()); } else { delete(&mut vd, key); } } } print_vec_deque(&vd, vd.len() as usize); }
extern crate turtle; use std::fs::File; // use std::io::{Write, Error}; // mod turtle::ast; fn main() { use std::io::*; let mut source = String::new(); match std::env::args().nth(1) { Some(filename) => { File::open(&filename) .expect(&format!("Can't open {}", &filename)) .read_to_string(&mut source) .expect(&format!("Can't read {}", &filename)); } None => { stdin() .read_to_string(&mut source) .expect("Can't read stdin"); } } if source.is_empty() { println!("No input"); return; } turtle::parse_turtle_commands(source); }
use bio::io::fasta; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; pub fn run(filename: &str) { let table: HashMap<&str, &str> = [ ("UUU", "F"), ("CUU", "L"), ("AUU", "I"), ("GUU", "V"), ("UUC", "F"), ("CUC", "L"), ("AUC", "I"), ("GUC", "V"), ("UUA", "L"), ("CUA", "L"), ("AUA", "I"), ("GUA", "V"), ("UUG", "L"), ("CUG", "L"), ("AUG", "M"), ("GUG", "V"), ("UCU", "S"), ("CCU", "P"), ("ACU", "T"), ("GCU", "A"), ("UCC", "S"), ("CCC", "P"), ("ACC", "T"), ("GCC", "A"), ("UCA", "S"), ("CCA", "P"), ("ACA", "T"), ("GCA", "A"), ("UCG", "S"), ("CCG", "P"), ("ACG", "T"), ("GCG", "A"), ("UAU", "Y"), ("CAU", "H"), ("AAU", "N"), ("GAU", "D"), ("UAC", "Y"), ("CAC", "H"), ("AAC", "N"), ("GAC", "D"), ("UAA", "Stop"), ("CAA", "Q"), ("AAA", "K"), ("GAA", "E"), ("UAG", "Stop"), ("CAG", "Q"), ("AAG", "K"), ("GAG", "E"), ("UGU", "C"), ("CGU", "R"), ("AGU", "S"), ("GGU", "G"), ("UGC", "C"), ("CGC", "R"), ("AGC", "S"), ("GGC", "G"), ("UGA", "Stop"), ("CGA", "R"), ("AGA", "R"), ("GGA", "G"), ("UGG", "W"), ("CGG", "R"), ("AGG", "R"), ("GGG", "G"), ] .iter() .cloned() .collect(); let path = Path::new(filename); let reader = fasta::Reader::from_file(&path).unwrap(); for record in reader.records() { let record = record.unwrap(); let record = String::from_utf8(record.seq().to_vec()).unwrap(); let record = record.replace("T", "U"); let mut res = HashSet::new(); for i in 0..record.len() - 3 { match table.get(&record[i..i + 3]) { Some(val) if val as &str == "M" => { let mut current = String::from(""); for j in (i..record.len() - 3).step_by(3) { match table.get(&record[j..j + 3]) { Some(val) if val as &str == "Stop" => { res.insert(current); break; } Some(val) => current.push_str(val), _ => println!("Invalid."), } } } _ => (), } } let record = record.replace("A", "0").replace("U", "A").replace("0", "U"); let record = record.replace("C", "0").replace("G", "C").replace("0", "G"); let record = record.chars().rev().collect::<String>(); for i in 0..record.len() - 3 { match table.get(&record[i..i + 3]) { Some(val) if val as &str == "M" => { let mut current = String::from(""); for j in (i..record.len() - 3).step_by(3) { match table.get(&record[j..j + 3]) { Some(val) if val as &str == "Stop" => { res.insert(current); break; } Some(val) => current.push_str(val), _ => println!("Invalid."), } } } _ => (), } } for r in &res { println!("{}", r); } } }
use std::{ fs::File, io::{self, BufRead, BufReader, BufWriter, Write}, os::unix::prelude::FromRawFd, path::PathBuf, }; use arguably::ArgParser; #[derive(Debug, Clone)] struct Options { input: Option<PathBuf>, output: Option<PathBuf>, } impl Options { pub fn parse() -> std::io::Result<Options> { let mut parser = ArgParser::new().helptext("Usage: runiq...").version("1.0"); if let Err(err) = parser.parse() { err.exit(); } let input = match parser.args.get(0) { Some(input_path) => Some(Self::parse_path(input_path)?), None => None, }; let output = match parser.args.get(1) { Some(output_path) => Some(Self::parse_path(output_path)?), None => None, }; Ok(Options { input: input, output: output, }) } pub fn open_input(&self) -> std::io::Result<Box<dyn BufRead>> { let file = match self.input { Some(ref path) => File::open(path)?, None => unsafe { File::from_raw_fd(0) }, }; let reader = BufReader::with_capacity(4 * 1024, file); Ok(Box::new(reader)) } pub fn open_output(&self) -> std::io::Result<io::BufWriter<File>> { let file = match self.output { Some(ref path) => File::open(path)?, None => unsafe { File::from_raw_fd(1) }, }; let buf_writer = BufWriter::with_capacity(64 * 1024, file); Ok(buf_writer) } fn parse_path(raw_path: &str) -> Result<PathBuf, io::Error> { let mut path_buf = PathBuf::new(); path_buf.push(raw_path); if !path_buf.is_file() { return Err(io::Error::new(io::ErrorKind::Other, "Not a file")); } Ok(path_buf) } } #[allow(dead_code)] fn with_iterator() -> std::io::Result<()> { let options = Options::parse()?; let input = options.open_input()?; let mut output = options.open_output()?; let mut lines_iterator = input.lines(); let first_line = lines_iterator.next(); if first_line.is_none() { return Ok(()); } let mut buffer = first_line.unwrap()?; output.write(&buffer.as_bytes())?; output.write("\n".as_bytes())?; for line in lines_iterator { let line = line?; if line != buffer { buffer = line; output.write(&buffer.as_bytes())?; output.write("\n".as_bytes())?; } } Ok(()) } fn buf_read() -> std::io::Result<()> { let options = Options::parse()?; let mut input = options.open_input()?; let mut output = options.open_output()?; let mut buffer = String::with_capacity(1024); let size = input.read_line(&mut buffer)?; if size == 0 { return Ok(()); } let mut last_line = buffer.clone(); output.write(&buffer.as_bytes())?; buffer.clear(); while input.read_line(&mut buffer)? > 0 { if buffer != last_line { output.write(&buffer.as_bytes())?; last_line.clear(); last_line.push_str(&buffer); } buffer.clear(); } Ok(()) } fn main() -> std::io::Result<()> { // with_iterator()?; buf_read()?; Ok(()) }
#[doc = "Register `CLRFR` reader"] pub type R = crate::R<CLRFR_SPEC>; #[doc = "Register `CLRFR` writer"] pub type W = crate::W<CLRFR_SPEC>; #[doc = "Field `CPERF` reader - Clear the preamble error flag"] pub type CPERF_R = crate::BitReader; #[doc = "Field `CPERF` writer - Clear the preamble error flag"] pub type CPERF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CSERF` reader - Clear the start error flag"] pub type CSERF_R = crate::BitReader; #[doc = "Field `CSERF` writer - Clear the start error flag"] pub type CSERF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CTERF` reader - Clear the turnaround error flag"] pub type CTERF_R = crate::BitReader; #[doc = "Field `CTERF` writer - Clear the turnaround error flag"] pub type CTERF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - Clear the preamble error flag"] #[inline(always)] pub fn cperf(&self) -> CPERF_R { CPERF_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Clear the start error flag"] #[inline(always)] pub fn cserf(&self) -> CSERF_R { CSERF_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Clear the turnaround error flag"] #[inline(always)] pub fn cterf(&self) -> CTERF_R { CTERF_R::new(((self.bits >> 2) & 1) != 0) } } impl W { #[doc = "Bit 0 - Clear the preamble error flag"] #[inline(always)] #[must_use] pub fn cperf(&mut self) -> CPERF_W<CLRFR_SPEC, 0> { CPERF_W::new(self) } #[doc = "Bit 1 - Clear the start error flag"] #[inline(always)] #[must_use] pub fn cserf(&mut self) -> CSERF_W<CLRFR_SPEC, 1> { CSERF_W::new(self) } #[doc = "Bit 2 - Clear the turnaround error flag"] #[inline(always)] #[must_use] pub fn cterf(&mut self) -> CTERF_W<CLRFR_SPEC, 2> { CTERF_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "MDIOS clear flag register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`clrfr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`clrfr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CLRFR_SPEC; impl crate::RegisterSpec for CLRFR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`clrfr::R`](R) reader structure"] impl crate::Readable for CLRFR_SPEC {} #[doc = "`write(|w| ..)` method takes [`clrfr::W`](W) writer structure"] impl crate::Writable for CLRFR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CLRFR to value 0"] impl crate::Resettable for CLRFR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::iter; fn main() { println!("First solution: {}", find_fuel_min(|n| n)); println!("Second solution: {}", find_fuel_min(|n| n * (n + 1) / 2)); } fn find_fuel_min(cost: fn(i64) -> i64) -> i64 { let mut min = i64::MAX; let crabs = input(); for i in 0..3000 { let fuel = crabs .iter() .zip(iter::repeat(i)) .map(|(&a, b)| cost((a - b).abs())) .sum(); min = min.min(fuel); } min } fn input() -> Vec<i64> { include_str!("../../input/07.txt") .split(',') .map(|n| n.parse().unwrap()) .collect() }
extern crate schedme; extern crate time; use schedme::Scheduler; use time::Duration; fn main() { let scheduler = Scheduler::new(); scheduler.keep_it(); // scheduler.add_task(Task { name: "abra" }, Duration::minutes(5)); }
fn main() { if let Err(e) = catr::get_args().and_then(catr::run) { eprintln!("{}", e); std::process::exit(1); } }
use crate::graphs::Graph; use crate::map_model::TrafficControl; use cgmath::MetricSpace; use cgmath::Vector2; use serde::{Deserialize, Serialize}; use slotmap::new_key_type; new_key_type! { pub struct NavNodeID; } #[derive(Clone, Copy, Serialize, Deserialize)] pub struct NavNode { pub pos: Vector2<f32>, pub control: TrafficControl, } impl NavNode { pub fn new(pos: Vector2<f32>) -> Self { NavNode { pos, control: TrafficControl::Always, } } pub fn origin() -> Self { Self::new([0.0, 0.0].into()) } } pub type NavMesh = Graph<NavNodeID, NavNode>; impl NavMesh { pub fn closest_node(&self, pos: Vector2<f32>) -> Option<NavNodeID> { let mut id: NavNodeID = self.ids().next()?; let mut min_dist = self.get(id).unwrap().pos.distance2(pos); for (key, value) in self { let dist = pos.distance2(value.pos); if dist < min_dist { id = key; min_dist = dist; } } Some(id) } }
extern crate gcc; fn main() { let sources = &[ "../../../rt/rust_builtin.c", "../../../rt/rust_android_dummy.c" ]; gcc::compile_library("librust_builtin.a", sources); }
use tokio::prelude::*; use std::net::SocketAddr; use failure::ResultExt; mod proto; pub struct ZooKeeper {} impl ZooKeeper { pub connect(addr: &SocketAddr) -> impl Future<Item = Self, Error = failure::Error> { tokio::net::TcpStream::connect(addr: &SocketAddr).and_then(|stream| { }) } pub handshake(stream: tokio::net::TcpStream) -> impl Future<Item = Self, Error = failure::Error> { let request = proto::Connect {}; let mut stream = proto::wrap(stream); stream.send(request).and_then(|stream| { stream.receive() }).and_then(|(response, stream)| { ZooKeeper {} }) } }
//! REST API of the node mod server; pub mod v0; pub use self::server::{Error, Server}; use crate::blockchain::BlockchainR; use crate::fragment::Logs; use crate::settings::start::{Error as ConfigError, Rest}; use std::sync::{Arc, Mutex}; pub struct Context { pub stats_counter: v0::node::stats::StatsCounter, pub blockchain: BlockchainR, pub transaction_task: v0::message::post::Task, pub logs: Logs, } pub fn start_rest_server(config: &Rest, context: Context) -> Result<Server, ConfigError> { let prefix = config .prefix .as_ref() .map(|prefix| prefix.as_str()) .unwrap_or(""); Server::builder(config.pkcs12.clone(), config.listen.clone(), prefix) .add_handler(v0::account::create_handler(context.blockchain.clone())) .add_handler(v0::block::create_handler(context.blockchain.clone())) .add_handler(v0::node::stats::create_handler(context.stats_counter)) .add_handler(v0::tip::create_handler(context.blockchain.clone())) .add_handler(v0::message::post::create_handler(context.transaction_task)) .add_handler(v0::message::logs::create_handler(Arc::new(Mutex::new( context.logs, )))) .add_handler(v0::utxo::create_handler(context.blockchain)) .build() .map_err(|e| e.into()) }
#[macro_use] extern crate clap; extern crate image; extern crate imageproc; extern crate rusttype; use clap::App; use std::iter::Iterator; use image::{DynamicImage, GenericImageView, Rgba}; use imageproc::drawing::draw_text_mut; use rusttype::{Font, FontCollection, Scale, Rect, point}; const TITLE: &str = "LGTM"; const DESCRIPTION: &str = "Looks Good To Me"; struct Size { first_padding: u32, width: u32, height: u32, } fn main() { let yaml = load_yaml!("cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let source = matches.value_of("source").unwrap(); let target = matches.value_of("target").unwrap(); let mut image = image::open(source).unwrap(); let font = Vec::from(include_bytes!("Roboto-Black.ttf") as &[u8]); let font = FontCollection::from_bytes(font).unwrap().into_font().unwrap(); let (w, h) = image.dimensions(); let scale = h as f32 / 5.0; let scale = Scale {x: scale, y: scale}; let size = get_text_size(&font, scale, TITLE); let title_x = (w / 2) - (size.width / 2) - size.first_padding; let title_y = (h * 2/3) - (size.height / 2); let padding = h / 30; let desc_y = title_y + size.height + padding; let color = Rgba([0u8, 0u8, 0u8, 1u8]); draw_description(&mut image, color, desc_y, &font); draw_text_mut(&mut image, color, title_x, title_y, scale, &font, TITLE); let _ = image.save(target).unwrap(); } fn draw_description(image: &mut DynamicImage, color: Rgba<u8>, y: u32 , font: &Font) { let (w, h) = image.dimensions(); let scale = h as f32 / 10.0; let margin = w / 20; let scale = Scale {x: scale, y: scale}; let splitted: Vec<&str> = DESCRIPTION.split(" ").collect(); let sizes: Vec<Size> = splitted.iter() .map(|s| get_text_size(&font, scale, s)) .collect(); let width: u32 = sizes.iter().map(|s| s.width).sum::<u32>() + ((splitted.len() - 1) as u32 * margin); let mut current_x = (w / 2) - (width / 2); for (s, size) in splitted.iter().zip(sizes.iter()) { current_x -= size.first_padding; draw_text_mut(image, color, current_x, y, scale, &font, s); current_x += margin + size.width + size.first_padding; } } fn get_text_size(font: &Font, scale: Scale, text: &str) -> Size { let point = point(0.0, font.v_metrics(scale).ascent); let glyphs: Vec<Rect<i32>> = font.layout(text, scale, point) .map(|g| g.pixel_bounding_box().unwrap()) .collect(); let first_x = glyphs.first().unwrap().min.x; let width = glyphs.last().unwrap().max.x - first_x; let height = glyphs.iter().map(|b| b.height()).max().unwrap(); return Size {first_padding: first_x as u32, width: width as u32, height: height as u32}; }
impl PacketConfig for Radio<'_> { pub fn packet_rssi(&self) -> u8 { // let freq = self.frequency.get() as f64; let rssi_base; if freq < 868E6 { rssi_base = 164; } else { rssi_base = 157; } self.register_return(RegMap::RegPktRssiValue) - rssi_base } pub fn packet_snr(&self) -> f32 { self.register_return(RegMap::RegPktSnrValue) as f32 * 0.25 } #[allow(arithmetic_overflow)] pub fn packet_frequency_error(&self) -> i64 { let mut freq_error; freq_error = self.register_return(RegMap::RegFreqErrorMsb) & 0b111; freq_error <<= 8; freq_error += self.register_return(RegMap::RegFreqErrorMid); freq_error <<= 8; freq_error += self.register_return(RegMap::RegFreqErrorLsb); if self.register_return(RegMap::RegFreqErrorMsb) & 0b1000 != 0 { // Sign bit is on //freq_error 24288; // B1000'0000'0000'0000'0000 } let f_xtal = 32E6 as f64; // Fxosc: crystal oscillator (Xtal) frequency (2.5. Chip Specification, p. 14) let f_error = ((freq_error << 24) as f64 / f_xtal) * (self.get_signal_bandwidth() as f64 / 500000.0); // p. 37 return f_error as i64; } pub fn set_power(&self, mut level: i8, output_pin: u8) { if output_pin == 0 { // Rfo if level < 0 { level = 0; } else if level > 14 { level = 14; } self.register_write(RegMap::RegPaConfig, 0x70 | level as u8); } else { // Pa Boost if level > 17 { if level > 20 { level = 20; } // subtract 3 from level, so 18 - 20 maps to 15 - 17 level -= 3; // High Power +20 dBm Operation (Semtech Sx1276/77/78/79 5.4.3.) self.register_write(RegMap::RegPaDac, 0x87); self.set_ocp(140); } else { if level < 2 { level = 2; } //Default value PaHf/Lf or +17dBm self.register_write(RegMap::RegPaDac, 0x84); self.set_ocp(100); } self.register_write(RegMap::RegPaConfig, PA_BOOST | (level as u8 - 2)); } } pub fn set_frequency(&self, frequency: u64) { self.frequency.set(frequency); let frf = (frequency << 19) / 32000000; self.register_write(RegMap::RegFrfMsb, (frf >> 16) as u8); self.register_write(RegMap::RegFrfMid, (frf >> 8) as u8); self.register_write(RegMap::RegFrfLsb, (frf >> 0) as u8); } pub fn get_spreading_factor(&self) -> u8 { self.register_return(RegMap::RegModemConfig2) >> 4 } pub fn set_spreading_factor(&self, mut sf: u8) { if sf < 6 { sf = 6; } else if sf > 12 { sf = 12; } if sf == 6 { self.register_write(RegMap::RegDetectionOptimize, 0xc5); self.register_write(RegMap::RegDetectionThreshold, 0x0c); } else { self.register_write(RegMap::RegDetectionOptimize, 0xc3); self.register_write(RegMap::RegDetectionThreshold, 0x0a); } self.register_write( RegMap::RegModemConfig2, (self.register_return(RegMap::RegModemConfig2) as u8 & 0x0f) | ((sf << 4) & 0xf0), ); self.set_ldo_flag(); } pub fn get_signal_bandwidth(&self) -> f64 { let bw = (self.register_return(RegMap::RegModemConfig1) >> 4) as u8; match bw { 0 => return 7.8E3, 1 => return 10.4E3, 2 => return 15.6E3, 3 => return 20.8E3, 4 => return 31.25E3, 5 => return 41.7E3, 6 => return 62.5E3, 7 => return 125E3, 8 => return 250E3, _ => return 500E3, } } pub fn set_signal_bandwidth(&self, sbw: f64) { let bw: u8; if sbw <= 7.8E3 { bw = 0; } else if sbw <= 10.4E3 { bw = 1; } else if sbw <= 15.6E3 { bw = 2; } else if sbw <= 20.8E3 { bw = 3; } else if sbw <= 31.25E3 { bw = 4; } else if sbw <= 41.7E3 { bw = 5; } else if sbw <= 62.5E3 { bw = 6; } else if sbw <= 125E3 { bw = 7; } else if sbw <= 250E3 { bw = 8; } else /*if sbw <= 250E3*/ { bw = 9; } self.register_write( RegMap::RegModemConfig1, (self.register_return(RegMap::RegModemConfig1) & 0x0f) as u8 | (bw << 4), ); self.set_ldo_flag(); } pub fn set_ldo_flag(&self) { // Section 4.1.1.5 let symbol_duration = 1000 / (self.get_signal_bandwidth() / (1 << self.get_spreading_factor()) as f64) as i64; // Section 4.1.1.6 let ldo_on: bool = symbol_duration > 16; let config3: u8; if ldo_on { config3 = self.register_return(RegMap::RegModemConfig3) | 0b1000; } else { config3 = self.register_return(RegMap::RegModemConfig3); } self.register_write(RegMap::RegModemConfig3, config3); } pub fn set_coding_rate4(&self, mut denominator: u8) { if denominator < 5 { denominator = 5; } else if denominator > 8 { denominator = 8; } let cr = denominator - 4 as u8; self.register_write( RegMap::RegModemConfig1, (self.register_return(RegMap::RegModemConfig1) as u8 & 0xf1) | (cr << 1), ); } pub fn set_preamble_length(&self, length: i64) { self.register_write(RegMap::RegPreambleMsb, (length >> 8) as u8); self.register_write(RegMap::RegPreambleLsb, (length >> 0) as u8); } pub fn set_sync_word(&self, sw: u8) { self.register_write(RegMap::RegSyncWord, sw); } pub fn enable_crc(&self) { self.register_write( RegMap::RegModemConfig2, self.register_return(RegMap::RegModemConfig2) as u8 | 0x04, ); } pub fn disable_crc(&self) { self.register_write( RegMap::RegModemConfig2, self.register_return(RegMap::RegModemConfig2) as u8 & 0xfb, ); } pub fn enable_invert_iq(&self) { self.register_write(RegMap::RegInvertiq, 0x66); self.register_write(RegMap::RegInvertiq2, 0x19); } pub fn disable_invert_iq(&self) { self.register_write(RegMap::RegInvertiq, 0x27); self.register_write(RegMap::RegInvertiq2, 0x1d); } pub fn set_ocp(&self, ma: u8) { let mut ocp_trim = 27 as u8; if ma <= 120 { ocp_trim = (ma - 45) / 5; } else if ma <= 240 { ocp_trim = (ma + 30) / 10; } self.register_write(RegMap::RegOcp, 0x20 | (0x1F & ocp_trim)); } }
use futures::{Future, Stream}; use tokio::timer::Interval; use std::time::{Duration, Instant}; pub(crate) fn timeloop<F: FnMut(Instant) -> bool>( func: F, period: Duration, ) -> impl Future<Item = (), Error = ()> { Interval::new(Instant::now(), period) .map_err(move |e| { error!( target: "server", "A timer error occurred: {}", e ); }) .map(func) .take_while(|&x| Ok(x)) .for_each(|_| Ok(())) }
use crate::{ import::*, * }; /// A futures 0.3 Sink/Stream of [WsMessage]. Created with [WsMeta::connect](crate::WsMeta::connect). /// /// ## Closing the connection /// /// When this is dropped, the connection closes, but you should favor calling one of the close /// methods on [WsMeta](crate::WsMeta), which allow you to set a proper close code and reason. /// /// Since this implements [`Sink`], it has to have a close method. This method will call the /// web api [`WebSocket.close`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close) /// without parameters. Eg. a default value of `1005` will be assumed for the close code. The /// situation is the same when dropping without calling close. /// /// **Warning**: This object holds the callbacks needed to receive events from the browser. /// If you drop it before the close event was emitted, you will no longer receive events. Thus, /// observers will never receive a `Close` event. Drop will issue a `Closing` event and this /// will be the very last event observers receive. The the stream will end if `WsMeta` is also dropped. /// /// See the [integration tests](https://github.com/najamelan/ws_stream_wasm/blob/release/tests/futures_codec.rs) /// if you need an example. /// // pub struct WsStream { ws: SendWrapper< Rc< WebSocket > >, // The queue of received messages // queue: SendWrapper< Rc<RefCell< VecDeque<WsMessage> >> >, // Last waker of task that wants to read incoming messages to be woken up on a new message // waker: SendWrapper< Rc<RefCell< Option<Waker> >> >, // Last waker of task that wants to write to the Sink // sink_waker: SendWrapper< Rc<RefCell< Option<Waker> >> >, // A pointer to the pharos of WsMeta for when we need to listen to events // pharos: SharedPharos<WsEvent>, // The callback closures. // _on_open : SendWrapper< Closure< dyn FnMut() > >, _on_error: SendWrapper< Closure< dyn FnMut() > >, _on_close: SendWrapper< Closure< dyn FnMut( JsCloseEvt ) > >, _on_mesg : SendWrapper< Closure< dyn FnMut( MessageEvent ) > >, // This allows us to store a future to poll when Sink::poll_close is called // closer: Option<SendWrapper< Pin<Box< dyn Future< Output=() > + Send >> >>, } impl WsStream { /// Create a new WsStream. // pub(crate) fn new ( ws : SendWrapper< Rc<WebSocket> > , pharos : SharedPharos<WsEvent> , on_open : SendWrapper< Closure< dyn FnMut() > > , on_error: SendWrapper< Closure< dyn FnMut() > > , on_close: SendWrapper< Closure< dyn FnMut( JsCloseEvt ) > > , ) -> Self { let waker : SendWrapper< Rc<RefCell<Option<Waker>>> > = SendWrapper::new( Rc::new( RefCell::new( None )) ); let sink_waker: SendWrapper< Rc<RefCell<Option<Waker>>> > = SendWrapper::new( Rc::new( RefCell::new( None )) ); let queue = SendWrapper::new( Rc::new( RefCell::new( VecDeque::new() ) ) ); let q2 = queue.clone(); let w2 = waker.clone(); let ph2 = pharos.clone(); // Send the incoming ws messages to the WsMeta object // #[ allow( trivial_casts ) ] // let on_mesg = Closure::wrap( Box::new( move |msg_evt: MessageEvent| { match WsMessage::try_from( msg_evt ) { Ok (msg) => q2.borrow_mut().push_back( msg ), Err(err) => notify( ph2.clone(), WsEvent::WsErr( err ) ), } if let Some( w ) = w2.borrow_mut().take() { w.wake() } }) as Box< dyn FnMut( MessageEvent ) > ); // Install callback // ws.set_onmessage ( Some( on_mesg.as_ref().unchecked_ref() ) ); // When the connection closes, we need to verify if there are any tasks // waiting on poll_next. We need to wake them up. // let ph = pharos .clone(); let wake = waker .clone(); let swake = sink_waker.clone(); let wake_on_close = async move { let mut rx; // Scope to avoid borrowing across await point. // { match ph.observe_shared( Filter::Pointer( WsEvent::is_closed ).into() ).await { Ok(events) => rx = events , Err(e) => unreachable!( "{:?}", e ) , // only happens if we closed it. } } rx.next().await; if let Some(w) = &*wake.borrow() { w.wake_by_ref(); } if let Some(w) = &*swake.borrow() { w.wake_by_ref(); } }; spawn_local( wake_on_close ); Self { ws , queue , waker , sink_waker , pharos , closer : None , _on_mesg : SendWrapper::new( on_mesg ) , _on_open : on_open , _on_error : on_error , _on_close : on_close , } } /// Verify the [WsState] of the connection. // pub fn ready_state( &self ) -> WsState { self.ws.ready_state().try_into() // This can't throw unless the browser gives us an invalid ready state // .expect_throw( "Convert ready state from browser API" ) } /// Access the wrapped [web_sys::WebSocket](https://docs.rs/web-sys/0.3.25/web_sys/struct.WebSocket.html) directly. /// /// _ws_stream_wasm_ tries to expose all useful functionality through an idiomatic rust API, so hopefully /// you won't need this, however if I missed something, you can. /// /// ## Caveats /// If you call `set_onopen`, `set_onerror`, `set_onmessage` or `set_onclose` on this, you will overwrite /// the event listeners from `ws_stream_wasm`, and things will break. // pub fn wrapped( &self ) -> &WebSocket { &self.ws } /// Wrap this object in [`IoStream`]. `IoStream` implements `AsyncRead`/`AsyncWrite`/`AsyncBufRead`. /// **Beware**: that this will transparenty include text messages as bytes. // pub fn into_io( self ) -> IoStream< WsStreamIo, Vec<u8> > { IoStream::new( WsStreamIo::new( self ) ) } } impl fmt::Debug for WsStream { fn fmt( &self, f: &mut fmt::Formatter<'_> ) -> fmt::Result { write!( f, "WsStream for connection: {}", self.ws.url() ) } } impl Drop for WsStream { // We don't block here, just tell the browser to close the connection and move on. // fn drop( &mut self ) { match self.ready_state() { WsState::Closing | WsState::Closed => {} _ => { // This can't fail. Only exceptions are related to invalid // close codes and reason strings to long. // self.ws.close().expect( "WsStream::drop - close ws socket" ); // Notify Observers. This event is not emitted by the websocket API. // notify( self.pharos.clone(), WsEvent::Closing ) } } self.ws.set_onmessage( None ); self.ws.set_onerror ( None ); self.ws.set_onopen ( None ); self.ws.set_onclose ( None ); } } impl Stream for WsStream { type Item = WsMessage; // Currently requires an unfortunate copy from Js memory to WASM memory. Hopefully one // day we will be able to receive the MessageEvt directly in WASM. // fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Option< Self::Item >> { // Once the queue is empty, check the state of the connection. // When it is closing or closed, no more messages will arrive, so // return Poll::Ready( None ) // if self.queue.borrow().is_empty() { *self.waker.borrow_mut() = Some( cx.waker().clone() ); match self.ready_state() { WsState::Open | WsState::Connecting => Poll::Pending , _ => None.into() , } } // As long as there is things in the queue, just keep reading // else { self.queue.borrow_mut().pop_front().into() } } } impl Sink<WsMessage> for WsStream { type Error = WsErr; // Web API does not really seem to let us check for readiness, other than the connection state. // fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>> { match self.ready_state() { WsState::Connecting => { *self.sink_waker.borrow_mut() = Some( cx.waker().clone() ); Poll::Pending } WsState::Open => Ok(()).into(), _ => Err( WsErr::ConnectionNotOpen ).into(), } } fn start_send( self: Pin<&mut Self>, item: WsMessage ) -> Result<(), Self::Error> { match self.ready_state() { WsState::Open => { // The send method can return 2 errors: // - unpaired surrogates in UTF (we shouldn't get those in rust strings) // - connection is already closed. // // So if this returns an error, we will return ConnectionNotOpen. In principle // we just checked that it's open, but this guarantees correctness. // match item { WsMessage::Binary( d ) => self.ws.send_with_u8_array( &d ).map_err( |_| WsErr::ConnectionNotOpen )? , WsMessage::Text ( s ) => self.ws.send_with_str ( &s ).map_err( |_| WsErr::ConnectionNotOpen )? , } Ok(()) }, // Connecting, Closing or Closed // _ => Err( WsErr::ConnectionNotOpen ), } } fn poll_flush( self: Pin<&mut Self>, _: &mut Context<'_> ) -> Poll<Result<(), Self::Error>> { Ok(()).into() } // TODO: find a simpler implementation, notably this needs to spawn a future. // this can be done by creating a custom future. If we are going to implement // events with pharos, that's probably a good time to re-evaluate this. // fn poll_close( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>> { let state = self.ready_state(); // First close the inner connection // if state == WsState::Connecting || state == WsState::Open { // Can't fail // self.ws.close().unwrap_throw(); notify( self.pharos.clone(), WsEvent::Closing ); } // Check whether it's closed // match state { WsState::Closed => Ok(()).into(), _ => { // Create a future that will resolve with the close event, so we can poll it. // if self.closer.is_none() { let mut ph = self.pharos.clone(); let closer = async move { let mut rx = match ph.observe( Filter::Pointer( WsEvent::is_closed ).into() ).await { Ok(events) => events , Err(e) => unreachable!( "{:?}", e ) , // only happens if we closed it. }; rx.next().await; }; self.closer = Some(SendWrapper::new( closer.boxed() )); } ready!( self.closer.as_mut().unwrap().as_mut().poll(cx) ); Ok(()).into() } } } }
use super::font::Font; use crate::graphics::drawable::Drawable; use crate::graphics::canvas::Canvas; use crate::graphics::color::Color; use wasm_bindgen::JsValue; const PX_STR: &str = "px"; /// A struct representing the style of a [Text](struct.Text.html). pub struct TextStyle { /// Italic pub italic: bool, /// Bold pub bold: bool, /// Underlined is not supported for now! pub underlined: bool, /// The color of the text pub color: Color } impl Default for TextStyle { fn default() -> TextStyle { TextStyle { italic: false, bold: false, underlined: false, color: Color::black() } } } /// A text drawable on a [Canvas](../canvas/struct.Canvas.html). /// Multiline (\n) works only when using a character size in px. pub struct Text<'a> { /// The coords of the text in px. pub coords: (usize, usize), /// The [font](../font/struct.Font.html) of the text. pub font: &'a Font, /// The text. pub text: String, /// The [style](struct.TextStyle.html) of the text (bold/italic...) pub style: TextStyle, /// The character_size. example: (14, "px") pub character_size: (usize, &'a str) } impl<'a> Text<'a> { /// Create a new text with default values. pub fn new(font: &'a Font) -> Text<'a> { Text { coords: (0,0), font, text: String::new(), style: TextStyle::default(), character_size: (26, PX_STR) } } /// Create a new text with some default values. pub fn new_with_text_and_coords(font: &'a Font, text: String, coords: (usize, usize)) -> Text<'a> { Text { coords, font, text, style: TextStyle::default(), character_size: (26, PX_STR) } } /// Create a new text with no default value. pub fn new_with_options(font: &'a Font, text: String, coords: (usize, usize), style: TextStyle, character_size: (usize, &'a str)) -> Text<'a> { Text { coords, font, text, style, character_size } } /// Set the displayed text. pub fn set_text(&mut self, text: String) { self.text = text; } /// Set the [style](struct.TextStyle.html) of the text. pub fn set_style(&mut self, style: TextStyle) { self.style = style; } /// Get the width of the text /// Needs a mutable reference to a canvas pub fn get_width(&self, mut canvas: &mut Canvas) -> f64 { self.apply_style_on_canvas(&mut canvas); let mut max_width = 0.0; for text in self.text.split('\n') { let width = canvas.context.measure_text(&text).unwrap().width(); if width > max_width { max_width = width; } } max_width } /// Get the width of the text. /// Works only for font size specified using a value in px. pub fn get_height(&self) -> usize { self.text.split('\n').count() * self.character_size.0 } fn apply_style_on_canvas(&self, canvas: &mut Canvas) { let mut font = String::new(); if self.style.italic { font.push_str("italic "); } if self.style.bold { font.push_str("bold "); } if self.style.underlined { unimplemented!("avoid underlined text for now"); } font.push_str(&self.character_size.0.to_string()); font.push_str(self.character_size.1); font.push_str(" '"); font.push_str(&self.font.name); font.push_str("'"); canvas.context.set_font(&font); canvas.context.set_fill_style(&JsValue::from_str(&self.style.color.to_string())); } } impl<'a> Drawable for Text<'a> { fn draw_on_canvas(&self, mut canvas: &mut Canvas) { self.apply_style_on_canvas(&mut canvas); for (idx, text) in self.text.split('\n').enumerate() { let mut coords = self.coords; coords.1 += self.character_size.0 * idx; canvas.fill_text(coords, text, None); } } }
use appData::AppData; use std::thread; use std::thread::JoinHandle; use std::sync::{Mutex,Arc,RwLock,Weak}; use std::io::{self, ErrorKind}; use std::rc::Rc; use mio::*; use mio::tcp::*; use slab::Slab; use std::net::SocketAddr; use server::{Server,DisconnectionReason,DisconnectionSource}; use packet::{ClientToServerTCPPacket, ClientToServerUDPPacket, ServerToClientTCPPacket, ServerToClientUDPPacket}; pub struct Player{ isActive:bool, server:Arc<Server>, playerID:usize, userID:usize, userName:String, } impl Player{ pub fn new(server:Arc<Server>, playerID:usize, userID:usize, userName:String) -> Player { Player{ isActive:true, server:server, playerID:playerID, userID:userID, userName:userName, } } pub fn _disconnect(&mut self, reason:DisconnectionReason){ self.isActive=false; } pub fn disconnect(&mut self, reason:DisconnectionReason){ self._disconnect(reason.clone()); self.server.tryDisconnectTCPConnection( self.playerID, reason.clone() ); self.server.tryDisconnectUDPConnection( self.playerID, reason.clone() ); } //self.server.disconnectPlayersList.lock().push((self.playerID, DisconnectionSource::Player, reason)); /* match reason{ DisconnectionReason::Hup => println!("hup"), DisconnectionReason::ServerShutdown => println!("server shutdown"), DisconnectionReason::FatalError( ref msg ) => println!("fatal error {}",msg), DisconnectionReason::ClientDesire( ref msg ) => println!("client desire {}",msg), DisconnectionReason::ServerDesire( ref msg ) => println!("server desire {}",msg), DisconnectionReason::ClientError( ref msg ) => println!("client error {}",msg ), DisconnectionReason::ServerError( ref msg ) => println!("server error {}",msg ), } match source{ DisconnectionSource::TCP => { //только try_lock server.getUDPConnectionAnd(playerID, | connection | connection.disconnect( source.clone(), reason.clone() )), }, DisconnectionSource::UDP => { server.getTCPConnectionAnd(Token(token), | connection | connection.disconnect( source.clone(), reason.clone() )), }, DisconnectionSource::Player => { /* match *udpConnectionGuard { Some( token ) => self.server.getUDPConnectionAnd(token, | connection | connection.disconnect( source.clone(), reason.clone() )), None => {}, } */ server.getTCPConnectionAnd(Token(token), | connection | connection.disconnect( source.clone(), reason.clone() )), }, } let mut playersGuard=server.players.write().unwrap(); */ pub fn sendDatagram(playerID:usize, datagram:&Vec<u8>){ //не паникует, если не находит udpConnection } pub fn sendMessage(playerID:usize, message:Vec<u8>){ //не паникует, если не находит tcpConnection } pub fn processMessage(&mut self, packet:&ClientToServerTCPPacket) -> Result<(), String> { println!("process TCP packet"); Ok(()) } pub fn processDatagram(&mut self, packet:&ClientToServerUDPPacket, time:u64) { println!("process UDP packet {}", time); } }
use std::io; use std::fmt; /// An RFC1035 `<domain-name>` (sequence of labels) /// #[deriving(PartialEq,Eq,Hash,Clone)] pub struct Name { labels: Vec<String>, } impl Name { pub fn new() -> Name { Name { labels: Vec::new() } } /// Parse a byte slice containing an already-decompressed name. pub fn parse_decompressed(buf: &[u8]) -> io::IoResult<Name> { let mut labels: Vec<String> = Vec::with_capacity(10); let mut reader = io::BufReader::new(buf); loop { let llen = try!(reader.read_u8()); if llen == 0 { break; } else if llen > 63 { return Err(io::standard_error(io::InvalidInput)); } else { let str_read = String::from_utf8(try!(reader.read_exact(llen as uint))); match str_read { Ok(s) => labels.push(s), Err(_) => return Err(io::standard_error(io::InvalidInput)), } } } Ok(Name { labels: labels }) } /// Generate a `Vec<u8>` containing this name in fully-expanded /// RFC1035 label format. pub fn to_bytes(&self) -> io::IoResult<Vec<u8>> { let mut vec: Vec<u8> = Vec::new(); for l in self.labels.iter() { try!(vec.write_u8(l.len() as u8)); try!(vec.write_str(l.as_slice())); } try!(vec.write_u8(0)); Ok(vec) } /// Push this name in fully-expanded RFC1035 label format onto an /// existing `Vec<u8>` pub fn push_bytes(&self, vec: &mut Vec<u8>) -> io::IoResult<()> { for l in self.labels.iter() { try!(vec.write_u8(l.len() as u8)); try!(vec.write_str(l.as_slice())); } try!(vec.write_u8(0)); Ok(()) } /// Generate a vector of Name objects containing pub fn gen_suffixes(&self) -> Vec<Name> { let mut output: Vec<Name> = Vec::new(); let mut clone = self.clone(); for i in range(0, output.len() - 1) { match clone.labels.remove(0) { Some(_) => { output.push(clone.clone()); continue; }, None => { break; }, } } output } } impl fmt::Show for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "{}", self.labels.connect("."))); write!(f, ".") } } /// Trait for `io::Reader`s that implement DNS packet parsing. /// Due to the way DNS name compression works readers likely /// need to implement `io::Seek`. pub trait DNSNameReader { fn read_dns_name(&mut self) -> io::IoResult<Name>; } impl<'a> DNSNameReader for io::BufReader<'a> { fn read_dns_name(&mut self) -> io::IoResult<Name> { let mut labels: Vec<String> = Vec::new(); let mut follow = false; let mut return_to = 0u64; // Read in labels loop { // Get the next label's size let llen = try!(self.read_u8()); if llen == 0 { // Zero length labels are the root, so we're done break; } else if (llen & 0xC0) == 0xC0 { // Labels with the two high order bits set (0xC0) // are pointers. let jump_to = try!(self.read_u8()) as i64; // If this is the first pointer encountered, store // the current reader location to restore later. if !follow { return_to = try!(self.tell()); follow = true; } // Seek to the pointer location try!(self.seek(jump_to, io::SeekStyle::SeekSet)); continue; } else { let str_read = String::from_utf8(try!(self.read_exact(llen as uint))); match str_read { Ok(s) => labels.push(s), Err(_) => return Err(io::standard_error(io::InvalidInput)), } } } if follow { // Restore the reader location to the byte after the first // pointer followed during the read. try!(self.seek(return_to as i64, io::SeekStyle::SeekSet)); } Ok(Name { labels: labels }) } } #[cfg(test)] mod test_dns_name_reader { use std::io; use super::DNSNameReader; static NET1_RS: &'static [u8] = include_bin!("../tests/packets/net1-rs.bin"); #[test] fn test_read_name() { let mut r = io::BufReader::new(NET1_RS); // Regular pointerless read (first name in packet) r.seek(0x0C, io::SeekStyle::SeekSet).ok(); let l1 = r.read_dns_name().ok().unwrap(); assert_eq!(l1.labels.len(), 1); assert_eq!(l1.labels[0].as_slice(), "net"); } #[test] fn test_read_single_ptr_follow() { let mut r = io::BufReader::new(NET1_RS); // Single pointer follow (second name in packet) r.seek(0x21, io::SeekStyle::SeekSet).ok(); let l2 = r.read_dns_name().ok().unwrap(); assert_eq!(l2.labels.len(), 3); assert_eq!(l2.labels[0].as_slice(), "m"); assert_eq!(l2.labels[1].as_slice(), "gtld-servers"); assert_eq!(l2.labels[2].as_slice(), "net"); } #[test] fn test_read_multi_ptr_follow() { let mut r = io::BufReader::new(NET1_RS); // Multi-pointer follow (nth name in packet) r.seek(0x5e, io::SeekStyle::SeekSet).ok(); let l2 = r.read_dns_name().ok().unwrap(); assert_eq!(l2.labels.len(), 3); assert_eq!(l2.labels[0].as_slice(), "j"); assert_eq!(l2.labels[1].as_slice(), "gtld-servers"); assert_eq!(l2.labels[2].as_slice(), "net"); // Test seek restoration after multi-pointer follow let l1 = r.read_dns_name().ok().unwrap(); assert_eq!(l1.labels.len(), 1); assert_eq!(l1.labels[0].as_slice(), "net"); } }
#[macro_use] extern crate criterion; #[macro_use] extern crate lazy_static; extern crate lab; extern crate rand; use criterion::Criterion; use rand::distributions::Standard; use rand::Rng; lazy_static! { static ref LABS: Vec<lab::Lab> = { let rand_seed = [0u8; 32]; let rng: rand::rngs::StdRng = rand::SeedableRng::from_seed(rand_seed); let labs: Vec<[f32; 8]> = rng.sample_iter(&Standard).take(512).collect(); labs.iter() .map(|lab| lab::Lab { l: lab[0], a: lab[1], b: lab[2], }) .collect() }; } fn labs_to_rgbs(c: &mut Criterion) { c.bench_function("[Lab] -> [RGB]", move |b| { b.iter(|| lab::__scalar::labs_to_rgbs(&LABS)) }); } fn labs_to_rgb_bytes(c: &mut Criterion) { c.bench_function("[Lab] -> [u8]", move |b| { b.iter(|| lab::__scalar::labs_to_rgb_bytes(&LABS)) }); } fn labs_to_rgbs_simd(c: &mut Criterion) { c.bench_function("[Lab] -> [RGB] (simd)", move |b| { b.iter(|| lab::labs_to_rgbs(&LABS)) }); } fn labs_to_rgb_bytes_simd(c: &mut Criterion) { c.bench_function("[Lab] -> [u8] (simd)", move |b| { b.iter(|| lab::labs_to_rgb_bytes(&LABS)) }); } criterion_group!( benches, labs_to_rgbs, labs_to_rgb_bytes, labs_to_rgbs_simd, labs_to_rgb_bytes_simd ); criterion_main!(benches);
pub fn eval_rpn(tokens: Vec<String>) -> i32 { let mut stack = vec![]; for token in tokens { match token.as_str() { "+" => { let a = stack.pop().unwrap(); let b = stack.pop().unwrap(); stack.push(b + a); }, "-" => { let a = stack.pop().unwrap(); let b = stack.pop().unwrap(); stack.push(b - a); }, "*" => { let a = stack.pop().unwrap(); let b = stack.pop().unwrap(); stack.push(b * a); }, "/" => { let a = stack.pop().unwrap(); let b = stack.pop().unwrap(); stack.push(b / a); }, s => { stack.push(s.parse::<i32>().unwrap()); } } } stack[0] }
/// see https://github.com/hecrj/iced/blob/0.2/examples/progress_bar/src/main.rs use std::char; use iced::widget::slider; use iced::{Column, Element, Row, Sandbox, Settings, Slider, Text}; use itertools::izip; type Num = u32; const DECIMAL: u32 = 10; struct State { format: String, digits: Vec<Num>, sliders: Vec<slider::State>, } #[derive(Debug, Clone, Copy)] pub enum Message { SetSlider { index: usize, value: Num }, } impl State { fn from_string(format: String) -> State { let ndigits = format.chars().filter(|c| c.is_digit(DECIMAL)).count(); return State { format, digits: vec![0; ndigits], sliders: vec![slider::State::default(); ndigits], }; } } impl Sandbox for State { type Message = Message; fn new() -> State { State::from_string(String::from("1-111-111-1111")) } fn title(&self) -> String { String::from("Pascal's Pager") } fn update(&mut self, message: Message) { match message { Message::SetSlider { index, value } => { self.digits[index] = value; } } } fn view(&mut self) -> Element<Message> { // We use a column: a simple vertical layout let mut out = Column::new().push( Text::new({ let mut ys = vec![0; self.digits.len()]; let mut pascal = vec![0; self.digits.len()]; pascal[0] = 1; for &coeff in self.digits.iter() { for (y, &p) in ys.iter_mut().zip(pascal.iter()) { *y += coeff * p; *y %= DECIMAL; } for i in (1..pascal.len()).rev() { pascal[i] += pascal[i - 1]; pascal[i] %= DECIMAL; } } let mut s = String::new(); { let mut ys = ys.iter(); for c in self.format.chars() { if c.is_digit(DECIMAL) { s.push(char::from_digit(*ys.next().unwrap(), DECIMAL).unwrap()); } else { s.push(c) } } assert!(ys.next().is_none()); } s }) .size(50) .horizontal_alignment(iced::HorizontalAlignment::Center), // doesn't work ); for (index, &coeff, _state) in izip!(0.., self.digits.iter(), self.sliders.iter_mut()) { out = out.push( Row::new() .push(Text::new(coeff.to_string())) .push(Slider::new( _state, 0..=(DECIMAL - 1), coeff, move |value| Message::SetSlider { index, value }, )), ); } out.into() } } fn main() -> iced::Result { let mut settings = Settings::default(); settings.window.size = (400, 300); State::run(settings) }
mod eddington; mod polar_eddington; mod polar_schwarzschild; mod schwarzschild; pub trait Mass { fn mass() -> f64; } pub use self::eddington::EddingtonFinkelstein; pub use self::polar_eddington::{NearPole0EF, NearPolePiEF}; pub use self::polar_schwarzschild::{NearPole0Schw, NearPolePiSchw}; pub use self::schwarzschild::Schwarzschild;
use std::fs::File; use std::fs::metadata; use std::io::prelude::*; use std::io::BufReader; use crate::parsing::args::*; pub fn parse_file(config: &Config) -> (f64, f64) { if !metadata(&config.file).expect("error: A problem occured with the file").is_file() { panic!("error: The file should be a file, I mean a real one, not a directory, hum... guess you got it"); } let file = File::open(&config.file).expect("error: file not found"); let lines: Vec<_> = BufReader::new(file).lines().collect(); if lines.len() != 2 { panic!("error: Bad file format"); } let content: Vec<&str> = lines[1].as_ref().expect("error: bad file format").split(",").collect(); let m: f64 = content[0].parse::<f64>().expect("error: bad character"); let b: f64 = content[1].parse::<f64>().expect("error: bad character"); return (m, b); }
use proc_macro::TokenStream; use quote::quote; #[proc_macro_derive(U8Enum)] pub fn derive_enum_variant_count(input: TokenStream) -> TokenStream { let syn_item: syn::DeriveInput = syn::parse(input).unwrap(); let len = match syn_item.data { syn::Data::Enum(enum_item) => enum_item.variants.len(), _ => panic!("U8Enum only works on Enums"), }; let enum_name = syn_item.ident; let expanded = quote! { impl #enum_name { pub const COUNT: usize = #len; pub fn as_u8(&self) -> u8 { *self as u8 } pub fn from_u8(byte: u8) -> Option<Self> { if byte as usize >= Self::COUNT { None } else { unsafe { std::mem::transmute(byte) } } } } }; expanded.into() }
// =============================================================================================== // Imports // =============================================================================================== use super::state::*; use memory::*; use spin::{Mutex, RwLock}; // =============================================================================================== // Statics // =============================================================================================== static NEXT_PID: Mutex<u64> = Mutex::new(0); // =============================================================================================== // Task // =============================================================================================== pub struct Task { pub pid: u64, pub context: MemoryContext, pub state: CPUState; } impl Task { pub fn new(entry: u64) -> Task { // Initialize values let context = unsafe { MemoryContext::new(false) }; let state = CPUState::empty_user(); let next_pid = NEXT_PID.lock(entry, context.stack() as u64); let pid = *next_pid; *next_pid += 1; // Return task Task { pid: pid, context: context, state: state, } } }
#![feature(use_extern_macros)] #![feature(custom_attribute)] extern crate erased_serde; extern crate futures; extern crate hyper; #[macro_use] extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; extern crate tokio_core; mod message; mod protocol; mod hubproxy; mod connection; mod hubresult; mod transports; //mod httpbasedtransport; mod httpclient; mod subscription; mod urlbuilder; mod version; mod negotiationresponse; //mod clienttransport; //mod autotransport; //mod serversenteventstransport; //mod longpollingtransport; #[cfg(test)] mod tests { use serde_json; use message; use message::InvocationMessage; use connection::{Connection, HubConnection, HubConnectionBuilder}; use hubproxy::Proxy; use std::mem; use futures::future::Future; use version::Version; use negotiationresponse::NegotiationResponse; use httpclient::{DefaultHttpClient, HttpClient}; use hyper; use urlbuilder::UrlBuilder; //http://localhost:8080/signalr/negotiate?clientProtocol=1.4&connectionData=[%7B%22Name%22:%22MyHub%22%7D] /*{ "Url": "/signalr", "ConnectionToken": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAJKIyAZi0e08Sl079QEAAAAAAACAAAAAAADZgAAwAAAABAAAACS4RdIo2SoYaPSfMgvcGE2AAAAAASAAACgAAAAEAAAAGZvAyT3V82W9ccsIVJY6bYoAAAAaFgu3M01wkQoR6yG5ePZ/jDnrhzhh5fwNaaABi3qD89zE6xEgF+PahQAAACD2D9WSLwmGHvzjdQ+K6je4ZX6KA==", "ConnectionId": "d9eb13e8-aabd-4184-964e-52570ba54663", "KeepAliveTimeout": 20, "DisconnectTimeout": 30, "ConnectionTimeout": 110, "TryWebSockets": false, "ProtocolVersion": "1.4", "TransportConnectTimeout": 5, "LongPollDelay": 0 }*/ //http://localhost:8080/signalr/send?clientProtocol=1.4&transport=serverSentEvents&connectionData=[%7B%22Name%22:%22MyHub%22%7D]&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAJKIyAZXvi0e08Sl079QEAAAAAAACAAAAAAADZgAAwAAAABAAAABKuV%2Bxe15SC20qoS1GIkm0AAAAAASAAACgAAAAEAAAANuqwbda%2FDjBwm7ikQKzgCwoAAAAkgvwaH5thyZv8X9ug41XupjSvsRPTX9XV0Np2QnUA3xpEI6mtigCXRQAAADTkkV58tskB3sVw1IBT%2FoxWDt8IQ%3D%3D #[test] fn test_message_serialization_to_json() { assert_eq!( serde_json::to_string(&message::Message::StreamItem { _type: 0, invocationId: String::from("a"), item: serde_json::json!(1), }).unwrap(), "{\"StreamItem\":{\"_type\":0,\"invocationId\":\"a\",\"item\":1}}" ); } #[test] fn test_connection_create() { let mut connection = HubConnectionBuilder::new(String::from( "http://localhost:8080/signalr", )).use_default_url(false) .finish(); let mut proxy = connection.create_hub_proxy(String::from("MyHub")); //TODO abhi: we can do better (using abstractions?) than calling methods like this: proxy.lock().unwrap().on_1_arg::<String>( String::from("send"), Box::new(|s| println!("The real callback says: {}", s)), ); connection.start().wait(); println!("connection started"); proxy .lock() .unwrap() .invoke( String::from("send"), vec![&String::from("abhi")], &mut connection, ) .wait() .unwrap(); use std::{thread, time}; thread::sleep(time::Duration::from_millis(5000)); } #[test] #[ignore] fn test_http_client_with_proxy() { let mut connection = HubConnectionBuilder::new(String::from( "http://localhost:8080/signalr", )).use_default_url(false) .finish(); let mut proxy = connection.create_hub_proxy(String::from("MyHub")); //proxy.http_client; //let uri = "https://www.rust-lang.org/en-US/".parse().unwrap(); //let work = proxy.http_client.client.get(uri).map(|res|{ // assert_eq!(res.status(),hyper::StatusCode::Ok); // println!("{}",res.status()); //}); //proxy.http_client.core.run(work); //proxy.http_client.create_negotiate_request(); } #[test] fn test_invocation_message_serialize() { let message = InvocationMessage { callback_id: String::from("9"), hub: String::from("MyHub"), method: String::from("send"), args: vec![], }; assert_eq!( serde_json::to_string(&message).unwrap(), "{\"I\":\"9\",\"H\":\"MyHub\",\"M\":\"send\",\"A\":[]}" ); } #[test] fn test_connection_headers_set() { let mut connection = HubConnectionBuilder::new(String::from("http://localhost:8080")) .use_default_url(false) .finish(); connection .headers .insert(String::from("header"), String::from("value")); } #[test] fn test_on_received_handler() { let mut connection = HubConnectionBuilder::new(String::from("http://localhost:8080")).finish(); connection.on_received(Box::new(|s| { assert_eq!(s, String::from("Hello from server")); })); } #[test] fn test_versions() { assert_eq!(Version::new(1, 4), Version::new(1, 4)); assert_ne!(Version::new(1, 4), Version::new(1, 3)); assert!(Version::new(1, 4) < Version::new(1, 5)); assert!(Version::new(1, 4) < Version::new(2, 5)); assert!(Version::new(1, 4) > Version::new(1, 3)); assert!(Version::new(1, 4) >= Version::new(1, 3)); } #[test] fn test_deserialize_negotiationresponse() { let j = "{ \"Url\": \"/signalr\", \"ConnectionToken\": \"AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAJKIyAZi0e08Sl079QEAAAAAAACAAAAAAADZgAAwAAAABAAAACS4RdIo2SoYaPSfMgvcGE2AAAAAASAAACgAAAAEAAAAGZvAyT3V82W9ccsIVJY6bYoAAAAaFgu3M01wkQoR6yG5ePZ/jDnrhzhh5fwNaaABi3qD89zE6xEgF+PahQAAACD2D9WSLwmGHvzjdQ+K6je4ZX6KA==\", \"ConnectionId\": \"d9eb13e8-aabd-4184-964e-52570ba54663\", \"KeepAliveTimeout\": 20, \"DisconnectTimeout\": 30, \"ConnectionTimeout\": 110, \"TryWebSockets\": false, \"ProtocolVersion\": \"1.4\", \"TransportConnectTimeout\": 5, \"LongPollDelay\": 0 }"; let n: NegotiationResponse = serde_json::from_str(j).unwrap(); assert_eq!(n.url, "/signalr"); } #[test] #[ignore] fn test_httpclient_get() { let mut http_client = DefaultHttpClient::new(); let uri = "http://localhost:8080/signalr/negotiate?clientProtocol=1.4&connectionData=[%7B%22Name%22:%22MyHub%22%7D]"; //println!("response : {}", http_client.get(uri)); } #[test] fn test_url_building() { assert_eq!( UrlBuilder::create_base_url( "http://localhost:8080", "negotiate", None, "abc", None, "4.3" ), String::from("http://localhost:8080/negotiate?clientProtocol=4.3&connectionData=abc") ); assert_eq!( UrlBuilder::create_base_url( "http://localhost:8080/", "negotiate", None, "abc", None, "4.3" ), String::from("http://localhost:8080/negotiate?clientProtocol=4.3&connectionData=abc") ); } use std::sync::mpsc::channel; #[test] #[ignore] fn test_sse_streaming() { let mut http_client = DefaultHttpClient::new(); let uri = "http://localhost:8080/signalr/connect?transport=serverSentEvents&clientProtocol=1.4&connectionData=[%7B%22Name%22:%22MyHub%22%7D]&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAJKIyAZXvi0e08Sl079QEAAAAAAACAAAAAAADZgAAwAAAABAAAACgHkzpuWmAtmAY8Rk2IRN7AAAAAASAAACgAAAAEAAAAPKUdM7j1ibT4s7FawppDCkoAAAAhcjKQMlrKgX%2F0%2FPBTXVTJAWzrY9xquk68WAQt04n9WrjHhgIhWUCzhQAAAD%2FR0E9HsraHZ6WTvaY7ktcm8stGQ%3D%3D"; let (tx, rx) = channel(); http_client.get_stream( uri, Some(vec![ ("Accept", "text/event-stream"), ("User-Agent", "genmei"), ]), tx, ); loop { println!("recv chunk {:?}", rx.recv().unwrap()); } } #[test] fn test_send_url_create() { assert_eq!(UrlBuilder::create_send_url("http://localhost:8080", Some("serverSentEvents"), "abc", Some("xyz"), "1.4"), String::from("http://localhost:8080/send?clientProtocol=1.4&transport=serverSentEvents&connectionData=abc&connectionToken=xyz")); } #[test] fn test_post_request() { let mut connection = HubConnectionBuilder::new(String::from( "http://localhost:8080/signalr", )).use_default_url(false) .finish(); let mut proxy = connection.create_hub_proxy(String::from("MyHub")); //TODO abhi: we can do better (using abstractions?) than calling methods like this: proxy.lock().unwrap().on_1_arg::<String>( String::from("send"), Box::new(|s| println!("The real callback says: {}", s)), ); proxy.lock().unwrap().invoke( String::from("send"), vec![&String::from("abhi"), &1], &mut connection, ); } }
use std::cell::RefCell; use std::path::Path; use std::rc::Rc; use storage::StorageBuilderFn; use svm_layout::Layout; use svm_storage::account::{AccountKVStore, AccountStorage}; use svm_storage::kv::StatefulKV; use svm_types::{AccountAddr, State}; use crate::{env, storage}; use crate::{Config, DefaultRuntime, Env}; use env::{DefaultRocksAccountStore, DefaultRocksEnvTypes, DefaultRocksTemplateStore}; /// Creates a new `Runtime` backed by `rocksdb` for persistence. pub fn create_rocksdb_runtime<P>( state_kv: &Rc<RefCell<dyn StatefulKV>>, kv_path: &P, ) -> DefaultRuntime<DefaultRocksEnvTypes> where P: AsRef<Path>, { todo!() // let env = build_env(&kv_path); // DefaultRuntime::new(env, kv_path, storage_builder(state_kv)) } fn build_env<P>(kv_path: &P) -> Env<DefaultRocksEnvTypes> where P: AsRef<Path>, { let account_store = DefaultRocksAccountStore::new(kv_path); let template_store = DefaultRocksTemplateStore::new(kv_path); Env::new(account_store, template_store) } pub fn storage_builder(state_kv: &Rc<RefCell<dyn StatefulKV>>) -> Box<StorageBuilderFn> { let state_kv = Rc::clone(state_kv); let func = move |addr: &AccountAddr, _state: &State, layout: &Layout, _config: &Config| { // The current pointed-to `State` is managed externally, so we ignore here the `state` parameter. // // Similarly, we ignore the `config` parameter since it only contains the `Path` of the key-value store // used for managing the Account's storage. We talk with the external key-value store via FFI interface. let addr = addr.inner(); let account_kv = AccountKVStore::new(addr.clone(), &state_kv); AccountStorage::new(layout.clone(), account_kv) }; Box::new(func) }
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use super::{collateral_penalty_for_deal_activation_missed, DealProposal, DealState}; use crate::{BalanceTable, DealID, OptionalEpoch, SetMultimap}; use address::Address; use cid::Cid; use clock::ChainEpoch; use encoding::Cbor; use ipld_amt::Amt; use ipld_blockstore::BlockStore; use num_traits::Zero; use runtime::Runtime; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use vm::{ActorError, ExitCode, TokenAmount}; /// Market actor state #[derive(Default)] pub struct State { /// Amt<DealID, DealProposal> pub proposals: Cid, /// Amt<DealID, DealState> pub states: Cid, /// Total amount held in escrow, indexed by actor address (including both locked and unlocked amounts). pub escrow_table: Cid, /// Amount locked, indexed by actor address. /// Note: the amounts in this table do not affect the overall amount in escrow: /// only the _portion_ of the total escrow amount that is locked. pub locked_table: Cid, /// Deal id state sequential incrementer pub next_id: DealID, /// Metadata cached for efficient iteration over deals. /// SetMultimap<Address> pub deal_ids_by_party: Cid, } impl State { pub fn new(empty_arr: Cid, empty_map: Cid, empty_mset: Cid) -> Self { Self { proposals: empty_arr.clone(), states: empty_arr, escrow_table: empty_map.clone(), locked_table: empty_map, next_id: 0, deal_ids_by_party: empty_mset, } } //////////////////////////////////////////////////////////////////////////////// // Balance table operations //////////////////////////////////////////////////////////////////////////////// pub fn add_escrow_balance<BS: BlockStore>( &mut self, store: &BS, a: &Address, amount: TokenAmount, ) -> Result<(), String> { let mut bt = BalanceTable::from_root(store, &self.escrow_table)?; bt.add_create(a, amount)?; self.escrow_table = bt.root()?; Ok(()) } pub fn add_locked_balance<BS: BlockStore>( &mut self, store: &BS, a: &Address, amount: TokenAmount, ) -> Result<(), String> { let mut bt = BalanceTable::from_root(store, &self.locked_table)?; bt.add_create(a, amount)?; self.locked_table = bt.root()?; Ok(()) } pub fn get_escrow_balance<BS: BlockStore>( &self, store: &BS, a: &Address, ) -> Result<TokenAmount, ActorError> { let bt = BalanceTable::from_root(store, &self.escrow_table).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("get escrow balance {}", e), ) })?; bt.get(a).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("get escrow balance {}", e), ) }) } pub fn get_locked_balance<BS: BlockStore>( &self, store: &BS, a: &Address, ) -> Result<TokenAmount, ActorError> { let bt = BalanceTable::from_root(store, &self.locked_table).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("get locked balance {}", e), ) })?; bt.get(a).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("get locked balance {}", e), ) }) } pub(super) fn maybe_lock_balance<BS: BlockStore>( &mut self, store: &BS, addr: &Address, amount: &TokenAmount, ) -> Result<(), ActorError> { let prev_locked = self.get_locked_balance(store, addr)?; let escrow_balance = self.get_locked_balance(store, addr)?; if &prev_locked + amount > escrow_balance { return Err(ActorError::new( ExitCode::ErrInsufficientFunds, format!( "not enough balance to lock for addr {}: {} < {} + {}", addr, escrow_balance, prev_locked, amount ), )); } let mut bt = BalanceTable::from_root(store, &self.locked_table) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; bt.add(addr, amount).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("adding locked balance {}", e), ) })?; self.locked_table = bt .root() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(()) } pub(super) fn unlock_balance<BS: BlockStore>( &mut self, store: &BS, addr: &Address, amount: &TokenAmount, ) -> Result<(), ActorError> { let mut bt = BalanceTable::from_root(store, &self.locked_table) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; bt.must_subtract(addr, amount).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("subtracting from locked balance: {}", e), ) })?; self.locked_table = bt .root() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(()) } pub(super) fn transfer_balance<BS: BlockStore>( &mut self, store: &BS, from_addr: &Address, to_addr: &Address, amount: &TokenAmount, ) -> Result<(), ActorError> { let mut et = BalanceTable::from_root(store, &self.escrow_table) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; let mut lt = BalanceTable::from_root(store, &self.locked_table) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; // Subtract from locked and escrow tables et.must_subtract(from_addr, &amount).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("subtract from escrow: {}", e), ) })?; lt.must_subtract(from_addr, &amount).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("subtract from escrow: {}", e), ) })?; // Add subtracted amount to the recipient et.add(to_addr, &amount).map_err(|e| { ActorError::new(ExitCode::ErrIllegalState, format!("add to escrow: {}", e)) })?; // Update locked and escrow roots self.locked_table = lt .root() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; self.escrow_table = et .root() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(()) } pub(super) fn slash_balance<BS: BlockStore>( &mut self, store: &BS, addr: &Address, amount: &TokenAmount, ) -> Result<(), ActorError> { let mut et = BalanceTable::from_root(store, &self.escrow_table) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; let mut lt = BalanceTable::from_root(store, &self.locked_table) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; // Subtract from locked and escrow tables et.must_subtract(addr, &amount).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("subtract from escrow: {}", e), ) })?; lt.must_subtract(addr, &amount).map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("subtract from escrow: {}", e), ) })?; // Update locked and escrow roots self.locked_table = lt .root() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; self.escrow_table = et .root() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(()) } //////////////////////////////////////////////////////////////////////////////// // Deal state operations //////////////////////////////////////////////////////////////////////////////// pub(super) fn update_pending_deal_states_for_party<BS, RT>( &mut self, rt: &RT, addr: &Address, ) -> Result<TokenAmount, ActorError> where BS: BlockStore, RT: Runtime<BS>, { // TODO check if rt curr_epoch can be 0 let epoch = rt.curr_epoch() - 1; let dbp = SetMultimap::from_root(rt.store(), &self.deal_ids_by_party) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; let mut extracted_ids = Vec::new(); dbp.for_each(addr, |id| { extracted_ids.push(id); Ok(()) }) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e))?; self.update_pending_deal_states(rt.store(), extracted_ids, epoch) } pub(super) fn update_pending_deal_states<BS>( &mut self, store: &BS, deal_ids: Vec<DealID>, epoch: ChainEpoch, ) -> Result<TokenAmount, ActorError> where BS: BlockStore, { let mut amount_slashed_total = TokenAmount::zero(); for deal in deal_ids { amount_slashed_total += self.update_pending_deal_state(store, deal, epoch)?; } Ok(amount_slashed_total) } pub(super) fn update_pending_deal_state<BS>( &mut self, store: &BS, deal_id: DealID, epoch: ChainEpoch, ) -> Result<TokenAmount, ActorError> where BS: BlockStore, { let deal = self.must_get_deal(store, deal_id)?; let mut state = self.must_get_deal_state(store, deal_id)?; let ever_updated = state.last_updated_epoch.is_some(); let ever_slashed = state.slash_epoch.is_some(); if ever_updated && state.last_updated_epoch.unwrap() > epoch { return Err(ActorError::new( ExitCode::ErrIllegalState, "Deal was updated in the future".to_owned(), )); } if state.sector_start_epoch.is_none() { if epoch > deal.start_epoch { return self.process_deal_init_timed_out(store, deal_id, deal, state); } return Ok(TokenAmount::zero()); } assert!( deal.start_epoch <= epoch, "Deal start cannot exceed current epoch" ); let deal_end = if ever_slashed { assert!( state.slash_epoch.unwrap() <= deal.end_epoch, "Epoch slashed must be less or equal to the end epoch" ); state.slash_epoch.unwrap() } else { deal.end_epoch }; let elapsed_start = if ever_updated && state.last_updated_epoch.unwrap() > deal.start_epoch { state.last_updated_epoch.unwrap() } else { deal.start_epoch }; let elapsed_end = if epoch < deal_end { epoch } else { deal_end }; let num_epochs_elapsed = elapsed_end - elapsed_start; self.transfer_balance( store, &deal.client, &deal.provider, &(deal.storage_price_per_epoch.clone() * num_epochs_elapsed), )?; if ever_slashed { let payment_remaining = deal_get_payment_remaining(&deal, state.slash_epoch.unwrap()); self.unlock_balance( store, &deal.client, &(payment_remaining + &deal.client_collateral), )?; let slashed = deal.provider_collateral.clone(); self.slash_balance(store, &deal.provider, &slashed)?; self.delete_deal(store, deal_id, deal)?; return Ok(slashed); } if epoch >= deal.end_epoch { self.process_deal_expired(store, deal_id, deal, state)?; return Ok(TokenAmount::zero()); } state.last_updated_epoch = OptionalEpoch(Some(epoch)); // Update states array let mut states = Amt::<DealState, _>::load(&self.states, store) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; states .set(deal_id, state) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; self.states = states .flush() .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(TokenAmount::zero()) } pub(super) fn delete_deal<BS>( &mut self, store: &BS, deal_id: DealID, deal: DealProposal, ) -> Result<(), ActorError> where BS: BlockStore, { // let deal = self.must_get_deal(store, deal_id)?; let mut proposals = Amt::<DealState, _>::load(&self.proposals, store) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; proposals .delete(deal_id) .map_err(|e| ActorError::new(ExitCode::ErrPlaceholder, e.into()))?; let mut dbp = SetMultimap::from_root(store, &self.deal_ids_by_party) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; dbp.remove(&deal.client, deal_id) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e))?; // Update roots of update self.proposals = proposals .flush() .map_err(|e| ActorError::new(ExitCode::ErrPlaceholder, e.into()))?; self.deal_ids_by_party = dbp .root() .map_err(|e| ActorError::new(ExitCode::ErrPlaceholder, e.into()))?; Ok(()) } pub(super) fn process_deal_init_timed_out<BS>( &mut self, store: &BS, deal_id: DealID, deal: DealProposal, state: DealState, ) -> Result<TokenAmount, ActorError> where BS: BlockStore, { assert!( state.sector_start_epoch.is_none(), "Sector start epoch must be undefined" ); self.unlock_balance(store, &deal.client, &deal.client_balance_requirement())?; let amount_slashed = collateral_penalty_for_deal_activation_missed(deal.provider_collateral.clone()); let amount_remainging = deal.provider_balance_requirement() - &amount_slashed; self.slash_balance(store, &deal.provider, &amount_slashed)?; self.unlock_balance(store, &deal.provider, &amount_remainging)?; self.delete_deal(store, deal_id, deal)?; Ok(amount_slashed) } pub(super) fn process_deal_expired<BS>( &mut self, store: &BS, deal_id: DealID, deal: DealProposal, state: DealState, ) -> Result<(), ActorError> where BS: BlockStore, { assert!( state.sector_start_epoch.is_some(), "Sector start epoch must be initialized at this point" ); self.unlock_balance(store, &deal.provider, &deal.provider_collateral)?; self.unlock_balance(store, &deal.client, &deal.client_collateral)?; self.delete_deal(store, deal_id, deal) } #[allow(dead_code)] pub(super) fn generate_storage_deal_id(&mut self) -> DealID { let ret = self.next_id; self.next_id += 1; ret } //////////////////////////////////////////////////////////////////////////////// // Method utility functions //////////////////////////////////////////////////////////////////////////////// pub(super) fn must_get_deal<BS: BlockStore>( &self, store: &BS, deal_id: DealID, ) -> Result<DealProposal, ActorError> { let proposals = Amt::load(&self.proposals, store) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(proposals .get(deal_id) .map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("get proposal for id {}: {}", deal_id, e), ) })? .ok_or_else(|| { ActorError::new( ExitCode::ErrIllegalState, format!("proposal not found for id {}", deal_id), ) })?) } pub(super) fn must_get_deal_state<BS: BlockStore>( &self, store: &BS, deal_id: DealID, ) -> Result<DealState, ActorError> { let states = Amt::load(&self.states, store) .map_err(|e| ActorError::new(ExitCode::ErrIllegalState, e.into()))?; Ok(states .get(deal_id) .map_err(|e| { ActorError::new( ExitCode::ErrIllegalState, format!("get deal state for id {}: {}", deal_id, e), ) })? .ok_or_else(|| { ActorError::new( ExitCode::ErrIllegalState, format!("deal state not found for id {}", deal_id), ) })?) } pub(super) fn lock_balance_or_abort<BS: BlockStore>( &mut self, store: &BS, addr: &Address, amount: &TokenAmount, ) -> Result<(), ActorError> { if amount < &TokenAmount::zero() { return Err(ActorError::new( ExitCode::ErrIllegalArgument, format!("negative amount {}", amount), )); } self.maybe_lock_balance(store, addr, amount) } } fn deal_get_payment_remaining(deal: &DealProposal, epoch: ChainEpoch) -> TokenAmount { assert!( epoch <= deal.end_epoch, "Current epoch must be before the end epoch of the deal" ); let duration_remaining = deal.end_epoch - (epoch - 1); deal.storage_price_per_epoch.clone() * duration_remaining } impl Cbor for State {} impl Serialize for State { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { ( &self.proposals, &self.states, &self.escrow_table, &self.locked_table, &self.next_id, &self.deal_ids_by_party, ) .serialize(serializer) } } impl<'de> Deserialize<'de> for State { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (proposals, states, escrow_table, locked_table, next_id, deal_ids_by_party) = Deserialize::deserialize(deserializer)?; Ok(Self { proposals, states, escrow_table, locked_table, next_id, deal_ids_by_party, }) } }
use actix::prelude::*; use futures::future::*; use crate::opentracing::Span; impl Handler<super::ingestor::IngestEvents<Span>> for super::ingestor::Ingestor { type Result = (); fn handle( &mut self, msg: super::ingestor::IngestEvents<Span>, _ctx: &mut Context<Self>, ) -> Self::Result { for event in &msg.events { let event = event.clone(); Arbiter::spawn(crate::DB_EXECUTOR_POOL.send(event.clone()).then(|span| { if let Ok(span) = span { if let (Some(_), None) = (span.duration, span.parent_id.clone()) { actix::System::current() .registry() .get::<super::test_result::TraceParser>() .do_send(super::test_result::TraceDone(span.trace_id.clone())); } } result(Ok(())) })); } } } #[cfg(test)] mod tests { extern crate serde_json; use std; #[test] fn can_deserialize_zipkin_query() { let zipkin_query = r#"[ { "traceId": "string", "name": "string", "parentId": "string", "id": "string", "kind": "CLIENT", "timestamp": 0, "duration": 0, "debug": true, "shared": true, "localEndpoint": { "serviceName": "string", "ipv4": "string", "ipv6": "string", "port": 0 }, "remoteEndpoint": { "serviceName": "string", "ipv4": "string", "ipv6": "string", "port": 0 }, "annotations": [ { "timestamp": 0, "value": "string" } ], "tags": { "additionalProp1": "string", "additionalProp2": "string", "additionalProp3": "string" } } ]"#; let span: std::result::Result<Vec<super::Span>, _> = serde_json::from_str(zipkin_query); assert!(span.is_ok()); } }
use artell_domain::scheduler::SchedulerRepository; #[derive(Error, Debug)] pub enum Error { #[error(transparent)] Others(#[from] anyhow::Error), } pub async fn system_update_scheduler( scheduler_repo: impl SchedulerRepository, ) -> Result<(), Error> { if let Some(mut scheduler) = scheduler_repo.find().await? { if scheduler.check_update() { scheduler_repo.save(scheduler).await?; } } Ok(()) }
use crate::models::report::Report; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Veiculo { pub id: String, // Placa pub chasis: String, pub km_atual: i64, pub relatorios: Vec<Report>, } impl Veiculo { pub fn verificar(&mut self) -> Result<(()), String> { self.relatorios .sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap()); let mut prev_timestamp: i64 = 0; let mut prev_km: i64 = 0; for r in self.relatorios.iter_mut() { let ts = r.timestamp.parse::<i64>(); match ts { Ok(t) => { if t < prev_timestamp { return Err("Erro na validação das timestamps do veiculo".to_string()); } else { if r.km < prev_km { return Err("Erro na validação da quilometragem do veículo".to_string()); } else { prev_timestamp = r.timestamp.parse::<i64>().unwrap(); prev_km = r.km.clone(); self.km_atual = prev_km.clone(); } } } Err(_) => return Err("Erro na análise da timestamp fornecida".to_string()), } } Ok(()) } }
// When will I Retire? use std::io::{stdin,stdout,Write}; fn main() { const CURRENT_YEAR: i32 = 2020; println!("What is your age? "); let mut age_str = String::new(); let _ = stdout().flush(); stdin() .read_line(&mut age_str) .expect("error: could not read stdin"); age_str = age_str.trim().to_string(); let age = age_str.parse::<i32>().unwrap(); println!("At what age would you like to retire? "); let mut retire_str = String::new(); let _ = stdout().flush(); stdin() .read_line(&mut retire_str) .expect("error: could not read stdin"); retire_str = retire_str.trim().to_string(); let retire_age = retire_str.parse::<i32>().unwrap(); let years_left = retire_age - age; println!("It's {}. You will retire in {}.", CURRENT_YEAR, CURRENT_YEAR + years_left); println!("You only have {} years of work to go!", years_left); }
use totsu::prelude::*; use totsu::operator::MatBuild; use totsu::logger::PrintLogger; use totsu::problem::ProbQP; use rand::prelude::*; use rand_xoshiro::rand_core::SeedableRng; use rand_xoshiro::Xoshiro256StarStar; type LA = FloatGeneric<f64>; type AMatBuild = MatBuild<LA, f64>; type AProbQP = ProbQP<LA, f64>; type ASolver = Solver<LA, f64>; /// main fn main() -> std::io::Result<()> { //----- make sample points for training let mut rng = Xoshiro256StarStar::seed_from_u64(0); let l = 50; // # of dimension let x = AMatBuild::new(MatType::General(l, 1)) .by_fn(|_, _| rng.gen_range(-1. ..= 1.)); // random l-dimensional vector //println!("{}", x); let mut y = vec![AMatBuild::new(MatType::General(l, 1)); l]; for yi in y.iter_mut() { yi.set_by_fn(|_, _| rng.gen_range(-1. ..= 1.)); // random l-dimensional vector //println!("{}", yi); } //----- formulate least square as QP let n = l; let m = 0; let p = 0; let sym_p = AMatBuild::new(MatType::SymPack(n)) .by_fn(|r, c| { let mut sum = 0.; for (yr, yc) in y[r].as_ref().iter().zip(y[c].as_ref()) { sum += yr * yc; } sum }); //println!("{}", sym_p); let mut vec_q = x.clone(); sym_p.op(-1., x.as_ref(), 0., vec_q.as_mut()); //println!("{}", vec_q); let mat_g = AMatBuild::new(MatType::General(m, n)); //println!("{}", mat_g); let vec_h = AMatBuild::new(MatType::General(m, 1)); //println!("{}", vec_h); let mat_a = AMatBuild::new(MatType::General(p, n)); //println!("{}", mat_a); let vec_b = AMatBuild::new(MatType::General(p, 1)); //println!("{}", vec_b); //----- solve QP let s = ASolver::new().par(|p| { p.log_period = Some(10000); }); let mut qp = AProbQP::new(sym_p, vec_q, mat_g, vec_h, mat_a, vec_b, s.par.eps_zero); let rslt = s.solve(qp.problem(), PrintLogger).unwrap(); //println!("{:?}", rslt.0); let mut max_absdiff = 0_f64; for i in 0.. l { let absdiff = (x[(i, 0)] - rslt.0[i]).abs(); max_absdiff = max_absdiff.max(absdiff); } println!("max_absdiff {:.3e}", max_absdiff); //println!("{:?}", x); Ok(()) }
use cssparser::{ToCss, RGBA}; use std::fmt; pub struct Hex<'a> { rgba: &'a RGBA, } impl<'a> From<&'a RGBA> for Hex<'a> { fn from(rgba: &'a RGBA) -> Self { Hex { rgba } } } impl<'a> ToCss for Hex<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { let &RGBA { red, green, blue, .. } = self.rgba; // #rrggbb can also be converted to #rgb let three_digit = red % 17 == 0 && green % 17 == 0 && blue % 17 == 0; if three_digit { write!(dest, "#{:X}{:X}{:X}", red / 17, green / 17, blue / 17) } else { write!(dest, "#{:<02X}{:<02X}{:<02X}", red, green, blue) } } } #[cfg(test)] mod tests { use super::*; #[test] fn to_css_format() { let data = vec![ (RGBA::new(0, 0, 0, 0), "#000"), (RGBA::new(17, 34, 51, 0), "#123"), (RGBA::new(255, 255, 255, 0), "#FFF"), (RGBA::new(1, 100, 255, 0), "#0164FF"), ]; for (rgba, expect) in data { let hex = Hex::from(&rgba); assert_eq!(hex.to_css_string(), expect); } } }
use std::fmt; use std::iter::Cloned; use std::mem; use std::ops::Index; use std::ops::IndexMut; use std::ops::Range; use std::ops::RangeFrom; use std::ops::RangeTo; use std::slice; use crate::data::*; pub type LineSize = u16; #[ derive (Eq, PartialEq) ] #[ repr (transparent) ] pub struct Line { cells: [Cell], } impl Line { pub fn new (cells: & [Cell]) -> & Line { unsafe { mem::transmute (cells) } } pub fn new_mut (cells: & mut [Cell]) -> & mut Line { unsafe { mem::transmute (cells) } } pub fn cells (& self) -> & [Cell] { & self.cells } pub fn len (& self) -> LineSize { self.cells.len () as LineSize } pub fn is_solved (& self) -> bool { ! self.iter ().any (Cell::is_unknown) } pub fn iter (& self) -> Cloned <slice::Iter <'_, Cell>> { self.cells.iter ().cloned () } pub fn iter_mut (& mut self) -> slice::IterMut <'_, Cell> { self.cells.iter_mut () } } impl <'a> Default for & 'a Line { fn default () -> & 'a Line { Line::new (Default::default ()) } } impl ToOwned for Line { type Owned = LineBuf; fn to_owned (& self) -> LineBuf { LineBuf::from (self.cells.to_owned ()) } } impl Index <LineSize> for Line { type Output = Cell; fn index (& self, index: LineSize) -> & Cell { & self.cells [index as usize] } } impl Index <Range <LineSize>> for Line { type Output = Line; fn index (& self, range: Range <LineSize>) -> & Line { & Line::new (& self.cells [ Range { start: range.start as usize, end: range.end as usize, } ]) } } impl Index <RangeFrom <LineSize>> for Line { type Output = Line; fn index (& self, range: RangeFrom <LineSize>) -> & Line { & Line::new (& self.cells [ RangeFrom { start: range.start as usize, } ]) } } impl Index <RangeTo <LineSize>> for Line { type Output = Line; fn index (& self, range: RangeTo <LineSize>) -> & Line { & Line::new (& self.cells [ RangeTo { end: range.end as usize, } ]) } } impl IndexMut <LineSize> for Line { fn index_mut <'a> (& 'a mut self, index: LineSize) -> & 'a mut Cell { & mut self.cells [index as usize] } } impl IndexMut <Range <LineSize>> for Line { fn index_mut <'a> (& 'a mut self, range: Range <LineSize>) -> & 'a mut Line { Line::new_mut (& mut self.cells [ Range { start: range.start as usize, end: range.end as usize, } ]) } } impl fmt::Debug for Line { fn fmt (& self, formatter: & mut fmt::Formatter <'_>) -> fmt::Result { write! ( formatter, "[{}]", self.cells.iter ().map ( |& cell| match cell { Cell::UNKNOWN => "-", Cell::EMPTY => " ", Cell::FILLED => "#", Cell::ERROR => "!", _ => "?", } ).collect::<String> (), ) ?; Ok (()) } } #[ cfg (test) ] mod tests { use super::*; #[ test ] fn test_line_debug () { assert_eq! ( format! ( "{:?}", Line::new (& vec! [ Cell::UNKNOWN, Cell::EMPTY, Cell::FILLED, Cell::ERROR, ]), ), "[- #!]", ); } }
use crate::address::{PAddr, VAddr}; use core::ptr; use kerla_utils::once::Once; use x86::io::outb; #[repr(u8)] #[derive(Copy, Clone)] #[allow(unused)] enum VgaColor { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Purple = 5, Brown = 6, Gray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPurple = 13, Yellow = 14, White = 15, } const COLUMNS: usize = 80; const ROWS: usize = 25; // Encoded in https://en.wikipedia.org/wiki/Code_page_437 const BANNER: &str = " Kerla /dev/console is connected to the serial port (no keyboard support) "; struct Console { base: VAddr, x: usize, y: usize, fg: VgaColor, bg: VgaColor, } impl Console { pub const fn new() -> Console { Console { base: PAddr::new(0xb8000).as_vaddr(), x: 0, y: 0, fg: VgaColor::White, bg: VgaColor::Black, } } pub fn clear_screen(&mut self) { self.x = 0; self.y = 0; for y in 0..ROWS { for x in 0..COLUMNS { self.draw_char(x, y, ' ', VgaColor::White, VgaColor::Black); } } self.move_cursor(0, 0); self.draw_banner(); } fn move_cursor(&self, x: usize, y: usize) { unsafe { let pos = y * COLUMNS + x; outb(0x3d4, 0x0f); outb(0x3d5, (pos & 0xff) as u8); outb(0x3d4, 0x0e); outb(0x3d5, ((pos >> 8) & 0xff) as u8); } } unsafe fn mut_ptr_at(&self, x: usize, y: usize) -> *mut u16 { #[allow(clippy::ptr_offset_with_cast)] self.base .as_mut_ptr::<u16>() .offset((x + y * COLUMNS) as isize) } fn draw_char(&mut self, x: usize, y: usize, ch: char, fg: VgaColor, bg: VgaColor) { unsafe { self.mut_ptr_at(x, y) .write((((bg as u16) << 12) | (fg as u16) << 8) | (ch as u16)); } } fn scroll(&mut self) { let diff = self.y - ROWS + 1; for from in diff..ROWS { unsafe { ptr::copy_nonoverlapping( self.mut_ptr_at(0, from), self.mut_ptr_at(0, from - diff), COLUMNS, ); } } // Clear the new lines. unsafe { ptr::write_bytes(self.mut_ptr_at(0, ROWS - diff), 0, COLUMNS); } self.y = ROWS - 1; self.draw_banner(); } fn draw_banner(&mut self) { for (x, ch) in BANNER.chars().enumerate() { self.draw_char(x, 0, ch, VgaColor::Black, VgaColor::LightGreen); } } } impl vte::Perform for Console { fn execute(&mut self, byte: u8) { match byte { b'\r' => { self.x = 0; } b'\n' => { self.y += 1; self.x = 0; } _ => {} } if self.y >= ROWS { self.scroll(); } self.move_cursor(self.x, self.y); } fn print(&mut self, c: char) { if self.x == COLUMNS { self.y += 1; self.x = 0; } if self.y > ROWS { self.scroll(); } self.draw_char(self.x, self.y, c, self.fg, self.bg); self.x += 1; self.move_cursor(self.x, self.y); } } static TERMINAL_PARSER: Once<spin::Mutex<vte::Parser>> = Once::new(); static CONSOLE: spin::Mutex<Console> = spin::Mutex::new(Console::new()); pub fn printchar(ch: u8) { TERMINAL_PARSER.lock().advance(&mut *CONSOLE.lock(), ch); } pub fn init() { TERMINAL_PARSER.init(|| spin::Mutex::new(vte::Parser::new())); CONSOLE.lock().clear_screen(); }
// Copyright 2018-2020, Wayfair GmbH // // 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 flate2::read::GzDecoder; use regex::Regex; use std::borrow::Borrow; // used instead of halfbrown::Hashmap because bincode can't deserialize that use async_std::task; use std::collections::HashMap; use std::env; use std::ffi::OsStr; use std::fs::{self, File}; use std::io::{BufReader, BufWriter, Read}; use std::path::{Path, PathBuf}; use std::process::{self, Command}; use tar::Archive; use walkdir::WalkDir; use tremor_script::ast::FnDoc; // TODO get rid of this once we can switch to FnDoc for aggregate functions too use tremor_script::docs::{FunctionDoc, FunctionSignatureDoc}; use tremor_script::path::ModulePath; use tremor_script::{registry, Script}; const LANGUAGES: &[&str] = &["tremor-script", "tremor-query"]; const TREMOR_SCRIPT_CRATE_NAME: &str = "tremor-script"; const BASE_DOCS_DIR: &str = "tremor-www-docs"; /* fn get_test_function_doc(language_name: &str) -> (String, FunctionDoc) { let test_func = match language_name { "tremor-script" => "random::bool".to_string(), "tremor-query" => "stats::min".to_string(), _ => unreachable!(), }; let test_doc = match language_name { "tremor-script" => FunctionDoc { signature: "random::bool() -> bool".to_string(), description: "Generates a random boolean.".to_string(), summary: None, examples: Some("```random::bool() # either true or false```".to_string()), }, "tremor-query" => FunctionDoc { signature: "stats::min(int|float) -> int|float".to_string(), description: "Determines the smallest event value in the current windowed operation." .to_string(), summary: None, examples: Some("```trickle\nstats::min(event.value)\n```".to_string()), }, _ => unreachable!(), }; (test_func, test_doc) } */ fn get_tremor_script_crate_path(download_dir: &str) -> String { // allows us to infer this from an environment variable, so that we can override // this easily during local dev testing if let Ok(env_path) = env::var("TRILL_TREMOR_SCRIPT_SRC_PATH") { println!( "Detected environment variable TRILL_TREMOR_SCRIPT_SRC_PATH for tremor script crate path: {}", env_path ); return env_path; } let tremor_script_version = &get_cargo_lock_version_for_crate(TREMOR_SCRIPT_CRATE_NAME) .expect("Failed to get tremor-script version from cargo lock file"); println!( "Detected tremor-script version from cargo lock file: {}", tremor_script_version ); match get_local_cargo_registry_path_for_crate(TREMOR_SCRIPT_CRATE_NAME, tremor_script_version) .unwrap() { Some(path) => path, None => { println!("Could not find tremor-script src in local cargo registry, so downloading it now..."); task::block_on(download_and_extract_crate( TREMOR_SCRIPT_CRATE_NAME, tremor_script_version, download_dir, )) .unwrap() } } } fn parse_tremor_stdlib(tremor_script_source_dir: &str) -> HashMap<String, FunctionDoc> { let mut function_docs: HashMap<String, FunctionDoc> = HashMap::new(); for entry in WalkDir::new(format!("{}/lib", tremor_script_source_dir)) { let entry = entry.unwrap(); let path = entry.path(); if path.is_file() { println!("Parsing tremor file: {}", path.display()); let module_file = File::open(Path::new(&path)).unwrap(); let mut buffered_reader = BufReader::new(module_file); let mut module_text = String::new(); buffered_reader.read_to_string(&mut module_text).unwrap(); let module_path = ModulePath::load(); let registry = registry::registry(); match Script::parse( &module_path, &path.display().to_string(), module_text, &registry, ) { Ok(script) => { let docs = script.docs(); // module name here is "self" always so can't use it right now // TODO fix this? //if let Some(module_doc) = &docs.module { // println!("Found module: {}", module_doc.name); //} // filenames match module name here let module_name = path.file_stem().unwrap().to_string_lossy(); println!("Found module: {}", module_name); for fndoc in &docs.fns { let function_doc = fndoc_to_function_doc(fndoc, &module_name); println!("Found function: {}", function_doc.signature); function_docs .insert(function_doc.signature.full_name.clone(), function_doc); } } Err(e) => eprintln!("Error parsing file {}: {:?}", path.display(), e), } } } function_docs } fn fndoc_to_function_doc(fndoc: &FnDoc, module_name: &str) -> FunctionDoc { let signature_doc = FunctionSignatureDoc { full_name: format!("{}::{}", module_name, fndoc.name), args: fndoc.args.iter().map(|s| s.to_string()).collect(), result: String::new(), // TODO adopt comment convention to represent result type }; FunctionDoc { signature: signature_doc, description: fndoc.doc.as_ref().unwrap_or(&String::new()).to_string(), summary: None, // TODO add first line? examples: None, // TODO parse out stuff in code blocks } } fn parse_raw_function_docs(language_docs_dir: &str) -> HashMap<String, FunctionDoc> { let mut function_docs: HashMap<String, FunctionDoc> = HashMap::new(); for entry in fs::read_dir(format!("{}/functions", language_docs_dir)).unwrap() { let entry = entry.unwrap(); let path = entry.path(); // TODO figure out why this does not work //if path.is_file() && path.ends_with(".md") { if path.is_file() && path.to_str().unwrap().ends_with(".md") { println!("Parsing markdown file: {}", path.display()); let module_doc_file = File::open(Path::new(&path)).unwrap(); let mut buffered_reader = BufReader::new(module_doc_file); let mut module_doc_contents = String::new(); buffered_reader .read_to_string(&mut module_doc_contents) .unwrap(); module_doc_contents .split("\n### ") .skip(1) // first element is the module header, so skip it .for_each(|raw_function_doc| { let function_doc = raw_doc_to_function_doc(raw_function_doc); function_docs.insert(function_doc.signature.full_name.clone(), function_doc); }); } } function_docs } fn raw_doc_to_function_doc(raw_doc: &str) -> FunctionDoc { let doc_parts: Vec<&str> = raw_doc.splitn(2, '\n').map(|s| s.trim()).collect(); // TOOD use named params here let re = Regex::new(r"(.+)\((.*)\)\s*->(.+)").unwrap(); let caps_raw = re.captures(doc_parts[0]); let signature_doc = match caps_raw { Some(caps) => { println!("Found function: {}", &caps[0]); FunctionSignatureDoc { full_name: caps[1].trim().to_string(), args: caps[2].split(',').map(|s| s.trim().to_string()).collect(), result: caps[3].trim().to_string(), } } None => { // TODO proper error handling here dbg!(&doc_parts[0]); dbg!(&caps_raw); FunctionSignatureDoc { full_name: "random::string".to_string(), args: vec!["length".to_string()], result: "string".to_string(), } } }; FunctionDoc { signature: signature_doc, description: doc_parts[1].to_string(), summary: None, // TODO add first line? examples: None, // TODO parse out stuff in code blocks } } // TODO remove unwraps here fn bindump_function_docs(language_name: &str, dest_dir: &str) { let dest_path = Path::new(dest_dir).join(format!("function_docs.{}.bin", language_name)); let mut f = BufWriter::new(File::create(&dest_path).unwrap()); println!( "Dumping function docs for {} to: {}", language_name, dest_path.to_str().unwrap() ); let function_docs = match language_name { "tremor-script" => { let tremor_script_crate_path = get_tremor_script_crate_path(dest_dir); println!( "Reading tremor script stdlib files from {}", tremor_script_crate_path ); parse_tremor_stdlib(&tremor_script_crate_path) } _ => { // Tremor docs repo is needed right now for generating aggregate function documentation // as well as module completion items for tremor-query. Once we can can generate these // the same way as tremor-script, this won't be needed. if !Path::new(&format!("{}/LICENSE", BASE_DOCS_DIR)).exists() { println!("Setting up submodule dependencies..."); run_command_or_fail(".", "git", &["submodule", "update", "--init"]); } parse_raw_function_docs(&format!("{}/docs/{}", BASE_DOCS_DIR, language_name)) } }; bincode::serialize_into(&mut f, &function_docs).unwrap(); } // Utility functions fn get_cargo_lock_version_for_crate(name: &str) -> Option<String> { let re = Regex::new(&format!(r#""{}"[\r\n]+version = "(.+)""#, name)).unwrap(); re.captures(include_str!("Cargo.lock")) .map(|caps| caps[1].to_string()) } fn get_local_cargo_registry_path_for_crate( name: &str, version: &str, ) -> Result<Option<String>, Box<dyn std::error::Error>> { let crate_src_glob_path = home::cargo_home()? .join(&format!("registry/src/*/{}-{}/", name, version)) .display() .to_string(); Ok(glob::glob(&crate_src_glob_path)? .map(|result| result.unwrap()) .max() .map(|pathbuf| pathbuf.display().to_string())) } async fn download_and_extract_crate( name: &str, version: &str, dest_dir: &str, ) -> Result<String, Box<dyn std::error::Error>> { let crate_src_dir = format!("{}/{}-{}", dest_dir, name, version); if Path::new(&format!("{}/Cargo.toml", crate_src_dir)).exists() { println!( "Crate content is already there in the final source directory {}, so skipping download", crate_src_dir ); } else { let download_url = format!( // based on https://github.com/rust-lang/crates.io/issues/1592#issuecomment-453221464 "https://crates.io/api/v1/crates/{}/{}/download", name, version ); println!( "Downloading crate `{}=={}` from {}", name, version, download_url ); let crate_bytes = reqwest::get(&download_url).await?.bytes().await?; println!("Exracting crate to {}/", dest_dir); Archive::new(GzDecoder::new(&crate_bytes[..])).unpack(dest_dir)?; } // just follows the naming convention for a crate file (extracted above) Ok(format!("{}/{}-{}", dest_dir, name, version)) } // lifted from https://github.com/fede1024/rust-rdkafka/blob/v0.23.0/rdkafka-sys/build.rs#L7 fn run_command_or_fail<P, S>(dir: &str, cmd: P, args: &[S]) where P: AsRef<Path>, S: Borrow<str> + AsRef<OsStr>, { let cmd = cmd.as_ref(); let cmd = if cmd.components().count() > 1 && cmd.is_relative() { // If `cmd` is a relative path (and not a bare command that should be // looked up in PATH), absolutize it relative to `dir`, as otherwise the // behavior of std::process::Command is undefined. // https://github.com/rust-lang/rust/issues/37868 PathBuf::from(dir) .join(cmd) .canonicalize() .expect("canonicalization failed") } else { PathBuf::from(cmd) }; println!( "Running command: \"{} {}\" in dir: {}", cmd.display(), args.join(" "), dir ); let ret = Command::new(cmd).current_dir(dir).args(args).status(); match ret.map(|status| (status.success(), status.code())) { Ok((true, _)) => (), Ok((false, Some(c))) => panic!("Command failed with error code {}", c), Ok((false, None)) => panic!("Command got killed"), Err(e) => panic!("Command failed with error: {}", e), } } fn main() { match env::var("OUT_DIR") { Ok(out_dir) => { for language_name in LANGUAGES { bindump_function_docs(language_name, &out_dir); } } Err(e) => { eprintln!("Variable: OUT_DIR\nError: {}", e); process::exit(1) } } }
#[macro_export] macro_rules! hashmap { ( $( $k: expr => $v: expr ),* $(,)? ) => { { let mut kvpair = std::collections::HashMap::new(); $( kvpair.insert($k, $v); )* kvpair } }; }
#[doc = "Register `SECSR` reader"] pub type R = crate::R<SECSR_SPEC>; #[doc = "Field `SECBSY` reader - busy flag BSY flag indicates that a FLASH memory is busy by an operation (write, erase, option byte change, OBK operations, PUF operation). It is set at the beginning of a Flash memory operation and cleared when the operation finishes or an error occurs."] pub type SECBSY_R = crate::BitReader; #[doc = "Field `SECWBNE` reader - write buffer not empty flag WBNE flag is set when the embedded Flash memory is waiting for new data to complete the write buffer. In this state, the write buffer is not empty. WBNE is reset by hardware each time the write buffer is complete or the write buffer is emptied following one of the event below: the application software forces the write operation using FW bit in FLASH_SECCR the embedded Flash memory detects an error that involves data loss This bit cannot be reset by writing 0 directly by software. To reset it, clear the write buffer by performing any of the above listed actions, or send the missing data."] pub type SECWBNE_R = crate::BitReader; #[doc = "Field `SECDBNE` reader - data buffer not empty flag DBNE flag is set when the embedded Flash memory interface is processing 6-bits ECC data in dedicated buffer. This bit cannot be set to 0 by software. The hardware resets it once the buffer is free."] pub type SECDBNE_R = crate::BitReader; #[doc = "Field `SECEOP` reader - end of operation flag EOP flag is set when a operation (program/erase) completes. An interrupt is generated if the EOPIE is set to. It is not necessary to reset EOP before starting a new operation. EOP bit is cleared by writing 1 to CLR_EOP bit in FLASH_SECCCR register."] pub type SECEOP_R = crate::BitReader; #[doc = "Field `SECWRPERR` reader - write protection error flag WRPERR flag is raised when a protection error occurs during a program operation. An interrupt is also generated if the WRPERRIE is set to 1. Writing 1 to CLR_WRPERR bit in FLASH_SECCCR register clears WRPERR."] pub type SECWRPERR_R = crate::BitReader; #[doc = "Field `SECPGSERR` reader - programming sequence error flag PGSERR flag is raised when a sequence error occurs. An interrupt is generated if the PGSERRIE bit is set to 1. Writing 1 to CLR_PGSERR bit in FLASH_SECCCR register clears PGSERR."] pub type SECPGSERR_R = crate::BitReader; #[doc = "Field `SECSTRBERR` reader - strobe error flag STRBERR flag is raised when a strobe error occurs (when the master attempts to write several times the same byte in the write buffer). An interrupt is generated if the STRBERRIE bit is set to 1. Writing 1 to CLR_STRBERR bit in FLASH_SECCCR register clears STRBERR."] pub type SECSTRBERR_R = crate::BitReader; #[doc = "Field `SECINCERR` reader - inconsistency error flag INCERR flag is raised when a inconsistency error occurs. An interrupt is generated if INCERRIE is set to 1. Writing 1 to CLR_INCERR bit in the FLASH_SECCCR register clears INCERR."] pub type SECINCERR_R = crate::BitReader; impl R { #[doc = "Bit 0 - busy flag BSY flag indicates that a FLASH memory is busy by an operation (write, erase, option byte change, OBK operations, PUF operation). It is set at the beginning of a Flash memory operation and cleared when the operation finishes or an error occurs."] #[inline(always)] pub fn secbsy(&self) -> SECBSY_R { SECBSY_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - write buffer not empty flag WBNE flag is set when the embedded Flash memory is waiting for new data to complete the write buffer. In this state, the write buffer is not empty. WBNE is reset by hardware each time the write buffer is complete or the write buffer is emptied following one of the event below: the application software forces the write operation using FW bit in FLASH_SECCR the embedded Flash memory detects an error that involves data loss This bit cannot be reset by writing 0 directly by software. To reset it, clear the write buffer by performing any of the above listed actions, or send the missing data."] #[inline(always)] pub fn secwbne(&self) -> SECWBNE_R { SECWBNE_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 3 - data buffer not empty flag DBNE flag is set when the embedded Flash memory interface is processing 6-bits ECC data in dedicated buffer. This bit cannot be set to 0 by software. The hardware resets it once the buffer is free."] #[inline(always)] pub fn secdbne(&self) -> SECDBNE_R { SECDBNE_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 16 - end of operation flag EOP flag is set when a operation (program/erase) completes. An interrupt is generated if the EOPIE is set to. It is not necessary to reset EOP before starting a new operation. EOP bit is cleared by writing 1 to CLR_EOP bit in FLASH_SECCCR register."] #[inline(always)] pub fn seceop(&self) -> SECEOP_R { SECEOP_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - write protection error flag WRPERR flag is raised when a protection error occurs during a program operation. An interrupt is also generated if the WRPERRIE is set to 1. Writing 1 to CLR_WRPERR bit in FLASH_SECCCR register clears WRPERR."] #[inline(always)] pub fn secwrperr(&self) -> SECWRPERR_R { SECWRPERR_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - programming sequence error flag PGSERR flag is raised when a sequence error occurs. An interrupt is generated if the PGSERRIE bit is set to 1. Writing 1 to CLR_PGSERR bit in FLASH_SECCCR register clears PGSERR."] #[inline(always)] pub fn secpgserr(&self) -> SECPGSERR_R { SECPGSERR_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - strobe error flag STRBERR flag is raised when a strobe error occurs (when the master attempts to write several times the same byte in the write buffer). An interrupt is generated if the STRBERRIE bit is set to 1. Writing 1 to CLR_STRBERR bit in FLASH_SECCCR register clears STRBERR."] #[inline(always)] pub fn secstrberr(&self) -> SECSTRBERR_R { SECSTRBERR_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - inconsistency error flag INCERR flag is raised when a inconsistency error occurs. An interrupt is generated if INCERRIE is set to 1. Writing 1 to CLR_INCERR bit in the FLASH_SECCCR register clears INCERR."] #[inline(always)] pub fn secincerr(&self) -> SECINCERR_R { SECINCERR_R::new(((self.bits >> 20) & 1) != 0) } } #[doc = "FLASH secure status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secsr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SECSR_SPEC; impl crate::RegisterSpec for SECSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`secsr::R`](R) reader structure"] impl crate::Readable for SECSR_SPEC {} #[doc = "`reset()` method sets SECSR to value 0"] impl crate::Resettable for SECSR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Reader of register MIS"] pub type R = crate::R<u32, super::MIS>; impl R {}
use std::env; use std::fs; fn main(){ let args : Vec<String> = env::args().collect(); if args.len() < 2 { return; } let input = fs::read_to_string(&args[1]).unwrap() .strip_suffix('\n').unwrap() .parse::<i32>().unwrap(); let mut elves = Vec::<i32>::new(); for i in 1..input+1 { elves.push(i); } let mut i = 0; while elves.len() > 1 { let opposite = (i + elves.len()/2) % elves.len(); elves.remove(opposite); if opposite > i { i += 1; } i %= elves.len(); } println!("{}", elves[0]); }
use std::{collections::HashMap, env, fs, io, path::Path}; use serde_derive::{Deserialize, Serialize}; use bincode::{deserialize_from}; #[derive(Debug, Clone, Default, Copy, Serialize, Deserialize)] #[repr(C)] pub struct CondStmtBase { pub cmpid: u32, pub context: u32, pub order: u32, pub belong: u32, // 对应输入的Id pub condition: u32, pub level: u32, pub op: u32, pub size: u32, pub lb1: u32, // clang label pub lb2: u32, pub arg1: u64, pub arg2: u64, } impl PartialEq for CondStmtBase { fn eq(&self, other: &CondStmtBase) -> bool { self.cmpid == other.cmpid && self.context == other.context && self.order == other.order } } impl Eq for CondStmtBase {} #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, Hash)] #[repr(C)] pub struct TagSeg { pub sign: bool, pub begin: u32, pub end: u32, } #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct LogData { pub cond_list: Vec<CondStmtBase>, // 条件语句列表 pub tags: HashMap<u32, Vec<TagSeg>>, // clang label -> offsets (label -> bit vector) pub magic_bytes: HashMap<usize, (Vec<u8>, Vec<u8>)>, // variables } pub fn get_log_data(path: &Path) -> io::Result<LogData> { let f = fs::File::open(path)?; if f.metadata().unwrap().len() == 0 { return Err(io::Error::new(io::ErrorKind::Other, "Could not find any interesting constraint!, Please make sure taint tracking works or running program correctly.")); } let mut reader = io::BufReader::new(f); match deserialize_from::<&mut io::BufReader<fs::File>, LogData>(&mut reader) { Ok(v) => Ok(v), Err(_) => Err(io::Error::new(io::ErrorKind::Other, "bincode parse error!")), } } fn main() { let args: Vec<String> = env::args().collect(); assert_eq!(args.len(), 2); let path = Path::new(&args[1]); if let Ok(v) = get_log_data(&path) { println!("cond_list: {}", v.cond_list.len()); println!("tags: {}", v.tags.len()); println!("magic_bytes: {}", v.magic_bytes.len()); for num in 0..v.cond_list.len() { println!("{}: {:?}", num, v.cond_list[num]); } for (key, value) in v.tags { println!("{}: {:?}", key, value); } for (key, value) in v.magic_bytes { println!("{}: {:?} {:?}", key, value.0, value.1); } } }
use http::header::CONTENT_TYPE; pub use http::status::StatusCode; pub use hyper::Body; /// An HTTP response with a streaming body. pub type Response = hyper::Response<Body>; pub trait IntoResponse: Send + Sized { fn into_response(self) -> Response; } impl IntoResponse for () { fn into_response(self) -> Response { StatusCode::NO_CONTENT.into_response() } } impl IntoResponse for Vec<u8> { fn into_response(self) -> Response { http::Response::builder() .header(CONTENT_TYPE, "application/octet-stream") .body(Body::from(self)) .unwrap() } } impl IntoResponse for &'_ [u8] { fn into_response(self) -> Response { self.to_vec().into_response() } } impl IntoResponse for String { fn into_response(self) -> Response { http::Response::builder() .header(CONTENT_TYPE, "text/plain; charset=utf-8") .body(Body::from(self)) .unwrap() } } impl IntoResponse for &'_ str { fn into_response(self) -> Response { self.to_string().into_response() } } impl IntoResponse for StatusCode { fn into_response(self) -> Response { http::Response::builder() .status(self) .body(Body::empty()) .unwrap() } } impl<T, U> IntoResponse for Result<T, U> where T: IntoResponse, U: IntoResponse + std::fmt::Debug, { fn into_response(self) -> Response { match self { Ok(r) => r.into_response(), Err(r) => { log::debug!("response error: {:?}", r); r.into_response() } } } } impl<T> IntoResponse for http::Response<T> where T: Send + Into<Body>, { fn into_response(self) -> Response { self.map(Into::into) } } /// A response type that modifies the status code. #[derive(Debug)] pub struct WithStatus<T> { inner: T, status: StatusCode, } impl<R> IntoResponse for WithStatus<R> where R: IntoResponse, { fn into_response(self) -> Response { let mut resp = self.inner.into_response(); *resp.status_mut() = self.status; resp } } pub fn json<T>(t: &T) -> Response where T: serde::Serialize, { let res = http::Response::builder(); match serde_json::to_vec(t) { Ok(v) => res .header(CONTENT_TYPE, "application/json") .body(Body::from(v)), Err(e) => { log::error!("{}", e); res.status(StatusCode::INTERNAL_SERVER_ERROR) .body(Body::empty()) } } .unwrap() } pub fn html<T>(t: T) -> Response where T: Send + Into<Body>, { http::Response::builder() .header(CONTENT_TYPE, "text/html; charset=utf-8") .body(t.into()) .unwrap() }
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use SocketAddressEnumerator; use ffi; use glib::object::IsA; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { pub struct SocketConnectable(Object<ffi::GSocketConnectable, ffi::GSocketConnectableIface>); match fn { get_type => || ffi::g_socket_connectable_get_type(), } } pub trait SocketConnectableExt { fn enumerate(&self) -> Option<SocketAddressEnumerator>; fn proxy_enumerate(&self) -> Option<SocketAddressEnumerator>; #[cfg(any(feature = "v2_48", feature = "dox"))] fn to_string(&self) -> Option<String>; } impl<O: IsA<SocketConnectable>> SocketConnectableExt for O { fn enumerate(&self) -> Option<SocketAddressEnumerator> { unsafe { from_glib_full(ffi::g_socket_connectable_enumerate(self.to_glib_none().0)) } } fn proxy_enumerate(&self) -> Option<SocketAddressEnumerator> { unsafe { from_glib_full(ffi::g_socket_connectable_proxy_enumerate(self.to_glib_none().0)) } } #[cfg(any(feature = "v2_48", feature = "dox"))] fn to_string(&self) -> Option<String> { unsafe { from_glib_full(ffi::g_socket_connectable_to_string(self.to_glib_none().0)) } } }
#[cfg(any(target_os = "android"))] use backtrace::Backtrace; use common::*; use components::*; use gfx_h::{ load_atlas_image, Canvas, GeometryData, GlyphVertex, ParticlesData, TextData, TextVertexBuffer, WorldTextData, }; use glyph_brush::*; #[cfg(any(target_os = "android"))] use log::trace; use nphysics2d::world::World; use packer::SerializedSpriteSheet; use physics::PHYSICS_SIMULATION_TIME; use red::{self, glow, GL}; use ron::de::from_str; use sdl2::rwops::RWops; use serde::{Deserialize, Serialize}; use slog::o; use specs::World as SpecsWorld; use std::collections::HashMap; use std::io::Read; #[cfg(any(target_os = "android"))] use std::panic; use std::path::Path; use std::time::Duration; use telemetry::TeleGraph; const NEBULAS_NUM: usize = 2usize; pub fn preloaded_images( name_to_atlas: &HashMap<String, AtlasImage>, name_to_animation: &HashMap<String, Animation>, ) -> PreloadedImages { let mut nebula_images = vec![]; for i in 1..=NEBULAS_NUM { let nebula_image = name_to_atlas[&format!("nebula{}", i)]; nebula_images.push(nebula_image); } let mut stars_images = vec![]; for i in 2..=4 { let stars_image = name_to_atlas[&format!("stars{}", i)]; stars_images.push(stars_image); } let mut planet_images = vec![]; for planet_name in vec!["planet", "jupyterish", "halfmoon"].iter() { let planet_image = name_to_atlas[&planet_name.to_string()]; planet_images.push(planet_image); } PreloadedImages { nebulas: nebula_images, stars: stars_images, fog: name_to_atlas["fog"], planets: planet_images, ship_speed_upgrade: name_to_atlas["speed_upgrade"], bullet_speed_upgrade: name_to_atlas["bullet_speed"], attack_speed_upgrade: name_to_atlas["fire_rate"], light_white: name_to_atlas["light"], direction: name_to_atlas["direction"], circle: name_to_atlas["circle"], lazer: name_to_atlas["lazer_gun"], blaster: name_to_atlas["blaster_gun"], coin: name_to_atlas["coin"], health: name_to_atlas["life"], side_bullet_ability: name_to_atlas["side_bullets_ability"], exp: name_to_atlas["exp"], bar: name_to_atlas["bar"], upg_bar: name_to_atlas["upg_bar"], transparent_sqr: name_to_atlas["transparent_sqr"], glow: name_to_atlas["glow"], explosion: name_to_animation["explosion_anim"].clone(), blast: name_to_animation["blast2_anim"].clone(), bullet_contact: name_to_animation["bullet_contact_anim"].clone(), double_coin: name_to_atlas["double_coin_ability"], double_exp: name_to_atlas["double_exp_ability"], basic_ship: name_to_atlas["basic"], heavy_ship: name_to_atlas["heavy"], super_ship: name_to_atlas["basic"], locked: name_to_atlas["locked"], cursor: name_to_atlas["cursor"], } } pub fn load_animations( atlas: &SerializedSpriteSheet, ) -> HashMap<String, Animation> { let mut name_to_animation = HashMap::new(); // load animations let animations = [ ("explosion_anim", 7), ("blast2_anim", 7), ("bullet_contact_anim", 1), ]; // (name, ticks) for (animation_name, ticks) in animations.iter() { let mut frames = vec![]; for i in 1..100 { let animation_name = format!("{}_{}", animation_name, i); if let Some(image) = load_atlas_image(&animation_name, &atlas, 1.0) { let animation_frame = AnimationFrame { image, ticks: *ticks, }; frames.push(animation_frame); } else { break; }; } let animation = Animation::new(frames, 1, 0); name_to_animation.insert(animation_name.to_string(), animation); } name_to_animation } pub fn just_read(file: &str) -> Result<String, String> { let mut rw = RWops::from_file(Path::new(&file), "r")?; let mut desc_str = String::new(); if let Ok(_) = rw.read_to_string(&mut desc_str) { Ok(desc_str) } else { Err("failed to read file".to_string()) } } pub fn setup_logging() -> slog_scope::GlobalLoggerGuard { use slog::Drain; use std::fs::OpenOptions; let log_path = "game.log"; let file = OpenOptions::new() .create(true) .write(true) .truncate(true) .open(log_path) .unwrap(); // create logger let decorator = slog_term::PlainSyncDecorator::new(file); let drain = slog_term::FullFormat::new(decorator).build().fuse(); let logger = slog::Logger::root(drain, o!()); // slog_stdlog uses the logger from slog_scope, so set a logger there let guard = slog_scope::set_global_logger(logger); // register slog_stdlog as the log handler with the log crate slog_stdlog::init().unwrap(); guard } pub fn setup_text(context: &red::GL, specs_world: &mut SpecsWorld) { let dejavu: &[u8] = include_bytes!("../assets/fonts/DejaVuSans.ttf"); { let text_buffer = TextVertexBuffer::empty_new(&context).unwrap(); let glyph_brush: GlyphBrush<GlyphVertex, _> = GlyphBrushBuilder::using_font_bytes(dejavu).build(); let glyph_texture = red::shader::Texture::new( context, glyph_brush.texture_dimensions(), ); let text_data = ThreadPin::new(TextData { vertex_buffer: text_buffer, vertex_num: 0, glyph_texture: glyph_texture.clone(), glyph_brush, }); specs_world.add_resource(text_data); specs_world.add_resource(glyph_texture); } { // copy paste to store world text data separetly // (needed because we need different transformation uniform in shader) let text_buffer = TextVertexBuffer::empty_new(&context).unwrap(); let glyph_brush: GlyphBrush<GlyphVertex, _> = GlyphBrushBuilder::using_font_bytes(dejavu).build(); let glyph_texture = red::shader::Texture::new( context, glyph_brush.texture_dimensions(), ); let text_data = ThreadPin::new(WorldTextData { vertex_buffer: text_buffer, vertex_num: 0, glyph_texture: glyph_texture.clone(), glyph_brush, }); specs_world.add_resource(text_data); specs_world.add_resource(glyph_texture); } } pub fn setup_telegraph() -> TeleGraph { let mut telegraph = TeleGraph::new(Duration::from_secs(10)); telegraph.set_color("rendering".to_string(), Point3::new(1.0, 0.0, 0.0)); telegraph.set_color("dispatch".to_string(), Point3::new(0.0, 1.0, 0.0)); telegraph.set_color("insert".to_string(), Point3::new(0.0, 0.0, 1.0)); telegraph.set_color("asteroids".to_string(), Point3::new(1.0, 0.0, 1.0)); telegraph.set_color("fps".to_string(), Point3::new(1.0, 1.0, 0.0)); telegraph.set_color( "asteroids rendering".to_string(), Point3::new(0.1, 1.0, 1.0), ); telegraph.set_color( "foreground rendering".to_string(), Point3::new(0.8, 0.8, 0.1), ); telegraph.set_color( "background rendering".to_string(), Point3::new(0.8, 0.1, 0.1), ); telegraph .set_color("shadow rendering".to_string(), Point3::new(0.1, 0.1, 1.0)); telegraph.set_color( "sprite batch rendering".to_string(), Point3::new(0.5, 0.1, 0.1), ); telegraph.set_color("clear".to_string(), Point3::new(0.0, 0.6, 0.0)); telegraph } #[cfg(any(target_os = "android"))] pub fn setup_android() { panic::set_hook(Box::new(|panic_info| { trace!("AAA PANIC"); trace!("{}", panic_info); let bt = Backtrace::new(); trace!("{:?}", bt); })); android_log::init("MyApp").unwrap(); } pub fn setup_physics(specs_world: &mut SpecsWorld) { let mut phys_world: World<f32> = World::new(); phys_world.set_timestep(PHYSICS_SIMULATION_TIME); { // nphysics whatever parameters tuning phys_world.integration_parameters_mut().erp = 0.01; phys_world .integration_parameters_mut() .max_linear_correction = 10.0; } specs_world.add_resource(phys_world); } pub fn setup_gfx( specs_world: &mut SpecsWorld, ) -> Result< ( red::GL, sdl2::Sdl, glow::native::RenderLoop<sdl2::video::Window>, sdl2::video::GLContext, f32, Canvas, ), String, > { let (window_w, window_h) = (1920u32, 1080); let viewport = red::Viewport::for_window(window_w as i32, window_h as i32); let sdl_context = sdl2::init().unwrap(); let video = sdl_context.video().unwrap(); let (_ddpi, hdpi, _vdpi) = video.display_dpi(0i32)?; let gl_attr = video.gl_attr(); #[cfg(not(any(target_os = "android")))] let glsl_version = "#version 330"; #[cfg(any(target_os = "android"))] let glsl_version = "#version 300 es"; #[cfg(any(target_os = "android"))] { gl_attr.set_context_profile(sdl2::video::GLProfile::GLES); gl_attr.set_context_version(3, 0); } #[cfg(not(any(target_os = "android")))] { gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(3, 3); } let window = video .window("Asteroids 2.0", window_w, window_h) // .fullscreen() .opengl() .resizable() .build() .unwrap(); let gl_context = window.gl_create_context().unwrap(); let render_loop = glow::native::RenderLoop::<sdl2::video::Window>::from_sdl_window( window, ); let context = glow::native::Context::from_loader_function(|s| { video.gl_get_proc_address(s) as *const _ }); let context = GL::new(context); let canvas = Canvas::new(&context, "", "atlas", &glsl_version).unwrap(); specs_world.add_resource(viewport); Ok((context, sdl_context, render_loop, gl_context, hdpi, canvas)) } pub fn read_atlas(path: &str) -> SerializedSpriteSheet { let content = just_read(path).unwrap(); let parsed: SerializedSpriteSheet = match from_str(&content) { Ok(x) => x, Err(e) => { println!("Failed to load atlas: {}", e); std::process::exit(1); } }; parsed } pub fn setup_images( atlas: &SerializedSpriteSheet, ) -> HashMap<String, AtlasImage> { // dbg!(&atlas.sprites["chains_dark"]); let mut name_to_image = HashMap::new(); for (name, _sprite) in atlas.sprites.iter() { let image = load_atlas_image(&name, &atlas, 1.0).unwrap(); name_to_image.insert(name.clone(), image); } name_to_image } pub fn data_setup(specs_world: &mut SpecsWorld) { specs_world.register::<Isometry>(); specs_world.register::<Velocity>(); specs_world.register::<CharacterMarker>(); specs_world.register::<AsteroidMarker>(); specs_world.register::<Rocket>(); specs_world.register::<RocketGun>(); specs_world.register::<Projectile>(); specs_world.register::<Reflection>(); specs_world.register::<Blast>(); specs_world.register::<ThreadPin<ImageData>>(); specs_world.register::<AtlasImage>(); specs_world.register::<ThreadPin<GeometryData>>(); specs_world.register::<Spin>(); specs_world.register::<AttachPosition>(); specs_world.register::<ShotGun>(); specs_world.register::<Cannon>(); specs_world.register::<MultyLazer>(); specs_world.register::<Sound>(); specs_world.register::<Geometry>(); specs_world.register::<Lifetime>(); specs_world.register::<Size>(); specs_world.register::<EnemyMarker>(); specs_world.register::<LightMarker>(); specs_world.register::<ShipMarker>(); specs_world.register::<Coin>(); specs_world.register::<SideBulletCollectable>(); specs_world.register::<SideBulletAbility>(); specs_world.register::<DoubleCoinsCollectable>(); specs_world.register::<DoubleCoinsAbility>(); specs_world.register::<DoubleExpCollectable>(); specs_world.register::<DoubleExpAbility>(); specs_world.register::<Exp>(); specs_world.register::<Health>(); specs_world.register::<CollectableMarker>(); specs_world.register::<PhysicsComponent>(); specs_world.register::<Polygon>(); specs_world.register::<ThreadPin<sdl2::mixer::Chunk>>(); specs_world.register::<ThreadPin<SoundData>>(); specs_world.register::<Lifes>(); specs_world.register::<Shield>(); specs_world.register::<NebulaMarker>(); specs_world.register::<StarsMarker>(); specs_world.register::<FogMarker>(); specs_world.register::<PlanetMarker>(); specs_world.register::<Damage>(); specs_world.register::<AI>(); specs_world.register::<ThreadPin<ParticlesData>>(); specs_world.register::<ShipStats>(); specs_world.register::<Animation>(); specs_world.register::<Charge>(); specs_world.register::<Chain>(); specs_world.register::<LazerConnect>(); specs_world.register::<SoundPlacement>(); specs_world.register::<Rift>(); specs_world.register::<DamageFlash>(); specs_world.register::<TextComponent>(); specs_world.register::<Position2D>(); specs_world.register::<ReflectBulletCollectable>(); specs_world.register::<ReflectBulletAbility>(); specs_world.add_resource(UpgradesStats::default()); specs_world.add_resource(DevInfo::new()); specs_world.add_resource(Pallete::new()); specs_world.add_resource(UIState::default()); specs_world.add_resource(BodiesMap::new()); let spawned_upgrades: SpawnedUpgrades = vec![]; specs_world.add_resource(spawned_upgrades); let touches: Touches = [None; FINGER_NUMBER]; specs_world.add_resource(touches); } pub fn load_description( specs_world: &mut SpecsWorld, name_to_atlas: &HashMap<String, AtlasImage>, ) { // load .ron files with tweaks #[derive(Debug, Serialize, Deserialize)] pub struct DescriptionSave { ship_costs: Vec<usize>, gun_costs: Vec<usize>, player_ships: Vec<ShipKindSave>, player_guns: Vec<GunKindSave>, enemies: Vec<EnemyKindSave>, } fn process_description( description_save: DescriptionSave, name_to_atlas: &HashMap<String, AtlasImage>, ) -> Description { Description { gun_costs: description_save.gun_costs, ship_costs: description_save.ship_costs, player_ships: description_save .player_ships .iter() .map(|x| x.clone().load(name_to_atlas)) .collect(), player_guns: description_save .player_guns .iter() .map(|gun| gun.convert(name_to_atlas)) .collect(), enemies: description_save .enemies .iter() .map(|enemy| load_enemy(enemy, name_to_atlas)) .collect(), } } fn load_enemy( enemy_save: &EnemyKindSave, name_to_atlas: &HashMap<String, AtlasImage>, ) -> EnemyKind { dbg!(&enemy_save.image_name); EnemyKind { ai_kind: enemy_save.ai_kind.clone(), gun_kind: enemy_save.gun_kind.convert(name_to_atlas), ship_stats: enemy_save.ship_stats, size: enemy_save.size, image: name_to_atlas[&enemy_save.image_name], snake: enemy_save.snake, rift: enemy_save.rift.clone(), } } #[derive(Debug, Serialize, Deserialize)] pub struct EnemyKindSave { pub ai_kind: AI, pub gun_kind: GunKindSave, pub ship_stats: ShipStats, pub size: f32, pub image_name: String, pub snake: Option<usize>, #[serde(default)] pub rift: Option<Rift>, }; #[cfg(not(target_os = "android"))] let file = just_read("rons/desc.ron").unwrap(); #[cfg(target_os = "android")] let file = include_str!("../rons/desc.ron"); let file = &file; let desc: DescriptionSave = match from_str(file) { Ok(x) => x, Err(e) => { println!("Failed to load config: {}", e); std::process::exit(1); } }; let mut enemy_name_to_id = HashMap::new(); for (id, enemy) in desc.enemies.iter().enumerate() { enemy_name_to_id.insert(enemy.image_name.clone(), id); } let desc = process_description(desc, &name_to_atlas); specs_world.add_resource(desc); let file = include_str!("../rons/upgrades.ron"); let upgrades_all: Vec<UpgradeCardRaw> = match from_str(file) { Ok(x) => x, Err(e) => { println!("Failed to load config: {}", e); std::process::exit(1); } }; let upgrades: Vec<UpgradeCard> = upgrades_all .iter() .map(|upgrade| { dbg!(&upgrade.image); UpgradeCard { upgrade_type: upgrade.upgrade_type, image: name_to_atlas[&upgrade.image], name: upgrade.name.clone(), description: upgrade.description.clone(), } }) .collect(); let avaliable_upgrades = upgrades; specs_world.add_resource(avaliable_upgrades); pub fn wave_load( wave: &WaveSave, enemy_name_to_id: &HashMap<String, usize>, ) -> Wave { let distribution: Vec<(usize, f32)> = wave .distribution .iter() .map(|p| { dbg!(&p.0); (enemy_name_to_id[&p.0], p.1) }) .collect(); let const_distribution: Vec<(usize, usize)> = wave .const_distribution .iter() .map(|p| (enemy_name_to_id[&p.0], p.1)) .collect(); Wave { distribution: distribution, ships_number: wave.ships_number, const_distribution: const_distribution, iterations: wave.iterations, } } #[cfg(target_os = "android")] let file = include_str!("../rons/waves.ron"); #[cfg(not(target_os = "android"))] let file = &just_read("rons/waves.ron").unwrap(); let waves: WavesSave = match from_str(file) { Ok(x) => x, Err(e) => { println!("Failed to load config: {}", e); std::process::exit(1); } }; let waves: Waves = Waves( waves .0 .iter() .map(|p| wave_load(p, &enemy_name_to_id)) .collect(), ); specs_world.add_resource(waves); specs_world.add_resource(upgrades_all); specs_world.add_resource(CurrentWave::default()); { // load macro game let file = "rons/macro_game.ron"; let macro_game = if let Ok(mut rw) = RWops::from_file(Path::new(&file), "r") { let mut macro_game_str = String::new(); let macro_game = if let Ok(_) = rw.read_to_string(&mut macro_game_str) { let macro_game: MacroGame = match from_str(&macro_game_str) { Ok(x) => x, Err(e) => { println!("Failed to load config: {}", e); std::process::exit(1); } }; macro_game } else { MacroGame::default() }; macro_game } else { MacroGame::default() }; specs_world.add_resource(macro_game); } }
use std::{error::Error, fs::File, io}; use rustyline::{error::ReadlineError, Editor}; use thiserror::Error; use crate::{ eval::eval, ident::identify, parser::parse, typeck::typeck, prelude::*, }; const HISTORY_FILE: &'static str = ".odlang_history"; #[derive(Debug, Error)] pub enum HistoryError { #[error("Failed to create history file.")] NotCreated(#[from] io::Error), #[error("Failed to append history to history file.")] NotAppended(#[from] ReadlineError), } pub fn repl() -> Result<(), HistoryError> { let mut editor = Editor::<()>::new(); if let Err(_) = editor.load_history(HISTORY_FILE) { File::create(HISTORY_FILE)?; } while let Ok(line) = editor.readline("turtle > ") { if !editor.add_history_entry(&line) { println!("This entry will not appear in history."); } match process_line(&line) { Ok(line) => println!("{}", line), Err(err) => eprintln!("{}", err), } } Ok(editor.append_history(HISTORY_FILE)?) } fn process_line<'a>( line: &'a str, ) -> Result<String, Box<dyn Error + 'a>> { let (term, names) = identify(parse(line)?)?; match typeck(term.clone()) { Ok(_) => Ok(eval(term).pprint(&names)), Err(err) => Err(err.pprint(&names).into()), } }
use std::collections::{HashMap, HashSet}; use std::io::{BufReader, BufRead, Error}; use std::fs::File; fn read_input() -> Result<Vec<String>, Error> { let file = File::open("input/day02.txt").unwrap(); BufReader::new(file).lines().collect::<_>() } fn count(s: &str) -> HashMap<char, u32> { let mut counts = HashMap::new(); for char in s.chars() { *counts.entry(char).or_insert(0) += 1; } counts } fn solve1(lines: &Vec<String>) -> u32 { let mut count2 = 0; let mut count3 = 0; for line in lines { let mut has_2 = false; let mut has_3 = false; for count in count(&line).values() { match count { 2 => has_2 = true, 3 => has_3 = true, _ => () } } count2 += has_2 as u32; count3 += has_3 as u32; } count2 * count3 } fn solve2(lines: &Vec<String>) -> String { let mut seen = HashSet::new(); for line in lines { let mut char_vec = line.chars().collect::<Vec<char>>(); for i in 0..char_vec.len() { let one_missing = char_vec[..i].iter().chain(char_vec[i + 1..].iter()).collect::<String>(); if seen.contains(&(i, one_missing.clone())) { return one_missing; } seen.insert((i, one_missing)); } } "".to_string() } pub fn solve() { let lines = read_input().unwrap(); println!("Checksum: {}", solve1(&lines)); println!("Common letters: {}", solve2(&lines)); }
extern crate clap; use clap::App; use clap::Arg; use clap::SubCommand; use std::env; /// Command line interface. pub fn main() { let query_arg = Arg::with_name("QUERY") .help("SQL statement to prepare") .required(true); let params_arg = Arg::with_name("PARAMS") .help("The values for the prepared statement parameters (required if any)") .required(false); let input_format_arg = Arg::with_name("input_format") .long("input-format") .short("i") .takes_value(true) .default_value("csv") // TODO @mverleg: any other format? .help("The output format to use: json, csv"); let output_format_arg = Arg::with_name("output_format") .long("output-format") .short("o") .takes_value(true) .default_value("text") .help("The output format to use: text, json, xml, csv"); // TODO @mverleg: Current options don't allow for creating database on another machine // TODO @mverleg: I might do something with stored keys to connect later let mut app = App::new(env!("CARGO_PKG_NAME").to_owned() + " command-line interface") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .arg(Arg::with_name("verbosity") .long("verbose") .short("v") .multiple(true) .help("Sets the level of verbosity")) .arg(Arg::with_name("version") .long("version") .help("Show the version and exit")) .subcommand(SubCommand::with_name("connect") .about("Connect to a database") .arg(Arg::with_name("DB") .help("The name of the database to connect to") .required(true) .index(1)) .arg(Arg::with_name("user") .long("user") .short("u") .takes_value(true) .default_value("root") .help("The name of a user to connect with")) .arg(Arg::with_name("password") .long("password") .short("p") .takes_value(true) .help("The password of a user to connect with (careful with shell history; leave this out to be prompted)")) .arg(Arg::with_name("timeout") .long("timeout") .short("t") .takes_value(true) .default_value("300") .help("The inactivity timeout (s) after which you need to reconnect")) ) .subcommand(SubCommand::with_name("disconnect") .about("Disconnect from a database") .arg(Arg::with_name("DB") .help("The name of the database to disconnect from") .required(true) .index(1)) ) // Note: there are no special permissions for create and delete, just OS-level file permissions .subcommand(SubCommand::with_name("create") .about("Create a new database") .arg(Arg::with_name("DB") .help("Sets the directory where the database is to be created") .required(true) .index(1)) .arg(Arg::with_name("user") .long("user") .short("u") .takes_value(true) .default_value("root") .help("The name of a user to create")) .arg(Arg::with_name("password") .long("password") .short("p") .takes_value(true) .help("The password of a user to create (careful with shell history; leave this out to be prompted)")) .arg(Arg::with_name("port") .long("port") .short("P") .takes_value(true) .default_value("4740") // TODO @mverleg: increment? .help("The port to make the database available at")) .arg(Arg::with_name("global") .long("global") .short("g") .help("Make this a shared database (needs root permissions)")) .arg(Arg::with_name("path") .long("path") .takes_value(true) .help("The path to store the database at")) ) .subcommand(SubCommand::with_name("delete") .about("Delete an existing database (careful!)") .arg(Arg::with_name("DB") .help("Sets the directory of the database to be deleted") .required(true) .index(1)) .arg(Arg::with_name("path") .long("path") .takes_value(true) .help("The path to store the database at")) .arg(Arg::with_name("yes") .short("y") .long("non-interactive") .help("Delete without further warning or confirmation")) ) .subcommand(SubCommand::with_name("prepare") .about("Prepare an SQL statement that can be run with 'perform'") .arg(Arg::with_name("DB") .help("The name of the database to prepare the query on") .required(true) .index(1)) .arg(query_arg.clone().index(2)) ) .subcommand(SubCommand::with_name("perform") .about("Perform an SQL statement prepared with 'prepare'") .arg(Arg::with_name("DB") .help("The name of the database to perform the query on") .required(true) .index(1)) .arg(Arg::with_name("PREP_STAT") .help("The identifier of the prepared statement returned by 'prepare'") .required(true) .index(2)) .arg(query_arg.clone().index(3)) .arg(input_format_arg.clone()) .arg(output_format_arg.clone()) ) .subcommand(SubCommand::with_name("direct") .about("Prepare and directly run an SQL statement (like 'prepare' + 'perform')") .arg(Arg::with_name("DB") .help("The name of the database to perform the query on") .required(true) .index(1)) .arg(query_arg.clone().index(2)) .arg(params_arg.clone().index(3)) .arg(input_format_arg.clone()) .arg(output_format_arg.clone()) ) ; if (env::args().len() <= 1) { app.print_help(); return; } let matches = app.clone().get_matches(); if matches.is_present("version") { println!("{}", env!("CARGO_PKG_VERSION")); return; } unimplemented!(); }
use crate::resources::spawner::DespawnEffect; use oxygengine::prelude::*; #[derive(Debug, Copy, Clone)] pub struct Death(pub DespawnEffect); impl Component for Death { type Storage = VecStorage<Self>; }