text
stringlengths
8
4.13M
// Copyright 2019, 2020 Wingchain // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use tempfile::tempdir; use futures::channel::oneshot; use node_chain::{Chain, ChainConfig, DBConfig}; use node_consensus::{Consensus, ConsensusConfig}; use node_consensus_base::support::DefaultConsensusSupport; use node_consensus_base::ConsensusInMessage; use node_consensus_raft::RaftConfig; use node_coordinator::support::DefaultCoordinatorSupport; use node_coordinator::{ Coordinator, CoordinatorConfig, Keypair, LinkedHashMap, Multiaddr, NetworkConfig, PeerId, Protocol, }; use node_txpool::support::DefaultTxPoolSupport; use node_txpool::{TxPool, TxPoolConfig}; use primitives::{Address, BlockNumber, Hash, Transaction}; use utils_test::TestAccount; pub fn get_service( authority_accounts: &[&TestAccount], account: &TestAccount, local_key_pair: Keypair, port: u16, bootnodes: LinkedHashMap<(PeerId, Multiaddr), ()>, ) -> ( Arc<Chain>, Arc<TxPool<DefaultTxPoolSupport>>, Arc<Consensus<DefaultConsensusSupport>>, Arc<Coordinator<DefaultCoordinatorSupport>>, ) { let chain = get_chain(authority_accounts); let txpool_config = TxPoolConfig { pool_capacity: 32 }; let txpool_support = Arc::new(DefaultTxPoolSupport::new(chain.clone())); let txpool = Arc::new(TxPool::new(txpool_config, txpool_support).unwrap()); let support = Arc::new(DefaultConsensusSupport::new(chain.clone(), txpool.clone())); let consensus_config = ConsensusConfig { poa: None, raft: Some(RaftConfig { secret_key: Some(account.secret_key.clone()), init_extra_election_timeout: Some(0), extra_election_timeout_per_kb: Some(5), request_proposal_min_interval: Some(1000), }), hotstuff: None, }; let consensus = Arc::new(Consensus::new(consensus_config, support).unwrap()); let coordinator_support = Arc::new(DefaultCoordinatorSupport::new( chain.clone(), txpool.clone(), consensus.clone(), )); let coordinator = get_coordinator(local_key_pair, port, bootnodes, coordinator_support); (chain, txpool, consensus, coordinator) } pub async fn insert_tx( chain: &Arc<Chain>, txpool: &Arc<TxPool<DefaultTxPoolSupport>>, tx: Transaction, ) -> Hash { let tx_hash = chain.hash_transaction(&tx).unwrap(); txpool.insert(tx).unwrap(); tx_hash } pub async fn wait_txpool(txpool: &Arc<TxPool<DefaultTxPoolSupport>>, count: usize) { loop { { let queue = txpool.get_queue().read(); if queue.len() == count { break; } } futures_timer::Delay::new(Duration::from_millis(10)).await; } } pub async fn wait_block_execution(chain: &Arc<Chain>, expected_number: BlockNumber) { loop { { let number = chain.get_confirmed_number().unwrap().unwrap(); let block_hash = chain.get_block_hash(&number).unwrap().unwrap(); let execution = chain.get_execution(&block_hash).unwrap(); if number == expected_number && execution.is_some() { break; } } futures_timer::Delay::new(Duration::from_millis(10)).await; } } pub async fn wait_leader_elected(consensus: &Arc<Consensus<DefaultConsensusSupport>>) -> Address { let in_tx = consensus.in_message_tx(); let address = loop { { let (tx, rx) = oneshot::channel(); let _ = in_tx.unbounded_send(ConsensusInMessage::GetConsensusState { tx }); let consensus_state = rx.await.unwrap(); let current_leader = &consensus_state["current_leader"]; if current_leader.is_string() { break current_leader.as_str().unwrap().to_string(); } } futures_timer::Delay::new(Duration::from_millis(10)).await; }; let address = hex::decode(address).unwrap(); Address(address) } fn get_coordinator( local_key_pair: Keypair, port: u16, bootnodes: LinkedHashMap<(PeerId, Multiaddr), ()>, support: Arc<DefaultCoordinatorSupport>, ) -> Arc<Coordinator<DefaultCoordinatorSupport>> { let agent_version = "wingchain/1.0.0".to_string(); let listen_address = Multiaddr::empty() .with(Protocol::Ip4([0, 0, 0, 0].into())) .with(Protocol::Tcp(port)); let listen_addresses = vec![listen_address].into_iter().map(|v| (v, ())).collect(); let network_config = NetworkConfig { max_in_peers: 32, max_out_peers: 32, listen_addresses, external_addresses: LinkedHashMap::new(), bootnodes, reserved_nodes: LinkedHashMap::new(), reserved_only: false, agent_version, local_key_pair, handshake_builder: None, }; let config = CoordinatorConfig { network_config }; let coordinator = Coordinator::new(config, support).unwrap(); Arc::new(coordinator) } fn get_chain(authority_accounts: &[&TestAccount]) -> Arc<Chain> { let path = tempdir().expect("Could not create a temp dir"); let home = path.into_path(); init(&home, authority_accounts); let db = DBConfig { memory_budget: 1 * 1024 * 1024, path: home.join("data").join("db"), partitions: vec![], }; let chain_config = ChainConfig { home, db }; let chain = Arc::new(Chain::new(chain_config).unwrap()); chain } fn init(home: &PathBuf, authority_accounts: &[&TestAccount]) { let config_path = home.join("config"); fs::create_dir_all(&config_path).unwrap(); let members = authority_accounts .into_iter() .map(|x| format!("\"{}\"", x.address)) .collect::<Vec<_>>() .join(","); let spec = format!( r#" [basic] hash = "blake2b_256" dsa = "ed25519" address = "blake2b_160" [genesis] [[genesis.txs]] module = "system" method = "init" params = ''' {{ "chain_id": "chain-test", "timestamp": "2020-04-29T15:51:36.502+08:00", "max_until_gap": 20, "max_execution_gap": 8, "consensus": "raft" }} ''' [[genesis.txs]] module = "balance" method = "init" params = ''' {{ "endow": [ ["{}", 10] ] }} ''' [[genesis.txs]] module = "raft" method = "init" params = ''' {{ "block_interval": null, "heartbeat_interval": 100, "election_timeout_min": 500, "election_timeout_max": 1000, "admin": {{ "threshold": 1, "members": [["{}", 1]] }}, "authorities": {{ "members": [{}] }} }} ''' [[genesis.txs]] module = "contract" method = "init" params = ''' {{ }} ''' "#, authority_accounts[0].address, authority_accounts[0].address, members ); fs::write(config_path.join("spec.toml"), &spec).unwrap(); }
pub mod pin; pub mod clock; pub mod serial; pub mod time; pub mod peripheral;
#![feature(global_allocator)] extern crate libc; extern crate jemalloc_sys as ffi; extern crate jemallocator; use std::ptr; use std::mem; use libc::{c_void, c_char}; use jemallocator::Jemalloc; #[global_allocator] static A: Jemalloc = Jemalloc; #[test] fn test_basic_alloc() { unsafe { let exp_size = ffi::nallocx(100, 0); assert!(exp_size >= 100); let mut ptr = ffi::mallocx(100, 0); assert!(!ptr.is_null()); assert_eq!(exp_size, ffi::malloc_usable_size(ptr)); ptr = ffi::rallocx(ptr, 50, 0); let size = ffi::xallocx(ptr, 30, 20, 0); assert!(size >= 50); ffi::sdallocx(ptr, 50, 0); } } #[test] fn test_mallctl() { let ptr = unsafe { ffi::mallocx(100, 0) }; let mut allocated: usize = 0; let mut val_len = mem::size_of_val(&allocated); let field = "stats.allocated\0"; let mut code; code = unsafe { ffi::mallctl(field.as_ptr() as *const _, &mut allocated as *mut _ as *mut c_void, &mut val_len, ptr::null_mut(), 0) }; assert_eq!(code, 0); assert!(allocated > 0); let mut mib = [0, 0]; let mut mib_len = 2; code = unsafe { ffi::mallctlnametomib(field.as_ptr() as *const _, mib.as_mut_ptr(), &mut mib_len) }; assert_eq!(code, 0); let mut allocated_by_mib = 0; let code = unsafe { ffi::mallctlbymib(mib.as_ptr(), mib_len, &mut allocated_by_mib as *mut _ as *mut c_void, &mut val_len, ptr::null_mut(), 0) }; assert_eq!(code, 0); assert_eq!(allocated_by_mib, allocated); unsafe { ffi::sdallocx(ptr, 100, 0) }; } #[test] fn test_stats() { struct PrintCtx { called_times: usize, } extern "C" fn write_cb(ctx: *mut c_void, _: *const c_char) { let print_ctx = unsafe { &mut *(ctx as *mut PrintCtx) }; print_ctx.called_times += 1; } let mut ctx = PrintCtx { called_times: 0 }; unsafe { ffi::malloc_stats_print(write_cb, &mut ctx as *mut _ as *mut c_void, ptr::null()); } assert_ne!(ctx.called_times, 0, "print should be triggered at lease once."); }
use draw::DrawContext; use std::os::raw::c_int; use ui_sys::{self, uiDrawFillMode, uiDrawFillModeAlternate, uiDrawFillModeWinding, uiDrawPath}; pub struct Path { ui_draw_path: *mut uiDrawPath, } impl Drop for Path { fn drop(&mut self) { unsafe { ui_sys::uiDrawFreePath(self.ui_draw_path) } } } /// Represents the fill mode used when drawing a path. #[derive(Clone, Copy, PartialEq)] pub enum FillMode { /// Draw using the [non-zero winding number fill rule](https://en.wikipedia.org/wiki/Nonzero-rule). Winding, /// Draw using the [even-odd fill rule](https://en.wikipedia.org/wiki/Even-odd_rule). Alternate, } impl FillMode { fn into_ui_fillmode(self) -> uiDrawFillMode { return match self { FillMode::Winding => uiDrawFillModeWinding, FillMode::Alternate => uiDrawFillModeAlternate, } as uiDrawFillMode; } } impl Path { pub fn new(_ctx: &DrawContext, fill_mode: FillMode) -> Path { unsafe { Path { ui_draw_path: ui_sys::uiDrawNewPath(fill_mode.into_ui_fillmode()), } } } pub fn new_figure(&self, _ctx: &DrawContext, x: f64, y: f64) { unsafe { ui_sys::uiDrawPathNewFigure(self.ui_draw_path, x, y) } } pub fn new_figure_with_arc( &self, _ctx: &DrawContext, x_center: f64, y_center: f64, radius: f64, start_angle: f64, sweep: f64, negative: bool, ) { unsafe { ui_sys::uiDrawPathNewFigureWithArc( self.ui_draw_path, x_center, y_center, radius, start_angle, sweep, negative as c_int, ) } } pub fn line_to(&self, _ctx: &DrawContext, x: f64, y: f64) { unsafe { ui_sys::uiDrawPathLineTo(self.ui_draw_path, x, y) } } pub fn arc_to( &self, _ctx: &DrawContext, x_center: f64, y_center: f64, radius: f64, start_angle: f64, sweep: f64, negative: bool, ) { unsafe { ui_sys::uiDrawPathArcTo( self.ui_draw_path, x_center, y_center, radius, start_angle, sweep, negative as c_int, ) } } pub fn bezier_to( &self, _ctx: &DrawContext, c1x: f64, c1y: f64, c2x: f64, c2y: f64, end_x: f64, end_y: f64, ) { unsafe { ui_sys::uiDrawPathBezierTo(self.ui_draw_path, c1x, c1y, c2x, c2y, end_x, end_y) } } pub fn close_figure(&self, _ctx: &DrawContext) { unsafe { ui_sys::uiDrawPathCloseFigure(self.ui_draw_path) } } pub fn add_rectangle(&self, _ctx: &DrawContext, x: f64, y: f64, width: f64, height: f64) { unsafe { ui_sys::uiDrawPathAddRectangle(self.ui_draw_path, x, y, width, height) } } pub fn end(&self, _ctx: &DrawContext) { unsafe { ui_sys::uiDrawPathEnd(self.ui_draw_path) } } /// Return the underlying pointer for this Path. pub fn ptr(&self) -> *mut uiDrawPath { self.ui_draw_path } }
use std::{error::Error, fs}; use std::{path::PathBuf, str::FromStr}; use super::temps::{GPUTempReader, GPUTemps}; use serde::Serialize; #[derive(Serialize, Clone)] pub struct GPUStatus { pub voltage: Option<f32>, pub power_consumption: Option<f32>, pub fan_speed: Option<i32>, pub temps: Option<GPUTemps>, } #[derive(Clone)] pub struct GPUStatusReader { hwmon_path: PathBuf, temps_reader: GPUTempReader, } impl GPUStatusReader { pub fn new(hwmon_path: &PathBuf) -> Self { GPUStatusReader { hwmon_path: hwmon_path.clone(), temps_reader: GPUTempReader::new(&hwmon_path), } } pub fn read_status(&self) -> GPUStatus { let voltage = match self.read_gpu_status_file(&self.hwmon_path.join("in0_input")) { Ok(value) => Some(value), Err(error) => { eprintln!("Could not read voltage value!\n{}", error); None } }; let power_consumption = match self.read_gpu_status_file(&self.hwmon_path.join("power1_average")) { Ok(value) => Some(value), Err(error) => { eprintln!("Could not read power consumption value!\n{}", error); None } }; let fan_speed = match self.read_gpu_status_file(&self.hwmon_path.join("fan1_input")) { Ok(value) => Some(value), Err(error) => { eprintln!("Could not read fan speed value!\n{}", error); None } }; GPUStatus { voltage, power_consumption, fan_speed, temps: self.temps_reader.read_temps(), } } fn read_gpu_status_file<T>(&self, file_path: &PathBuf) -> Result<T, Box<dyn Error>> where T: FromStr, <T as FromStr>::Err: Error + 'static, { let file_content = fs::read_to_string(file_path)?; let value = file_content.trim().parse::<T>()?; Ok(value) } }
use crate::{root::AppRoute, services::is_authenticated}; use yew::prelude::*; use yew_router::{ agent::RouteRequest, prelude::{Route, RouteAgentDispatcher}, RouterState, }; pub struct Token<STATE: RouterState = ()> { router: RouteAgentDispatcher<STATE>, } pub enum Message { ChangeRoute(AppRoute), } impl<STATE: RouterState> Component for Token<STATE> { type Message = Message; type Properties = (); fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { if !is_authenticated() { link.send_message(Message::ChangeRoute(AppRoute::Auth)); } Self { router: RouteAgentDispatcher::new(), } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Message::ChangeRoute(route) => { let route = Route::from(route); self.router.send(RouteRequest::ChangeRoute(route)); } } true } fn change(&mut self, _props: Self::Properties) -> ShouldRender { false } fn view(&self) -> Html { html! { <></> } } }
// Copyright 2017 rust-ipfs-api Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. // use std::error::Error; use std::fs; pub const EXPECTED_API: &'static str = "expected response from API"; pub const EXPECTED_FILE: &'static str = "expected to read input file"; /// Verifies that a path points to a file that exists, and not a directory. /// pub fn verify_file(path: String) -> Result<(), String> { match fs::metadata(path) { Ok(ref metadata) if metadata.is_file() => Ok(()), Ok(_) => Err("file must not be a directory".into()), Err(e) => Err(e.description().into()), } } pub mod add; pub mod bitswap; pub mod block; pub mod bootstrap; pub mod cat; pub mod commands; pub mod config; pub mod dag; pub mod dht; pub mod diag; pub mod dns; pub mod file; pub mod files; pub mod filestore; pub mod version;
use date_tuple::DateTuple; use date_utils; use regex::Regex; use std::cmp::Ordering; use std::convert::From; use std::fmt; use std::str::FromStr; const MONTH_STRINGS: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; pub type Month = MonthTuple; /// A container for a month of a specific year. /// /// **NOTE:** MonthTuple's `m` field is zero-based (zero represents January). /// /// Only handles values between Jan 0000 and Dec 9999 (inclusive). #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub struct MonthTuple { y: u16, m: u8, } impl MonthTuple { /// Produces a new MonthTuple. /// /// Only accepts a valid month value (`0 <= m <= 11`). /// /// Only accepts a valid year value (`0 <= y <= 9999`). pub fn new(y: u16, m: u8) -> Result<MonthTuple, String> { if m <= 11 { if y <= 9999 { Ok(MonthTuple { y, m }) } else { Err(format!( "Invalid year in MonthTuple: {:?}\nYear must be <= 9999.", MonthTuple { y, m } )) } } else { Err(format!( "Invalid month in MonthTuple: {:?}\nMonth must be <= 11; Note that months are ZERO-BASED.", MonthTuple { y, m } )) } } /// Returns a `MonthTuple` of the current month according to the system clock. pub fn this_month() -> MonthTuple { date_utils::now_as_monthtuple() } pub fn get_year(&self) -> u16 { self.y } /// Retrieves the month component of the tuple. /// /// Note this month is **ZERO-BASED** (zero represents January). pub fn get_month(&self) -> u8 { self.m } /// Gets a MonthTuple representing the month immediately following /// the current one. Will not go past Dec 9999. pub fn next_month(self) -> MonthTuple { if self.y == 9999 && self.m == 11 { return self; } if self.m == 11 { MonthTuple { y: self.y + 1, m: 0, } } else { MonthTuple { y: self.y, m: self.m + 1, } } } /// Gets a MonthTuple representing the month immediately preceding /// the current one. Will not go past Jan 0000. pub fn previous_month(self) -> MonthTuple { if self.y == 0 && self.m == 0 { return self; } if self.m == 0 { MonthTuple { y: self.y - 1, m: 11, } } else { MonthTuple { y: self.y, m: self.m - 1, } } } /// Adds a number of months to a MonthTuple. pub fn add_months(&mut self, months: u32) { for _ in 0..months { *self = self.next_month(); } } /// Subtracts a number of months from a MonthTuple. pub fn subtract_months(&mut self, months: u32) { for _ in 0..months { *self = self.previous_month(); } } /// Adds a number of years to a MonthTuple. pub fn add_years(&mut self, years: u16) { let mut new_years = self.y + years; if new_years > 9999 { new_years = 9999; } self.y = new_years; } /// Subtracts a number of years from a MonthTuple. pub fn subtract_years(&mut self, years: u16) { let mut new_years = self.y as i32 - years as i32; if new_years < 0 { new_years = 0; } self.y = new_years as u16; } /// Returns the month formatted to be human-readable. /// /// ## Examples /// * Jan 2018 /// * Dec 1994 pub fn to_readable_string(&self) -> String { match MONTH_STRINGS.iter().skip(self.m as usize).next() { Some(s) => return format!("{} {:04}", s, self.y), None => panic!("Invalid MonthTuple: {:?}", self), } } } impl fmt::Display for MonthTuple { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:04}{:02}", self.y, self.m) } } impl FromStr for MonthTuple { type Err = String; fn from_str(s: &str) -> Result<MonthTuple, Self::Err> { let valid_format = Regex::new(r"^\d{6}$").unwrap(); if !valid_format.is_match(s) { Err(format!( "Invalid str formatting of MonthTuple: {}\nExpects a string formatted like 201811", s )) } else { let (s1, s2) = s.split_at(4); Ok(MonthTuple::new(u16::from_str(s1).unwrap(), u8::from_str(s2).unwrap()).unwrap()) } } } impl PartialOrd for MonthTuple { fn partial_cmp(&self, other: &MonthTuple) -> Option<Ordering> { u32::from_str(&self.to_string()) .unwrap() .partial_cmp(&u32::from_str(&other.to_string()).unwrap()) } } impl Ord for MonthTuple { fn cmp(&self, other: &MonthTuple) -> Ordering { u32::from_str(&self.to_string()) .unwrap() .cmp(&u32::from_str(&other.to_string()).unwrap()) } } impl From<DateTuple> for MonthTuple { fn from(date: DateTuple) -> Self { MonthTuple { y: date.get_year(), m: date.get_month(), } } } #[cfg(test)] mod tests { #[test] fn test_next_month() { let tuple1 = super::MonthTuple::new(2000, 5).unwrap(); let tuple2 = super::MonthTuple::new(2000, 11).unwrap(); assert_eq!(super::MonthTuple { y: 2000, m: 6 }, tuple1.next_month()); assert_eq!(super::MonthTuple { y: 2001, m: 0 }, tuple2.next_month()); } #[test] fn test_previous_month() { let tuple1 = super::MonthTuple::new(2000, 5).unwrap(); let tuple2 = super::MonthTuple::new(2000, 0).unwrap(); assert_eq!(super::MonthTuple { y: 2000, m: 4 }, tuple1.previous_month()); assert_eq!( super::MonthTuple { y: 1999, m: 11 }, tuple2.previous_month() ); } #[test] fn test_to_readable_string() { let tuple = super::MonthTuple::new(2000, 5).unwrap(); assert_eq!(String::from("Jun 2000"), tuple.to_readable_string()); } #[test] fn test_to_string() { let tuple = super::MonthTuple::new(2000, 5).unwrap(); assert_eq!(String::from("200005"), tuple.to_string()); } #[test] fn test_equals() { let tuple1 = super::MonthTuple::new(2000, 5).unwrap(); let tuple2 = super::MonthTuple::new(2000, 5).unwrap(); assert_eq!(tuple1, tuple2); } #[test] fn test_comparisons() { let tuple1 = super::MonthTuple::new(2000, 5).unwrap(); let tuple2 = super::MonthTuple::new(2000, 5).unwrap(); let tuple3 = super::MonthTuple::new(2000, 6).unwrap(); let tuple4 = super::MonthTuple::new(2001, 0).unwrap(); assert!(tuple1 <= tuple2); assert!(!(tuple1 < tuple2)); assert!(tuple1 >= tuple2); assert!(tuple1 < tuple3); assert!(tuple3 < tuple4); assert!(tuple4 > tuple2); } #[test] fn test_invalid() { if let Ok(_) = super::MonthTuple::new(2000, 12) { assert!(false) } } #[test] fn test_from_date() { let date = ::date_tuple::DateTuple::new(2000, 5, 10).unwrap(); assert_eq!( super::MonthTuple { y: 2000, m: 5 }, super::MonthTuple::from(date) ); } #[test] fn test_from_string() { let tuple = super::MonthTuple::new(2000, 5).unwrap(); assert_eq!(tuple, str::parse("200005").unwrap()); } #[test] fn test_add_months() { let mut tuple1 = super::MonthTuple::new(2000, 5).unwrap(); let tuple1_orig = super::MonthTuple::new(2000, 5).unwrap(); let mut tuple2 = super::MonthTuple::new(2000, 11).unwrap(); let tuple2_orig = super::MonthTuple::new(2000, 11).unwrap(); tuple1.add_months(1); assert_eq!(tuple1, tuple1_orig.next_month()); tuple2.add_months(2); assert_eq!(tuple2, tuple2_orig.next_month().next_month()); } #[test] fn test_subtract_months() { let mut tuple1 = super::MonthTuple::new(2000, 5).unwrap(); let tuple1_orig = super::MonthTuple::new(2000, 5).unwrap(); let mut tuple2 = super::MonthTuple::new(2000, 11).unwrap(); let tuple2_orig = super::MonthTuple::new(2000, 11).unwrap(); tuple1.subtract_months(1); assert_eq!(tuple1, tuple1_orig.previous_month()); tuple2.subtract_months(2); assert_eq!(tuple2, tuple2_orig.previous_month().previous_month()); } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ //! tests for delaying signal delivery //! SIGALRM: suppressed //! SIGVTALRM: delayed about 500ms, then delivered //! SIGSYS: delayed till next syscall. //! //! NB: restarted syscalls should not count, as syscall //! returning ERESTARTSYS could be automatically restarted use nix::sys::signal; use nix::sys::signal::Signal; use reverie::syscalls::Errno; use reverie::syscalls::Syscall; use reverie::syscalls::SyscallInfo; use reverie::syscalls::Sysno; use reverie::syscalls::Tgkill; use reverie::Error; use reverie::Guest; use reverie::Tool; use serde::Deserialize; use serde::Serialize; use tokio::time::sleep; use tokio::time::Duration; #[derive(Debug, Default, Clone)] struct LocalState; const GAP_MS: u64 = 500; #[derive(Debug, Serialize, Deserialize, Default)] struct ThreadState { sigpending: Option<i32>, injected_signal: Option<i32>, } // syscall is interrupted and may restart fn is_syscall_restarted(errno: Errno) -> bool { [ Errno::ERESTARTSYS, Errno::ERESTARTNOINTR, Errno::ERESTARTNOHAND, Errno::ERESTART_RESTARTBLOCK, ] .contains(&errno) } #[reverie::tool] impl Tool for LocalState { type GlobalState = (); type ThreadState = ThreadState; async fn handle_signal_event<T: Guest<Self>>( &self, guest: &mut T, signal: signal::Signal, ) -> Result<Option<signal::Signal>, Errno> { Ok(if signal == Signal::SIGVTALRM { sleep(Duration::from_millis(GAP_MS)).await; Some(signal) } else if signal == Signal::SIGALRM { None // Suppress the signal. } else if signal == Signal::SIGSYS { eprintln!( "[pid = {}] delay delivery of signal {:?}, thread_state {:?}", guest.tid(), signal, guest.thread_state(), ); match guest.thread_state_mut().injected_signal.take() { None => { guest.thread_state_mut().sigpending = Some(signal as i32); None } Some(sig) => { guest.thread_state_mut().sigpending = None; Some(Signal::try_from(sig).unwrap()) } } } else { println!("[pid = {}] deliverying signal {:?}", guest.tid(), signal); Some(signal) }) } async fn handle_syscall_event<T: Guest<Self>>( &self, guest: &mut T, syscall: Syscall, ) -> Result<i64, Error> { let pending = guest.thread_state().sigpending; if pending.is_some() { eprintln!( "[pid = {}] syscall {:?} pending signal {:?}", guest.tid(), syscall, pending, ); } if [ Sysno::exit_group, Sysno::exit, Sysno::execve, Sysno::execveat, ] .contains(&syscall.number()) { eprintln!("[pid = {}] tail injecting {:?}", guest.tid(), syscall); guest.tail_inject(syscall).await } else { eprintln!("[pid = {}] injecting {:?}", guest.tid(), syscall); let res = guest.inject(syscall).await; if let Some(sig) = pending { // NB: don't do signal delivery if syscall is interrupted // and restarted. if res.is_ok() || res.is_err() && is_syscall_restarted(res.unwrap_err()) { eprintln!( "[pid = {}] injecting tgkill to deliver signal {:?}", guest.tid(), sig ); let send_signal = Tgkill::new() .with_tgid(guest.pid().as_raw()) .with_tid(guest.tid().as_raw()) .with_sig(sig); guest.thread_state_mut().injected_signal = Some(sig); let _ = guest.inject(send_signal).await; } } Ok(res?) } } } #[cfg(all(not(sanitized), test))] mod tests { use std::io; use std::mem::MaybeUninit; use std::sync::mpsc; use std::thread; use std::time; use reverie::ExitStatus; use reverie_ptrace::testing::check_fn; use reverie_ptrace::testing::test_fn; use super::*; // kernel_sigset_t used by naked syscall #[derive(Clone, Copy, PartialEq, Eq, Debug)] struct KernelSigset(u64); impl From<&[Signal]> for KernelSigset { fn from(signals: &[Signal]) -> Self { let mut set: u64 = 0; for &sig in signals { set |= 1u64 << (sig as usize - 1); } KernelSigset(set) } } #[allow(dead_code)] unsafe fn block_signals(signals: &[Signal]) -> io::Result<KernelSigset> { let set = KernelSigset::from(signals); let mut oldset: MaybeUninit<u64> = MaybeUninit::uninit(); if libc::syscall( libc::SYS_rt_sigprocmask, libc::SIG_BLOCK, &set as *const _, oldset.as_mut_ptr(), 8, ) != 0 { Err(io::Error::last_os_error()) } else { Ok(KernelSigset(oldset.assume_init())) } } // unblock signal(s) and set its handler to SIG_DFL unsafe fn unblock_signals(signals: &[Signal]) -> io::Result<KernelSigset> { let set = KernelSigset::from(signals); let mut oldset: MaybeUninit<u64> = MaybeUninit::uninit(); if libc::syscall( libc::SYS_rt_sigprocmask, libc::SIG_UNBLOCK, &set as *const _, oldset.as_mut_ptr(), 8, ) != 0 { Err(io::Error::last_os_error()) } else { Ok(KernelSigset(oldset.assume_init())) } } unsafe fn restore_sig_handlers(signals: &[Signal]) -> io::Result<()> { for &sig in signals { libc::signal(sig as i32, libc::SIG_DFL); } Ok(()) } #[no_mangle] extern "C" fn sigprof_handler( _sig: i32, _siginfo: *mut libc::siginfo_t, _ucontext: *const libc::c_void, ) { nix::unistd::write(2, b"caught SIGPROF!").unwrap(); unsafe { libc::syscall(libc::SYS_exit_group, 0); } } unsafe fn install_sigprof_handler() -> i32 { let mut sa: libc::sigaction = MaybeUninit::zeroed().assume_init(); sa.sa_flags = libc::SA_RESTART | libc::SA_SIGINFO | libc::SA_NODEFER; sa.sa_sigaction = sigprof_handler as _; libc::sigaction(libc::SIGPROF, &sa as *const _, std::ptr::null_mut()) } unsafe fn sigtimedwait(signals: &[Signal], timeout_ns: u64) -> io::Result<Signal> { let mut siginfo: MaybeUninit<libc::siginfo_t> = MaybeUninit::zeroed(); let sigset = KernelSigset::from(signals); let timeout = libc::timespec { tv_sec: timeout_ns as i64 / 1000000000, tv_nsec: (timeout_ns % 1000000000) as i64, }; match Signal::try_from(libc::syscall( libc::SYS_rt_sigtimedwait, &sigset as *const _, siginfo.as_mut_ptr(), &timeout as *const _, 8, ) as i32) { Ok(sig) => { let siginfo = siginfo.assume_init(); assert_eq!(siginfo.si_signo, sig as i32); Ok(sig) } Err(_) => Err(io::Error::last_os_error()), } } unsafe fn sigsuspend(signals: &[Signal]) -> io::Result<()> { let mut set: u64 = 0; for &sig in signals { set |= 1u64 << (sig as usize - 1); } libc::syscall(libc::SYS_rt_sigsuspend, &set as *const _, 8); // always return Err. Err(io::Error::last_os_error()) } // set timer with SIGPROF as signal unsafe fn settimer(time_us: u64) -> io::Result<()> { let zero = libc::timeval { tv_sec: 0, tv_usec: 0, }; let mut next = libc::timeval { tv_sec: time_us as i64 / 1000000, tv_usec: time_us as i64 % 1000000, }; if next.tv_usec > 1000000 { next.tv_sec += 1; next.tv_usec -= 1000000; } let timer_val = libc::itimerval { it_interval: zero, it_value: next, }; if libc::syscall( libc::SYS_setitimer, libc::ITIMER_PROF, &timer_val as *const _, 0, ) != 0 { eprintln!("setitimer returned error: {:?}", io::Error::last_os_error()); Err(io::Error::last_os_error()) } else { Ok(()) } } #[test] fn signal_delay_500ms() { check_fn::<LocalState, _>(|| { assert!(unsafe { restore_sig_handlers(&[Signal::SIGVTALRM]) }.is_ok()); assert!(unsafe { unblock_signals(&[Signal::SIGVTALRM]) }.is_ok()); unsafe { libc::signal(libc::SIGVTALRM, libc::SIG_IGN) }; let now = time::Instant::now(); thread::sleep(time::Duration::from_millis(10)); assert!(signal::raise(Signal::SIGVTALRM).is_ok()); assert!(now.elapsed().as_millis() >= GAP_MS as u128 + 10); }); } #[test] // signal is suppressed by handle_signal_event fn signal_suppress() { check_fn::<LocalState, _>(|| { assert!(unsafe { restore_sig_handlers(&[Signal::SIGALRM]) }.is_ok()); assert!(unsafe { unblock_signals(&[Signal::SIGALRM]) }.is_ok()); let now = time::Instant::now(); thread::sleep(time::Duration::from_millis(10)); assert!(signal::raise(Signal::SIGALRM).is_ok()); assert!(now.elapsed().as_millis() < GAP_MS as u128); }); } #[test] fn sigtimedwait_sanity() { check_fn::<LocalState, _>(|| { let (sender, receiver) = mpsc::channel(); let handle = thread::spawn(move || { assert!(sender.send(nix::unistd::gettid()).is_ok()); unsafe { libc::signal(libc::SIGBUS, libc::SIG_DFL) }; assert_eq!( unsafe { sigtimedwait(&[Signal::SIGBUS], 1000000000000u64) }.unwrap(), Signal::SIGBUS, ); eprintln!("[thread] sigtimedwait returned SIGBUS"); }); let thread_id = receiver.recv().unwrap(); // wait until thread is blocked by rt_sigtimedwait.. thread::sleep(Duration::from_millis(500)); let signal_sent = unsafe { libc::syscall(libc::SYS_tkill, thread_id.as_raw(), Signal::SIGBUS as i32) }; assert_eq!(signal_sent, 0); assert!(handle.join().is_ok()); }); } #[test] fn sigsuspend_sanity() { let (output, _) = test_fn::<LocalState, _>(|| { let (sender, receiver) = mpsc::channel(); let handle = thread::spawn(move || { assert!(sender.send(nix::unistd::gettid()).is_ok()); unsafe { libc::signal(libc::SIGBUS, libc::SIG_DFL) }; assert_eq!( unsafe { sigsuspend(&[]) } .err() .and_then(|e| e.raw_os_error()), Some(libc::EINTR) ); }); let thread_id = receiver.recv().unwrap(); // wait until thread is blocked by rt_sigtimedwait.. thread::sleep(Duration::from_millis(500)); let signal_sent = unsafe { libc::syscall(libc::SYS_tkill, thread_id.as_raw(), Signal::SIGBUS as i32) }; assert_eq!(signal_sent, 0); assert!(handle.join().is_ok()); }) .unwrap(); assert_eq!(output.status, ExitStatus::Signaled(Signal::SIGBUS, true)); } #[test] // A sanity check ITIMER_PROF can indeed cause program to exit with SIGPROF // NB: rust runtime masks most signals, hence SIGPROF has to be explicitly // unmasked. fn sigprof_sanity() { check_fn::<LocalState, _>(|| { assert_eq!(unsafe { install_sigprof_handler() }, 0); // timer should expire assert!(unsafe { unblock_signals(&[Signal::SIGPROF]) }.is_ok()); assert!(unsafe { settimer(100000) }.is_ok()); loop {} }); } #[test] // SIGSYS is delayed till next syscall is trapped. However, since we send // SIGSYS when rt_sigsuspend is called, rt_sigsuspend won't return because // the signal is delayed till next syscall. Which causes this test to timeout // pease note this is expected behavior. Showing we cannot assume signal // delivery can be always delayed. fn sigsuspend_delay_till_next_syscall_should_timeout_1() { check_fn::<LocalState, _>(|| { let (sender, receiver) = mpsc::channel(); let _handle = thread::spawn(move || { assert!(sender.send(nix::unistd::gettid()).is_ok()); unsafe { libc::signal(libc::SIGSYS, libc::SIG_DFL) }; assert_eq!( unsafe { sigsuspend(&[Signal::SIGPROF, Signal::SIGVTALRM]) } .err() .and_then(|e| e.raw_os_error()), Some(libc::EINTR) ); }); let thread_id = receiver.recv().unwrap(); // wait until thread is blocked by rt_sigtimedwait.. thread::sleep(Duration::from_millis(500)); let signal_sent = unsafe { libc::syscall(libc::SYS_tkill, thread_id.as_raw(), Signal::SIGSYS as i32) }; assert_eq!(signal_sent, 0); assert!(unsafe { restore_sig_handlers(&[Signal::SIGPROF, Signal::SIGVTALRM]) }.is_ok()); assert_eq!(unsafe { install_sigprof_handler() }, 0); // timer should expire assert!(unsafe { unblock_signals(&[Signal::SIGPROF, Signal::SIGVTALRM]) }.is_ok()); assert!(unsafe { settimer(500000) }.is_ok()); loop { /* sigprof handler calls exit_group */ } }); } #[test] // similar to sigsuspend_delay_till_next_syscall_should_timeout_1, but this test // only has one line difference compare to sigsuspend_delay_till_next_syscall_should_pass // to emphasis SIGSYS is indeeded not delivered without the extra syscall after tgkill. // because we delay SIGSYS delivery to next syscall. fn sigsuspend_delay_till_next_syscall_should_timeout_2() { check_fn::<LocalState, _>(|| { let (sender, receiver) = mpsc::channel(); let _handle = thread::spawn(move || { let tid = nix::unistd::gettid(); let pid = nix::unistd::getpid(); assert!(sender.send(tid).is_ok()); unsafe { libc::signal(libc::SIGSYS, libc::SIG_DFL); }; // block SIGPROF as the parent task is setting up a timer // with ITIMER_PROF. Linux does not guarantee which thread // receive the signal. As a result, we simply mask SIGPROF // in this thread, so that only parent task can receive it. assert!(unsafe { block_signals(&[Signal::SIGPROF]) }.is_ok()); assert!(unsafe { unblock_signals(&[Signal::SIGSYS]) }.is_ok()); assert_eq!( unsafe { sigtimedwait(&[Signal::SIGSYS], 1000_000_000) }.ok(), Some(Signal::SIGSYS) ); unsafe { libc::syscall( libc::SYS_tgkill, pid.as_raw(), tid.as_raw(), Signal::SIGSYS as i32, ); // expected to timeout, because we delay signal delivery to next // syscall which returns success loop {} } }); let thread_id = receiver.recv().unwrap(); // wait until thread is blocked by rt_sigtimedwait.. thread::sleep(Duration::from_millis(100)); let signal_sent = unsafe { libc::syscall(libc::SYS_tkill, thread_id.as_raw(), Signal::SIGSYS as i32) }; assert_eq!(signal_sent, 0); assert!(unsafe { restore_sig_handlers(&[Signal::SIGPROF, Signal::SIGVTALRM]) }.is_ok()); assert_eq!(unsafe { install_sigprof_handler() }, 0); // timer should expire assert!(unsafe { unblock_signals(&[Signal::SIGPROF, Signal::SIGVTALRM]) }.is_ok()); assert!(unsafe { settimer(500000) }.is_ok()); loop {} }); } #[test] // since we delay SIGSYS till next syscall, adding a syscall like getsid should // cause SIGSYS to be delivered, hence the program should be killed by SIGSYS. fn sigsuspend_delay_till_next_syscall_should_pass() { let (output, _) = test_fn::<LocalState, _>(|| { let (sender, receiver) = mpsc::channel(); let _handle = thread::spawn(move || { let tid = nix::unistd::gettid(); let pid = nix::unistd::getpid(); assert!(sender.send(tid).is_ok()); unsafe { libc::signal(libc::SIGSYS, libc::SIG_DFL); }; assert!(unsafe { unblock_signals(&[Signal::SIGSYS]) }.is_ok()); assert_eq!( unsafe { sigtimedwait(&[Signal::SIGSYS], 1000_000_000) }.ok(), Some(Signal::SIGSYS) ); unsafe { libc::syscall( libc::SYS_tgkill, pid.as_raw(), tid.as_raw(), Signal::SIGSYS as i32, ); // signal should delivered after SYS_getsid returned // hence the program should be killed by SIGSYS libc::syscall(libc::SYS_getsid); // will run into SIGSYS handler (SIG_DFL) hence below // statement is not reachable. unreachable!() } }); let thread_id = receiver.recv().unwrap(); // wait until thread is blocked by rt_sigtimedwait.. thread::sleep(Duration::from_millis(100)); let signal_sent = unsafe { libc::syscall(libc::SYS_tkill, thread_id.as_raw(), Signal::SIGSYS as i32) }; assert_eq!(signal_sent, 0); assert!(unsafe { restore_sig_handlers(&[Signal::SIGPROF, Signal::SIGVTALRM]) }.is_ok()); assert_eq!(unsafe { install_sigprof_handler() }, 0); assert!(unsafe { unblock_signals(&[Signal::SIGPROF, Signal::SIGVTALRM]) }.is_ok()); assert!(unsafe { settimer(500000) }.is_ok()); // SIGSYS handler (SIG_DFL) should be called before timer expire unreachable!() }) .unwrap(); assert_eq!(output.status, ExitStatus::Signaled(Signal::SIGSYS, true)); } }
use atty::Stream; use color_eyre::{Help, Report}; use csv::Reader; use dialoguer::Confirm; use std::process; use std::{fs::File, fs::OpenOptions, io, path::PathBuf}; use tracing::instrument; use crate::{ cli::args::{MultipleReports, SingleReport}, BinError, }; pub mod abundance_csv; pub mod newick; pub mod report; /* ---------------------------------- Input --------------------------------- */ custom_derive! { #[derive(clap::Clap, Debug, PartialEq)] #[derive(EnumFromStr, EnumDisplay)] pub enum InputReportFormat { Kraken, } } #[instrument] pub fn get_reader(input: &PathBuf, headers: bool) -> Result<Reader<File>, csv::Error> { csv::ReaderBuilder::new() .has_headers(headers) .delimiter(b'\t') .double_quote(false) .flexible(true) .from_path(input) } impl SingleReport { #[instrument] pub fn open_report(&self) -> Result<File, BinError> { let path = &self.path; open_file(path) } } impl MultipleReports { fn join_errors(errors: Vec<Result<File, BinError>>) -> Result<(), Report> { if errors.is_empty() { return Ok(()); } errors .into_iter() .filter_map(|result| { if let Err(error) = result { Some(error) } else { None } }) .fold(Err(eyre!("encountered multiple errors")), |report, e| { report.error(e) }) } #[instrument] pub fn open_reports(&self) -> Result<Vec<File>, Report> { let readers: Vec<Result<File, BinError>> = self.paths.iter().map(|p| open_file(p)).collect(); let (ok, errors) = readers.into_iter().partition(Result::is_ok); Self::join_errors(errors)?; Ok(ok.into_iter().map(Result::unwrap).collect::<Vec<File>>()) } } #[instrument] pub fn open_file(path: &PathBuf) -> Result<File, BinError> { let path = path; OpenOptions::new() .read(true) .write(false) .open(path) .map_err(|err| BinError::Io { err, path: path.clone(), }) } /* --------------------------------- OUTPUT --------------------------------- */ custom_derive! { #[derive(clap::Clap, Debug, PartialEq)] #[derive(EnumFromStr, EnumDisplay)] pub enum OutputPhyloFormat { Newick, } } custom_derive! { #[derive(clap::Clap, Debug, PartialEq)] #[derive(EnumFromStr, EnumDisplay)] pub enum OutputAbundanceFormat { Csv, } } #[derive(Debug, Clone)] pub enum OutputKind { File(PathBuf), Stdout, } #[derive(Debug, Clone)] pub struct Output { pub kind: OutputKind, pub overwrite: bool, } impl From<Option<PathBuf>> for OutputKind { fn from(path: Option<PathBuf>) -> Self { path.map_or(Self::Stdout, |p| { if p == PathBuf::from(r"-") { Self::Stdout } else { Self::File(p) } }) } } impl From<crate::cli::args::OutputFile> for Output { fn from(clap_output: crate::cli::args::OutputFile) -> Self { Self { kind: OutputKind::from(clap_output.path), overwrite: clap_output.overwrite, } } } impl Output { pub fn try_writtable(&self) -> Result<(), Report> { #[instrument] fn internal_can_open_file(path: &PathBuf, overwrite: bool) -> Result<(), Report> { if path.exists() { if overwrite { } else if atty::is(Stream::Stdout) { if Confirm::new() .with_prompt(format!("Overwrite `{}`?", path.display())) .interact()? { } else { process::exit(exitcode::NOPERM); } } else { { Err(std::io::Error::new( std::io::ErrorKind::AlreadyExists, "File already exists", )) }? } } Ok(()) } match &self.kind { OutputKind::File(path) => internal_can_open_file(path, self.overwrite), OutputKind::Stdout => Ok(()), } } pub fn writer(&self) -> Result<Box<dyn io::Write>, Report> { match &self.kind { OutputKind::File(path) => Ok(Box::new( OpenOptions::new() .write(true) .truncate(true) .create(true) .open(path)?, ) as Box<dyn io::Write>), OutputKind::Stdout => Ok(Box::new(io::stdout()) as Box<dyn io::Write>), } } }
use clap::{App, Arg, ArgMatches, SubCommand}; use std::process; mod mix_peer; mod node; fn main() { let arg_matches = App::new("Nym Mixnode") .version("0.1.0") .author("Nymtech") .about("Implementation of the Loopix-based Mixnode") .subcommand( SubCommand::with_name("run") .about("Starts the mixnode") .arg( Arg::with_name("host") .long("host") .help("The custom host on which the mixnode will be running") .takes_value(true), ) .arg( Arg::with_name("port") .long("port") .help("The port on which the mixnode will be listening") .takes_value(true) ) .arg( Arg::with_name("layer") .long("layer") .help("The mixnet layer of this particular node") .takes_value(true) .required(true), ) .arg( Arg::with_name("local") .long("local") .help("Flag to indicate whether the client is expected to run on a local deployment.") .takes_value(false), ), ) .get_matches(); if let Err(e) = execute(arg_matches) { println!("{}", e); process::exit(1); } } fn execute(matches: ArgMatches) -> Result<(), String> { match matches.subcommand() { ("run", Some(m)) => Ok(node::runner::start(m)), _ => Err(usage()), } } fn usage() -> String { banner() + "usage: --help to see available options.\n\n" } fn banner() -> String { return r#" _ __ _ _ _ __ ___ | '_ \| | | | '_ \ _ \ | | | | |_| | | | | | | |_| |_|\__, |_| |_| |_| |___/ (mixnode) "# .to_string(); }
use async_trait::async_trait; use uuid::Uuid; use common::cache::Cache; use common::error::Error; use common::infrastructure::cache::InMemCache; use common::result::Result; use crate::domain::reader::{Reader, ReaderId, ReaderRepository}; use crate::mocks; pub struct InMemReaderRepository { cache: InMemCache<ReaderId, Reader>, } impl InMemReaderRepository { pub fn new() -> Self { InMemReaderRepository { cache: InMemCache::new(), } } pub async fn reader() -> Self { let repo = Self::new(); repo.save(&mut mocks::reader1()).await.unwrap(); repo.save(&mut mocks::author_as_reader1()).await.unwrap(); repo } } impl Default for InMemReaderRepository { fn default() -> Self { Self::new() } } #[async_trait] impl ReaderRepository for InMemReaderRepository { async fn next_id(&self) -> Result<ReaderId> { let id = Uuid::new_v4(); ReaderId::new(id.to_string()) } async fn find_by_id(&self, id: &ReaderId) -> Result<Reader> { self.cache .get(id) .await .ok_or(Error::new("reader", "not_found")) } async fn save(&self, reader: &mut Reader) -> Result<()> { self.cache .set(reader.base().id().clone(), reader.clone()) .await } }
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> extern crate googl; use std::env::{args}; use std::fs::{File}; use std::io::{Read}; use std::path::{Path}; fn main() { let longurl = args().nth(1).unwrap(); let mut file = File::open(&Path::new("key.txt")).unwrap(); let mut key = String::new(); file.read_to_string(&mut key).unwrap(); println!("{:?}", googl::shorten(&key, &longurl)); }
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{context::Context, filters}; use diem_genesis_tool::validator_builder::ValidatorBuilder; use diem_temppath::TempPath; use diem_types::chain_id::ChainId; use diem_vm::DiemVM; use diemdb::DiemDB; use executor::db_bootstrapper; use storage_interface::DbReaderWriter; use serde_json::{json, Value}; #[tokio::test] async fn test_get_ledger_info() { let context = new_test_context(); let filter = filters::routes(context.clone()); let resp = warp::test::request() .method("GET") .path("/") .reply(&filter) .await; assert_eq!(resp.status(), 200); let ledger_info = context.get_latest_ledger_info().unwrap(); let ledger_version = ledger_info.ledger_info().version(); let ledger_timestamp = ledger_info.ledger_info().timestamp_usecs(); assert_eq!( serde_json::from_slice::<Value>(resp.body()).unwrap(), json!({ "chain_id": 4, "ledger_version": ledger_version.to_string(), "ledger_timestamp": ledger_timestamp.to_string(), }) ); } pub fn new_test_context() -> Context { let tmp_dir = TempPath::new(); tmp_dir.create_as_dir().unwrap(); let rng = rand::thread_rng(); let builder = ValidatorBuilder::new( &tmp_dir, diem_framework_releases::current_module_blobs().to_vec(), ); let (_root_keys, genesis, genesis_waypoint, _validators) = builder.build(rng).unwrap(); let (db, db_rw) = DbReaderWriter::wrap(DiemDB::new_for_test(&tmp_dir)); db_bootstrapper::maybe_bootstrap::<DiemVM>(&db_rw, &genesis, genesis_waypoint).unwrap(); Context::new(ChainId::test(), db) }
use crate::dna::{Base, DNA}; /// The `dna` value is consumed since the implementation does not follow the /// specification about mutation of `dna` in the step where the program ends. pub fn execute(mut dna: DNA, mut rna_sink: impl FnMut(DNA)) { // TODO: these lines are just for testing. Remove soon. rna_sink("ICFPICFPI".into()); rna_sink("CFPICFPIC".into()); while step(&mut dna, &mut rna_sink).is_ok() { // do nothing } } #[derive(Clone, Copy, PartialEq, Eq, Debug)] struct Finish; #[derive(Clone, PartialEq, Eq, Debug)] enum PItem { Base(Base), Skip(usize), Search(DNA), Open(), Close(), } type Pattern = Vec<PItem>; #[derive(Clone, PartialEq, Eq, Debug)] enum TItem { Base(Base), Ref { n: usize, l: usize }, RefLen(usize), } type Template = Vec<TItem>; fn step(dna: &mut DNA, rna_sink: &mut dyn FnMut(DNA)) -> Result<(), Finish> { let p = pattern(dna, rna_sink)?; let t = template(dna, rna_sink)?; matchreplace(dna, p, t); Ok(()) } /// May leave `dna` inconsistent when EOF reached fn pattern(mut dna: &mut DNA, rna_sink: &mut dyn FnMut(DNA)) -> Result<Pattern, Finish> { let mut p = vec![]; // TODO: avoid allocation? let mut lvl: usize = 0; loop { match dna.pop() { Some(Base::C) => p.push(PItem::Base(Base::I)), Some(Base::F) => p.push(PItem::Base(Base::C)), Some(Base::P) => p.push(PItem::Base(Base::F)), Some(Base::I) => match dna.pop() { Some(Base::C) => p.push(PItem::Base(Base::P)), Some(Base::P) => { let n = nat(&mut dna)?; p.push(PItem::Skip(n)); } Some(Base::F) => { dna.pop(); // quirk of the specification let s = consts(&mut dna); p.push(PItem::Search(s)); } Some(Base::I) => match dna.pop() { Some(Base::P) => { lvl += 1; p.push(PItem::Open()) } Some(Base::C) | Some(Base::F) => { if lvl == 0 { return Ok(p); } else { lvl = lvl - 1; p.push(PItem::Close()); } } Some(Base::I) => { rna_sink(dna.subseq(0, 7)); dna.drop(7); } None => break, }, None => break, }, None => break, } } Err(Finish) } /// MSB is last fn nat(dna: &mut DNA) -> Result<usize, Finish> { let mut shiftcount = 0; let mut acc = 0; while let Some(b) = dna.pop() { match b { Base::P => return Ok(acc), Base::I | Base::F => (), // `|=` with 0 is a no-op Base::C => acc |= (1 << shiftcount), } shiftcount += 1; } Err(Finish) } fn consts(dna: &mut DNA) -> DNA { let mut acc = DNA::default(); while let Some(b) = dna.pop() { match b { Base::C => acc.append(Base::I), Base::F => acc.append(Base::C), Base::P => acc.append(Base::F), Base::I => match dna.pop() { Some(Base::C) => acc.append(Base::P), Some(b) => { // Went too far by two dna.prepend(b); dna.prepend(Base::I); return acc; } None => { // Went too far by one dna.prepend(Base::I); return acc; } }, } } acc } /// May leave `dna` inconsistent when EOF reached fn template(mut dna: &mut DNA, rna_sink: &mut dyn FnMut(DNA)) -> Result<Template, Finish> { let mut t = vec![]; // TODO: avoid allocation? loop { match dna.pop() { Some(Base::C) => t.push(TItem::Base(Base::I)), Some(Base::F) => t.push(TItem::Base(Base::C)), Some(Base::P) => t.push(TItem::Base(Base::F)), Some(Base::I) => match dna.pop() { Some(Base::C) => t.push(TItem::Base(Base::P)), Some(Base::F) | Some(Base::P) => { let l = nat(&mut dna)?; let n = nat(&mut dna)?; t.push(TItem::Ref { n, l }); } Some(Base::I) => match dna.pop() { Some(Base::C) | Some(Base::F) => return Ok(t), Some(Base::P) => { let n = nat(&mut dna)?; t.push(TItem::RefLen(n)); } Some(Base::I) => { rna_sink(dna.subseq(0, 7)); dna.drop(7); } None => break, }, None => break, }, None => break, } } Err(Finish) } fn matchreplace(mut dna: &mut DNA, pattern: Pattern, template: Template) { let mut i : usize = 0; let mut env : Vec<DNA> = vec![]; let mut c_rev : Vec<usize> = vec![]; for p in pattern { match p { PItem::Base(b) => { if dna.at(i) == Some(b) { i += 1 } else { return } }, PItem::Skip(n) => { i += n; if i > dna.len() { return } }, PItem::Search(s) => { match dna.find_first(&s, i) { None => return, Some(idx) => i = idx, } }, PItem::Open() => { c_rev.push(i) }, PItem::Close() => { let from = c_rev.pop().expect("Closing an unopened group"); env.push(dna.subseq(from, i)) } } } let mut r = replace(template, env); let tail = dna.subseq(i, dna.len()); dna.assign(r); dna.concat(tail) } fn replace(template: Template, env : Vec<DNA>) -> DNA { let mut r = DNA::default(); for t in template { match t { TItem::Base(b) => r.append(b), TItem::Ref{n, l} => { r.concat(protect(l, env[n].clone())) }, TItem::RefLen(n) => { r.concat(asnat(env[n].len())) } } } r } fn protect(l: usize, d: DNA) -> DNA { if l == 0 { d } else { protect(l-1, quote(d)) } } fn quote(d: DNA) -> DNA { let mut r = DNA::default(); for b in d { match b { Base::I => r.append(Base::C), Base::C => r.append(Base::F), Base::F => r.append(Base::P), Base::P => { r.append(Base::I); r.append(Base::C) } } } r } mod jonas_matchreplace { use super::*; type Environment = Vec<DNA>; fn matchreplace(mut dna: &mut DNA, pat: Pattern, t: Template) { // TODO: it's inefficient to use `i`: we're traversing `dna` left to right // but without the benefit of amortization. let mut i = 0; let mut e: Environment = vec![]; let mut c_rev: Vec<usize> = vec![]; for p in pat { match p { PItem::Base(b) => { if dna.at(i) == Some(b) { i += 1; } else { return; } } PItem::Skip(n) => { i += n; if i > dna.len() { return; } } PItem::Search(s) => match dna.find_first_jonas(&s, i) { Some(n) => i = n, None => return, }, PItem::Open() => c_rev.push(i), PItem::Close() => { // The `c_rev` stack must be non-empty, or the spec is meaningless let head = c_rev.pop().unwrap(); e.push(dna.subseq(head, i)); } } } dna.drop(i); replace(dna, t, e); } fn replace(mut dna: &mut DNA, tpl: Template, e: Environment) { let mut r = DNA::default(); for t in tpl { match t { TItem::Base(b) => r.append(b), TItem::Ref { n, l } => { if let Some(en) = e.get(n) { r.concat(protect(l, en.clone())); } // If `n` is out of bounds, `en` conceptually becomes the empty // DNA sequence, which is empty when protected. } TItem::RefLen(n) => { let len = e.get(n).map_or_else(|| 0, |s| s.len()); r.concat(asnat(len)); } } } } fn protect(mut l: usize, mut d: DNA) -> DNA { for _ in 0 .. l { d = quote(d); } d } fn quote(mut d: DNA) -> DNA { let mut result = DNA::default(); while let Some(b) = d.pop() { match b { Base::I => result.append(Base::C), Base::C => result.append(Base::F), Base::F => result.append(Base::P), Base::P => { result.append(Base::I); result.append(Base::C); } } } result } // TODO: instead of creating a new DNA fragment, appending to an existing one // might be faster. fn asnat(mut n: usize) -> DNA { let mut result = DNA::default(); while n > 0 { result.append(if n % 2 == 0 { Base::I } else { Base::C }); n /= 2; } result.append(Base::P); result } #[cfg(test)] mod test { use super::*; #[test] fn test_asnat_jonas() { assert_eq!(asnat(5), "CICP".into()); assert_eq!(asnat(0), "P".into()); assert_eq!(asnat(1), "CP".into()); assert_eq!(asnat(2), "ICP".into()); // Test that `asnat` is the right inverse of `nat` for i in 0 .. 10 { let mut dna = asnat(i); assert_eq!(nat(&mut dna), Ok(i)); assert_eq!(dna, "".into()); } } } } fn asnat(mut n: usize) -> DNA { let mut r = DNA::default(); while n > 0 { if n % 2 == 0 { // Even r.append(Base::I); } else { r.append(Base::C); } n /= 2; } r.append(Base::P); r } #[cfg(test)] mod test { use super::*; #[test] fn test_nat() { assert_eq!(nat(&mut "P".into()), Ok(0)); assert_eq!(nat(&mut "IP".into()), Ok(0)); assert_eq!(nat(&mut "CP".into()), Ok(1)); assert_eq!(nat(&mut "ICFCP".into()), Ok(2 | 8)); assert_eq!(nat(&mut "ICFCIIIIP".into()), Ok(2 | 8)); assert_eq!(nat(&mut "CIICICP".into()), Ok(1 | 8 | 32)); } #[test] fn test_consts() { assert_eq!(consts(&mut "".into()), "".into()); let mut dna = "CFPIC".into(); assert_eq!(consts(&mut dna), "ICFP".into()); assert_eq!(dna, "".into()); // Test replacement of one base let mut dna = "CFI".into(); assert_eq!(consts(&mut dna), "IC".into()); assert_eq!(dna, "I".into()); // Test replacement of two bases at EOF let mut dna = "CFIF".into(); assert_eq!(consts(&mut dna), "IC".into()); assert_eq!(dna, "IF".into()); // Test replacement of two bases before EOF let mut dna = "CFIPC".into(); assert_eq!(consts(&mut dna), "IC".into()); assert_eq!(dna, "IPC".into()); } fn noop(_: DNA) {} #[test] fn test_pattern() { // Test 1 from spec assert_eq!( pattern(&mut "CIIC".into(), &mut noop), Ok(vec![PItem::Base(Base::I)]) ); // Test 2 from spec assert_eq!( pattern(&mut "IIP IPICP IIC IC IIF".into(), &mut noop), Ok(vec![ PItem::Open(), PItem::Skip(2), PItem::Close(), PItem::Base(Base::P) ]) ); // The IF pattern item is always followed by a base that's ignored. Then // comes a sequence of escaped bases followed by I[IFP] as a terminator, // which doubles as the start of the next pattern item! assert_eq!( pattern(&mut "IFC() IP(P) IIF".into(), &mut noop), Ok(vec![PItem::Search("".into()), PItem::Skip(0)]) ); // Same example as above but with non-trivial literals. assert_eq!( pattern(&mut "IFI(C F P IC) IP(CP) IIF".into(), &mut noop), Ok(vec![PItem::Search("ICFP".into()), PItem::Skip(1)]) ); let mut rna = vec![]; let t = pattern(&mut "P III(ICFPICF) IC IIC".into(), &mut |x| rna.push(x)); assert_eq!(t, Ok(vec![PItem::Base(Base::F), PItem::Base(Base::P)])); assert_eq!(rna, vec!["ICFPICF".into()]); } #[test] fn test_template() { assert_eq!(template(&mut "".into(), &mut noop), Err(Finish)); assert_eq!( template(&mut "IF(P,CP) IIP(ICP) IIF".into(), &mut noop), Ok(vec![TItem::Ref { l: 0, n: 1 }, TItem::RefLen(2)]) ); let mut rna = vec![]; let t = template(&mut "C III(ICFPICF) F IIC".into(), &mut |x| rna.push(x)); assert_eq!(t, Ok(vec![TItem::Base(Base::I), TItem::Base(Base::C)])); assert_eq!(rna, vec!["ICFPICF".into()]); } #[test] fn test_asnat() { assert_eq!(nat(&mut asnat(0)), Ok(0)); assert_eq!(nat(&mut asnat(1)), Ok(1)); assert_eq!(nat(&mut asnat(2)), Ok(2)); assert_eq!(nat(&mut asnat(9)), Ok(9)); assert_eq!(nat(&mut asnat(9384)), Ok(9384)); } #[test] fn test_quote() { assert_eq!(quote("ICFP".into()), "CFPIC".into()); assert_eq!(quote("IICCFFPP".into()), "CCFFPPICIC".into()); } #[test] fn test_protect() { assert_eq!(protect(0, "ICFP".into()), "ICFP".into()); let l1 = protect(1, "ICFP".into()); assert_eq!(l1, "CFPIC".into()); assert_eq!(protect(2, "ICFP".into()), protect(1, l1)); assert_eq!(protect(2, "ICFP".into()), "FPICCF".into()); } #[test] fn test_step() { let mut dna : DNA = "IIPIPICPIICICIIFICCIFPPIICCFPC".into(); let mut rna_sink = |rna| (); step(&mut dna, &mut rna_sink); assert_eq!(dna, "PICFC".into()); let mut dna : DNA = "IIPIPICPIICICIIFICCIFCCCPPIICCFPC".into(); let mut rna_sink = |rna| (); step(&mut dna, &mut rna_sink); assert_eq!(dna, "PIICCFCFFPC".into()); let mut dna : DNA = "IIPIPIICPIICIICCIICFCFC".into(); let mut rna_sink = |rna| (); step(&mut dna, &mut rna_sink); assert_eq!(dna, "I".into()); } }
#[macro_use] extern crate criterion; use criterion::{BatchSize, Criterion}; use hacspec_dev::rand::random_byte_vec; use hacspec_gf128::*; use hacspec_lib::prelude::*; fn benchmark(c: &mut Criterion) { c.bench_function("GCM", |b| { b.iter_batched( || { let key = Gf128Key::from_public_slice(&random_byte_vec(16)); let data = ByteSeq::from_public_slice(&random_byte_vec(1_000)); (data, key) }, |(data, key)| { let _tag = gmac(&data, key); }, BatchSize::SmallInput, ) }); } criterion_group!(benches, benchmark); criterion_main!(benches);
extern crate ph; fn main() { ph::start(); }
use std::sync::atomic::{AtomicUsize, Ordering}; use crate::config::config; use crate::coroutine_impl::CoroutineImpl; use crossbeam::queue::SegQueue; use generator::Gn; /// the raw coroutine pool, with stack and register prepared /// you need to tack care of the local storage pub struct CoroutinePool { // the pool must support mpmc operation! pool: SegQueue<CoroutineImpl>, size: AtomicUsize, } impl CoroutinePool { fn create_dummy_coroutine() -> CoroutineImpl { Gn::new_opt(config().get_stack_size(), move || { unreachable!("dummy coroutine should never be called"); }) } pub fn new() -> Self { let capacity = config().get_pool_capacity(); let pool = SegQueue::new(); for _ in 0..capacity { let co = Self::create_dummy_coroutine(); pool.push(co); } let size = AtomicUsize::new(capacity); CoroutinePool { pool, size } } /// get a raw coroutine from the pool #[inline] pub fn get(&self) -> CoroutineImpl { self.size.fetch_sub(1, Ordering::AcqRel); match self.pool.pop() { Some(co) => co, None => { self.size.fetch_add(1, Ordering::AcqRel); Self::create_dummy_coroutine() } } } /// put a raw coroutine into the pool #[inline] pub fn put(&self, co: CoroutineImpl) { // discard the co if push failed let m = self.size.fetch_add(1, Ordering::AcqRel); if m >= config().get_pool_capacity() { self.size.fetch_sub(1, Ordering::AcqRel); return; } self.pool.push(co); } }
use crate::util::Point2; #[derive(Debug, Clone, Copy)] pub enum Identifier { Empty = 0, Wall = 1, Block = 2, Paddle = 3, Ball = 4, } impl From<i64> for Identifier { fn from(o: i64) -> Self { match o { 0 => Identifier::Empty, 1 => Identifier::Wall, 2 => Identifier::Block, 3 => Identifier::Paddle, 4 => Identifier::Ball, wrong => panic!("invalid input {} for Identifier::from", wrong), } } } #[derive(Debug, Clone, Copy)] pub struct Tile { position: Point2, id: Identifier, } #[derive(Debug, Clone, Copy)] pub enum JoystickPosition { Left = -1, Neutral = 0, Right = 1, } #[cfg(test)] mod tests { use super::*; use crate::intcode::{Intcode, Interrupt}; use crate::util; use crate::util::ListInput; #[test] fn test_advent_puzzle() { let mut score = None; let ListInput(rom) = util::load_input_file("day13.txt").unwrap(); let mut program = Intcode::new(&rom); let mut tile_position_buffer: [Option<i32>; 2] = [None, None]; let mut ball: Option<Tile> = None; let mut paddle: Option<Tile> = None; program.set_address(0, 2); loop { match program.run() { Interrupt::WaitingForInput => { let joystick = match (ball, paddle) { (Some(b), Some(p)) if b.position.x < p.position.x => JoystickPosition::Left, (Some(b), Some(p)) if b.position.x > p.position.x => { JoystickPosition::Right } (Some(b), Some(p)) if b.position.x == p.position.x => { JoystickPosition::Neutral } _ => JoystickPosition::Neutral, }; program.set_input(joystick as i64) } Interrupt::Output(o) => { if tile_position_buffer[0] == None { tile_position_buffer[0] = Some(o as i32); } else if tile_position_buffer[1] == None { tile_position_buffer[1] = Some(o as i32); } else if tile_position_buffer[0] == Some(-1) && tile_position_buffer[1] == Some(0) { score = Some(o); tile_position_buffer = [None, None]; } else { let tile = Tile { position: Point2::new( tile_position_buffer[0].unwrap(), tile_position_buffer[1].unwrap(), ), id: Identifier::from(o), }; match tile.id { Identifier::Paddle => paddle = Some(tile), Identifier::Ball => ball = Some(tile), _ => {} } tile_position_buffer = [None, None]; } } _ => break, } } assert_eq!(score, Some(11991)); } }
use specs::{self, Component}; use components::InitFromBlueprint; #[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)] pub enum Faction { Neutral, Player, Enemy, } impl Default for Faction { fn default() -> Self { Faction::Neutral } } impl Component for Faction { type Storage = specs::VecStorage<Self>; } impl InitFromBlueprint for Faction {}
use { crate::hdl_reactor::HdlReactor, crate::models::internal_action, crate::state::State, crate::xlibwrapper::DisplayServer, crate::xlibwrapper::{action, xlibmodels::*}, reducer::*, std::rc::Rc, std::sync::mpsc::*, x11_dl::xlib, }; pub fn run(xlib: Box<Rc<dyn DisplayServer>>, sender: Sender<bool>) { let (tx, rx) = channel::<internal_action::InternalAction>(); let state = State::new(xlib.clone(), tx.clone()); let mut store = Store::new(state, HdlReactor::new(xlib.clone(), tx)); //setup xlib.grab_server(); let _ = xlib.get_top_level_windows().iter().map(|w| { store.dispatch(action::MapRequest { win: *w, parent: xlib.get_root(), }); }); xlib.ungrab_server(); let _ = sender.send(true); loop { let xevent = xlib.next_event(); // debug!("Event: {:?}", xevent); match xevent.get_type() { xlib::ConfigureRequest => { let event = xlib::XConfigureRequestEvent::from(xevent); let window_changes = WindowChanges { x: event.x, y: event.y, width: event.width, height: event.height, border_width: event.border_width, sibling: event.above, stack_mode: event.detail, }; store.dispatch(action::ConfigurationRequest { win: event.window, win_changes: window_changes, value_mask: event.value_mask, parent: event.parent, }) } xlib::MapRequest => { let event = xlib::XMapRequestEvent::from(xevent); /*debug!( "window type: {}", xlib.get_window_type(event.window).get_name() );*/ store.dispatch(action::MapRequest { win: event.window, parent: event.parent, }) } xlib::UnmapNotify => { let event = xlib::XUnmapEvent::from(xevent); store.dispatch(action::UnmapNotify { win: event.window }) } xlib::ButtonPress => { let event = xlib::XButtonEvent::from(xevent); store.dispatch(action::ButtonPress { win: event.window, sub_win: event.subwindow, button: event.button, x_root: event.x_root as u32, y_root: event.y_root as u32, state: event.state as u32, }); } xlib::ButtonRelease => { let event = xlib::XButtonEvent::from(xevent); store.dispatch(action::ButtonRelease { win: event.window, sub_win: event.subwindow, button: event.button, x_root: event.x_root as u32, y_root: event.y_root as u32, state: event.state as u32, }) } xlib::KeyPress => { let event = xlib::XKeyEvent::from(xevent); store.dispatch(action::KeyPress { win: event.window, state: event.state, keycode: event.keycode, }) } /*xlib::KeyRelease => { let event = xlib::XKeyEvent::from(xevent); action::KeyRelease{win: event.window, state: event.state, keycode: event.keycode}; },*/ xlib::MotionNotify => { //debug!("motion"); let event = xlib::XMotionEvent::from(xevent); store.dispatch(action::MotionNotify { win: event.window, sub_win: event.subwindow, x_root: event.x_root, y_root: event.y_root, state: event.state, }) } xlib::EnterNotify => { let event = xlib::XCrossingEvent::from(xevent); store.dispatch(action::EnterNotify { win: event.window, sub_win: event.subwindow, }) } xlib::LeaveNotify => { let event = xlib::XCrossingEvent::from(xevent); store.dispatch(action::LeaveNotify { win: event.window }) } /*xlib::Expose => { let event = xlib::XExposeEvent::from(xevent); action::Expose{win: event.window}; },*/ xlib::DestroyNotify => { let event = xlib::XDestroyWindowEvent::from(xevent); store.dispatch(action::Destroy { win: event.window }) } xlib::PropertyNotify => { let event = xlib::XPropertyEvent::from(xevent); store.dispatch(action::PropertyNotify { win: event.window, atom: event.atom, }); } xlib::ClientMessage => { let event = xlib::XClientMessageEvent::from(xevent); //debug!("ClientMessage: {:#?}", event); store.dispatch(action::ClientMessageRequest { win: event.window, message_type: event.message_type, data: vec![ event.data.get_long(0), event.data.get_long(1), event.data.get_long(2), ], }); } _ => store.dispatch(action::UnknownEvent), } if let Ok(action) = rx.try_recv() { match action { internal_action::InternalAction::Focus => { //debug!("Motion dispatch focus"); if let Some(win) = xlib.window_under_pointer() { store.dispatch(action::Focus { win }) } } internal_action::InternalAction::FocusSpecific(win) => { store.dispatch(action::Focus { win }) } internal_action::InternalAction::UpdateLayout => { debug!("UpdateLayout"); store.dispatch(action::UpdateLayout) } _ => (), } } } }
// implements the optimization submodule pub fn gradient() /*-> vector */ { } pub fn gradient_decent() /*-> vector */ { } pub fn adam() /*-> vector */ { } // TODO: how do I best structure this module for use with kernels?
use std::net::TcpStream; use std::io::{Write, Error}; use commands::ClientCommand; use ser_de::ser; pub struct Writer { to_write: Vec<u8>, } impl Writer { pub fn new() -> Writer { Writer { to_write: Vec::new(), } } pub fn write(&mut self, stream: &mut TcpStream) -> Result<(), Error> { let written = try!( stream.write(&self.to_write[..]) ); trace!("Written, {}", written); let mut still = self.to_write.split_off(written); ::std::mem::swap(&mut self.to_write, &mut still); Ok(()) } pub fn push(&mut self, command: ClientCommand) { self.to_write.push_all(&ser(command)[..]); } }
use serde::{Serialize}; #[derive(Queryable, Serialize)] pub struct Article { pub id: i32, pub title: String, pub discribe: String, pub body: String, }
use crate::hook; use failure::Error; use std::path::PathBuf; use std::vec::Vec; /// Execute the provided command (argv) after loading the environment from the current directory pub fn run(pathbuf: PathBuf, shadowenv_data: String, argv: Vec<&str>) -> Result<(), Error> { if let Some((shadowenv, _)) = hook::load_env(pathbuf, shadowenv_data, true)? { hook::mutate_own_env(&shadowenv)?; } // exec only returns if it was unable to start the new process, and it's always an error. let err = exec::Command::new(&argv[0]).args(&argv[1..]).exec(); Err(err.into()) }
use crate::common; use crate::vector3::Vector3; use std::cmp; use std::convert::From; use std::f32::EPSILON; use std::fmt; use std::fmt::{Display, Formatter}; use std::ops::{ Index, IndexMut, Neg, Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, }; #[repr(C, packed)] #[derive(Copy, Clone, Debug)] pub struct Vector4 { pub x: f32, pub y: f32, pub z: f32, pub w: f32, } impl Vector4 { /// Creates a vector <0.0, 0.0, 0.0, 0.0> /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::new(); /// let expected = Vector4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; /// assert_eq!(actual, expected); /// ``` #[inline] pub fn new() -> Vector4 { Vector4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0, } } /// Creates a vector <0.0, 0.0, 0.0, 0.0> /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::one(); /// let expected = Vector4 { x: 1.0, y: 1.0, z: 1.0, w: 1.0 }; /// assert_eq!(actual, expected); /// ``` #[inline] pub fn one() -> Vector4 { Vector4 { x: 1.0, y: 1.0, z: 1.0, w: 1.0, } } /// Creates a vector from the provided values /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// let expected = Vector4 { x: 1.0, y: 2.0, z: 3.0, w: 4.0 }; /// assert_eq!(actual, expected); /// ``` #[inline] pub fn make(x: f32, y: f32, z: f32, w: f32) -> Vector4 { Vector4 { x, y, z, w } } /// Find the dot product between two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 0.0, 0.0, 0.0); /// let b = Vector4::make(0.0, 0.0, 1.0, 0.0); /// let actual = Vector4::dot(&a, &b); /// let expected = 0.0; /// assert_eq!(actual, expected); /// ``` #[inline] pub fn dot(a: &Vector4, b: &Vector4) -> f32 { a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w } /// Find the minimum (component-wise) vector between two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 4.0, 5.0, 7.0); /// let b = Vector4::make(2.0, 3.0, 6.0, 8.0); /// let actual = Vector4::min(&a, &b); /// let expected = Vector4::make(1.0, 3.0, 5.0, 7.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn min(a: &Vector4, b: &Vector4) -> Vector4 { Vector4::make(a.x.min(b.x), a.y.min(b.y), a.z.min(b.z), a.w.min(b.w)) } /// Find the maximum (component-wise) vector between two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 4.0, 5.0, 7.0); /// let b = Vector4::make(2.0, 3.0, 6.0, 8.0); /// let actual = Vector4::max(&a, &b); /// let expected = Vector4::make(2.0, 4.0, 6.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn max(a: &Vector4, b: &Vector4) -> Vector4 { Vector4::make(a.x.max(b.x), a.y.max(b.y), a.z.max(b.z), a.w.max(b.w)) } /// Find the clamped (component-wise) vector between two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 3.0, 5.0, 7.0); /// let b = Vector4::make(2.0, 4.0, 6.0, 8.0); /// let mut actual = Vector4::make(0.0, 5.0, 10.0, 20.0); /// actual.clamp(&a, &b); /// let expected = Vector4::make(1.0, 4.0, 6.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn clamp(&mut self, a: &Vector4, b: &Vector4) { let low = Self::min(a, b); let high = Self::max(a, b); let result = Self::max(&low, &Self::min(self, &high)); self.set(result.x, result.y, result.z, result.w); } /// Set the components of a vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::new(); /// actual.set(1.0, 2.0, 3.0, 4.0); /// let expected = Vector4::make(1.0, 2.0, 3.0, 4.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn set(&mut self, x: f32, y: f32, z: f32, w: f32) { self.x = x; self.y = y; self.z = z; self.w = w; } /// Get the magnitude of the vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0).mag(); /// let expected = 5.47722557505; /// assert_eq!(actual, expected); /// ``` #[inline] pub fn mag(&self) -> f32 { self.mag_sq().sqrt() } /// Get the squared magnitude of the vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0).mag_sq(); /// let expected = 30.0; /// assert_eq!(actual, expected); /// ``` #[inline] pub fn mag_sq(&self) -> f32 { self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w } /// Normalize the vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual.norm(); /// let expected = Vector4::make(0.18257418, 0.36514837, 0.5477225, 0.73029673); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn norm(&mut self) -> f32 { let length = self.mag(); if length > EPSILON { self.x /= length; self.y /= length; self.z /= length; self.w /= length; length } else { 0.0 } } /// Set the components of a vector to their absolute values /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(-1.0, -2.0, -3.0, -4.0); /// actual.abs(); /// let expected = Vector4::make(1.0, 2.0, 3.0, 4.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn abs(&mut self) { self.x = self.x.abs(); self.y = self.y.abs(); self.z = self.z.abs(); self.w = self.w.abs(); } /// Determine whether or not all components of the vector are valid /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// assert!(actual.is_valid()); /// ``` #[inline] pub fn is_valid(&self) -> bool { for i in 0..4 { if !common::is_valid(self[i]) { return false; } } true } } impl From<Vector3> for Vector4 { /// Creates a Vector4 from the components of a Vector3 /// /// # Examples /// ``` /// use vex::Vector3; /// use vex::Vector4; /// /// let input = Vector3::make(1.0, 2.0, 3.0); /// let actual = Vector4::from(input); /// let expected = Vector4 { x: 1.0, y: 2.0, z: 3.0, w: 0.0 }; /// assert_eq!(actual, expected); /// ``` #[inline] fn from(item: Vector3) -> Vector4 { Vector4 { x: item.x, y: item.y, z: item.z, w: 0.0, } } } impl Index<u32> for Vector4 { type Output = f32; /// Looks up a component by index /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut v = Vector4::make(1.0, 2.0, 3.0, 4.0); /// assert_eq!(v[0], 1.0); /// assert_eq!(v[1], 2.0); /// assert_eq!(v[2], 3.0); /// assert_eq!(v[3], 4.0); /// ``` #[inline] fn index(&self, index: u32) -> &f32 { unsafe { match index { 0 => &self.x, 1 => &self.y, 2 => &self.z, 3 => &self.w, _ => panic!("Invalid index for Vector4: {}", index), } } } } impl IndexMut<u32> for Vector4 { /// Mutate a component by index /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut v = Vector4::new(); /// v[0] = 4.0; /// v[1] = 5.0; /// v[2] = 6.0; /// v[3] = 7.0; /// assert_eq!(v[0], 4.0); /// assert_eq!(v[1], 5.0); /// assert_eq!(v[2], 6.0); /// assert_eq!(v[3], 7.0); /// ``` #[inline] fn index_mut<'a>(&'a mut self, index: u32) -> &'a mut f32 { unsafe { match index { 0 => &mut self.x, 1 => &mut self.y, 2 => &mut self.z, 3 => &mut self.w, _ => panic!("Invalid index for Vector4: {}", index), } } } } impl Neg for Vector4 { type Output = Vector4; /// Negates all components in a vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = -Vector4::make(1.0, 2.0, 3.0, 4.0); /// let expected = Vector4::make(-1.0, -2.0, -3.0, -4.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn neg(self) -> Vector4 { Vector4::make(-self.x, -self.y, -self.z, -self.w) } } impl Add<f32> for Vector4 { type Output = Vector4; /// Find the resulting vector by adding a scalar to a vector's components /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0) + 1.0; /// let expected = Vector4::make(2.0, 3.0, 4.0, 5.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add(self, _rhs: f32) -> Vector4 { Vector4::make(self.x + _rhs, self.y + _rhs, self.z + _rhs, self.w + _rhs) } } impl Add<Vector4> for Vector4 { type Output = Vector4; /// Add two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 2.0, 3.0, 4.0); /// let b = Vector4::make(5.0, 6.0, 7.0, 8.0); /// let actual = a + b; /// let expected = Vector4::make(6.0, 8.0, 10.0, 12.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add(self, _rhs: Vector4) -> Vector4 { Vector4::make( self.x + _rhs.x, self.y + _rhs.y, self.z + _rhs.z, self.w + _rhs.w, ) } } impl AddAssign<f32> for Vector4 { /// Increment a vector by a scalar /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual += 10.0; /// let expected = Vector4::make(11.0, 12.0, 13.0, 14.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add_assign(&mut self, _rhs: f32) { self.x += _rhs; self.y += _rhs; self.z += _rhs; self.w += _rhs; } } impl AddAssign<Vector4> for Vector4 { /// Increment a vector by another vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual += Vector4::make(1.0, 2.0, 3.0, 4.0); /// let expected = Vector4::make(2.0, 4.0, 6.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add_assign(&mut self, _rhs: Vector4) { self.x += _rhs.x; self.y += _rhs.y; self.z += _rhs.z; self.w += _rhs.w; } } impl Sub<f32> for Vector4 { type Output = Vector4; /// Find the resulting vector by subtracting a scalar from a vector's components /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0) - 10.0; /// let expected = Vector4::make(-9.0, -8.0, -7.0, -6.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn sub(self, _rhs: f32) -> Vector4 { Vector4::make(self.x - _rhs, self.y - _rhs, self.z - _rhs, self.w - _rhs) } } impl Sub<Vector4> for Vector4 { type Output = Vector4; /// Subtract two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 2.0, 3.0, 4.0); /// let b = Vector4::make(5.0, 4.0, 3.0, 2.0); /// let actual = a - b; /// let expected = Vector4::make(-4.0, -2.0, 0.0, 2.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn sub(self, _rhs: Vector4) -> Vector4 { Vector4::make( self.x - _rhs.x, self.y - _rhs.y, self.z - _rhs.z, self.w - _rhs.w, ) } } impl SubAssign<f32> for Vector4 { /// Decrement a vector by a scalar /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual -= 1.0; /// let expected = Vector4::make(0.0, 1.0, 2.0, 3.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn sub_assign(&mut self, _rhs: f32) { self.x -= _rhs; self.y -= _rhs; self.z -= _rhs; self.w -= _rhs; } } impl SubAssign<Vector4> for Vector4 { /// Decrement a vector by another vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual -= Vector4::make(1.0, 2.0, 3.0, 4.0); /// assert_eq!(actual, Vector4::new()); /// ``` #[inline] fn sub_assign(&mut self, _rhs: Vector4) { self.x -= _rhs.x; self.y -= _rhs.y; self.z -= _rhs.z; self.w -= _rhs.w; } } impl Mul<f32> for Vector4 { type Output = Vector4; /// Find the resulting vector by multiplying a scalar to a vector's components /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0) * 2.0; /// let expected = Vector4::make(2.0, 4.0, 6.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul(self, _rhs: f32) -> Vector4 { Vector4::make(self.x * _rhs, self.y * _rhs, self.z * _rhs, self.w * _rhs) } } impl Mul<Vector4> for Vector4 { type Output = Vector4; /// Multiply two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(1.0, 2.0, 3.0, 4.0); /// let b = Vector4::make(5.0, 6.0, 7.0, 8.0); /// let actual = a * b; /// let expected = Vector4::make(5.0, 12.0, 21.0, 32.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul(self, _rhs: Vector4) -> Vector4 { Vector4::make( self.x * _rhs.x, self.y * _rhs.y, self.z * _rhs.z, self.w * _rhs.w, ) } } impl MulAssign<f32> for Vector4 { /// Multiply a vector by a scalar /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual *= 2.0; /// let expected = Vector4::make(2.0, 4.0, 6.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul_assign(&mut self, _rhs: f32) { self.x *= _rhs; self.y *= _rhs; self.z *= _rhs; self.w *= _rhs; } } impl MulAssign<Vector4> for Vector4 { /// Multiply a vector by another vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual *= Vector4::make(2.0, 3.0, 6.0, 8.0); /// let expected = Vector4::make(2.0, 6.0, 18.0, 32.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul_assign(&mut self, _rhs: Vector4) { self.x *= _rhs.x; self.y *= _rhs.y; self.z *= _rhs.z; self.w *= _rhs.w; } } impl Div<f32> for Vector4 { type Output = Vector4; /// Find the resulting vector by dividing a scalar to a vector's components /// /// # Examples /// ``` /// use vex::Vector4; /// /// let actual = Vector4::make(1.0, 2.0, 3.0, 4.0) / 2.0; /// let expected = Vector4::make(0.5, 1.0, 1.5, 2.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn div(self, _rhs: f32) -> Vector4 { Vector4::make(self.x / _rhs, self.y / _rhs, self.z / _rhs, self.w / _rhs) } } impl Div<Vector4> for Vector4 { type Output = Vector4; /// Divide two vectors /// /// # Examples /// ``` /// use vex::Vector4; /// /// let a = Vector4::make(2.0, 4.0, 6.0, 8.0); /// let b = Vector4::make(1.0, 4.0, 12.0, 32.0); /// let actual = a / b; /// let expected = Vector4::make(2.0, 1.0, 0.5, 0.25); /// assert_eq!(actual, expected); /// ``` #[inline] fn div(self, _rhs: Vector4) -> Vector4 { Vector4::make( self.x / _rhs.x, self.y / _rhs.y, self.z / _rhs.z, self.w / _rhs.w, ) } } impl DivAssign<f32> for Vector4 { /// Divide a vector by a scalar /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(1.0, 2.0, 3.0, 4.0); /// actual /= 2.0; /// let expected = Vector4::make(0.5, 1.0, 1.5, 2.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn div_assign(&mut self, _rhs: f32) { self.x /= _rhs; self.y /= _rhs; self.z /= _rhs; self.w /= _rhs; } } impl DivAssign<Vector4> for Vector4 { /// Divide a vector by another vector /// /// # Examples /// ``` /// use vex::Vector4; /// /// let mut actual = Vector4::make(2.0, 4.0, 6.0, 8.0); /// actual /= Vector4::make(1.0, 4.0, 12.0, 32.0); /// let expected = Vector4::make(2.0, 1.0, 0.5, 0.25); /// assert_eq!(actual, expected); /// ``` #[inline] fn div_assign(&mut self, _rhs: Vector4) { self.x /= _rhs.x; self.y /= _rhs.y; self.z /= _rhs.z; self.w /= _rhs.w; } } impl cmp::PartialEq for Vector4 { /// Determines if two vectors' components are equivalent /// /// # Examples /// ``` /// use vex::Vector4; /// /// assert!(Vector4::new() == Vector4::new()); /// ``` #[inline] fn eq(&self, _rhs: &Vector4) -> bool { for i in 0..4 { if self[i] != _rhs[i] { return false; } } true } } impl Display for Vector4 { #[inline] fn fmt(&self, f: &mut Formatter) -> fmt::Result { unsafe { write!(f, "<{} {} {} {}>", self.x, self.y, self.z, self.w) } } }
//! SPI Commands for the Waveshare 4.2" E-Ink Display use crate::traits; /// EPD4IN2 commands /// /// Should rarely (never?) be needed directly. /// /// For more infos about the addresses and what they are doing look into the pdfs /// /// The description of the single commands is mostly taken from IL0398.pdf #[allow(dead_code)] #[derive(Copy, Clone)] pub(crate) enum Command { /// Set Resolution, LUT selection, BWR pixels, gate scan direction, source shift direction, booster switch, soft reset /// One Byte of Data: /// 0x0F Red Mode, LUT from OTP /// 0x1F B/W Mode, LUT from OTP /// 0x2F Red Mode, LUT set by registers /// 0x3F B/W Mode, LUT set by registers PanelSetting = 0x00, /// selecting internal and external power /// self.send_data(0x03)?; //VDS_EN, VDG_EN /// self.send_data(0x00)?; //VCOM_HV, VGHL_LV[1], VGHL_LV[0] /// self.send_data(0x2b)?; //VDH /// self.send_data(0x2b)?; //VDL /// self.send_data(0xff)?; //VDHR PowerSetting = 0x01, /// After the Power Off command, the driver will power off following the Power Off Sequence. This command will turn off charge /// pump, T-con, source driver, gate driver, VCOM, and temperature sensor, but register data will be kept until VDD becomes OFF. /// Source Driver output and Vcom will remain as previous condition, which may have 2 conditions: floating. PowerOff = 0x02, /// Setting Power OFF sequence PowerOffSequenceSetting = 0x03, /// Turning On the Power PowerOn = 0x04, /// This command enables the internal bandgap, which will be cleared by the next POF. PowerOnMeasure = 0x05, /// Starting data transmission /// 3-times: self.send_data(0x17)?; //07 0f 17 1f 27 2F 37 2f BoosterSoftStart = 0x06, /// After this command is transmitted, the chip would enter the deep-sleep mode to save power. /// /// The deep sleep mode would return to standby by hardware reset. /// /// The only one parameter is a check code, the command would be excuted if check code = 0xA5. DeepSleep = 0x07, /// This command starts transmitting data and write them into SRAM. To complete data transmission, command DSP (Data /// transmission Stop) must be issued. Then the chip will start to send data/VCOM for panel. /// /// - In B/W mode, this command writes “OLD” data to SRAM. /// - In B/W/Red mode, this command writes “B/W” data to SRAM. /// - In Program mode, this command writes “OTP” data to SRAM for programming. DataStartTransmission1 = 0x10, /// Stopping data transmission DataStop = 0x11, /// While user sent this command, driver will refresh display (data/VCOM) according to SRAM data and LUT. /// /// After Display Refresh command, BUSY_N signal will become “0” and the refreshing of panel starts. DisplayRefresh = 0x12, /// This command starts transmitting data and write them into SRAM. To complete data transmission, command DSP (Data /// transmission Stop) must be issued. Then the chip will start to send data/VCOM for panel. /// - In B/W mode, this command writes “NEW” data to SRAM. /// - In B/W/Red mode, this command writes “RED” data to SRAM. DataStartTransmission2 = 0x13, /// This command stores VCOM Look-Up Table with 7 groups of data. Each group contains information for one state and is stored /// with 6 bytes, while the sixth byte indicates how many times that phase will repeat. /// /// from IL0373 LutForVcom = 0x20, /// This command stores White-to-White Look-Up Table with 7 groups of data. Each group contains information for one state and is /// stored with 6 bytes, while the sixth byte indicates how many times that phase will repeat. /// /// from IL0373 LutWhiteToWhite = 0x21, /// This command stores Black-to-White Look-Up Table with 7 groups of data. Each group contains information for one state and is /// stored with 6 bytes, while the sixth byte indicates how many times that phase will repeat. /// /// from IL0373 LutBlackToWhite = 0x22, /// This command stores White-to-Black Look-Up Table with 7 groups of data. Each group contains information for one state and is /// stored with 6 bytes, while the sixth byte indicates how many times that phase will repeat. /// /// from IL0373 LutWhiteToBlack = 0x23, /// This command stores Black-to-Black Look-Up Table with 7 groups of data. Each group contains information for one state and is /// stored with 6 bytes, while the sixth byte indicates how many times that phase will repeat. /// /// from IL0373 LutBlackToBlack = 0x24, /// The command controls the PLL clock frequency. PllControl = 0x30, /// This command reads the temperature sensed by the temperature sensor. /// /// Doesn't work! Waveshare doesn't connect the read pin TemperatureSensor = 0x40, /// Selects the Internal or External temperature sensor and offset TemperatureSensorSelection = 0x41, /// Write External Temperature Sensor TemperatureSensorWrite = 0x42, /// Read External Temperature Sensor /// /// Doesn't work! Waveshare doesn't connect the read pin TemperatureSensorRead = 0x43, /// This command indicates the interval of Vcom and data output. When setting the vertical back porch, the total blanking will be kept (20 Hsync) VcomAndDataIntervalSetting = 0x50, /// This command indicates the input power condition. Host can read this flag to learn the battery condition. LowPowerDetection = 0x51, /// This command defines non-overlap period of Gate and Source. TconSetting = 0x60, /// This command defines alternative resolution and this setting is of higher priority than the RES\[1:0\] in R00H (PSR). ResolutionSetting = 0x61, /// This command defines the Fist Active Gate and First Active Source of active channels. GsstSetting = 0x65, /// The LUT_REV / Chip Revision is read from OTP address = 0x001. /// /// Doesn't work! Waveshare doesn't connect the read pin Revision = 0x70, /// Read Flags. This command reads the IC status /// PTL, I2C_ERR, I2C_BUSY, DATA, PON, POF, BUSY /// /// Doesn't work! Waveshare doesn't connect the read pin GetStatus = 0x71, /// Automatically measure VCOM. This command reads the IC status AutoMeasurementVcom = 0x80, /// This command gets the VCOM value /// /// Doesn't work! Waveshare doesn't connect the read pin ReadVcomValue = 0x81, /// Set VCM_DC VcmDcSetting = 0x82, /// This command sets partial window PartialWindow = 0x90, /// This command makes the display enter partial mode PartialIn = 0x91, /// This command makes the display exit partial mode and enter normal mode PartialOut = 0x92, /// After this command is issued, the chip would enter the program mode. /// /// After the programming procedure completed, a hardware reset is necessary for leaving program mode. /// /// The only one parameter is a check code, the command would be excuted if check code = 0xA5. ProgramMode = 0xA0, /// After this command is transmitted, the programming state machine would be activated. /// /// The BUSY flag would fall to 0 until the programming is completed. ActiveProgramming = 0xA1, /// The command is used for reading the content of OTP for checking the data of programming. /// /// The value of (n) is depending on the amount of programmed data, tha max address = 0xFFF. ReadOtp = 0xA2, /// This command is set for saving power during fresh period. If the output voltage of VCOM / Source is from negative to positive or /// from positive to negative, the power saving mechanism will be activated. The active period width is defined by the following two /// parameters. PowerSaving = 0xE3, } impl traits::Command for Command { /// Returns the address of the command fn address(self) -> u8 { self as u8 } } #[cfg(test)] mod tests { use super::*; use crate::traits::Command as CommandTrait; #[test] fn command_addr() { assert_eq!(Command::PowerSaving.address(), 0xE3); assert_eq!(Command::PanelSetting.address(), 0x00); assert_eq!(Command::DisplayRefresh.address(), 0x12); } }
use codespan_reporting::diagnostic::{Diagnostic as CodespanDiagnostic, Label}; use either::Either::*; use walrus_semantics::{ diagnostic::Diagnostic, hir::{Field, Module}, ty::InferenceId, }; pub fn render_diagnostic(module: &Module, diag: &Diagnostic) -> CodespanDiagnostic<()> { match diag { Diagnostic::UnnecessarySemicolon(semicolon) => CodespanDiagnostic::note() .with_message("Unnecessary semicolon") .with_labels(vec![ Label::primary((), semicolon.span).with_message("This semicolon is not needed") ]), Diagnostic::BadLit { err, span } => CodespanDiagnostic::error() .with_message("Bad literal") .with_labels(vec![Label::primary((), *span).with_message(err.to_string())]), Diagnostic::DuplicateVar { first, second } => { let name = &module.hir[*first]; let first = &module.source[*first]; let second = &module.source[*second]; CodespanDiagnostic::error() .with_message(format!("Name `{name}` is already defined")) .with_labels(vec![ Label::primary((), second.span()).with_message("Second definition"), Label::secondary((), first.span()).with_message("First definition"), ]) } Diagnostic::UnboundVar { var, mode, denotation, } => { let syntax = &module.source[*var]; let name = &module.hir[*var]; match denotation { None => CodespanDiagnostic::error() .with_message(format!("Unbound variable: `{name}`")) .with_labels(vec![Label::primary((), syntax.span()) .with_message(format!("Name `{name} is not defined"))]), Some(denotation) => CodespanDiagnostic::error() .with_message(format!("No {mode} named {name} in scope")) .with_labels(vec![Label::primary((), syntax.span()).with_message( format!( "The name `{name}` is defined, but it is a {denotation}, not a {mode}" ), )]), } } Diagnostic::TypeMismatch { id, expected, got } => { let span = match id { Left(id) => module.source[*id].span(), Right(id) => module.source[*id].span(), }; let expected = expected.to_string(&module.hir); let got = got.to_string(&module.hir); CodespanDiagnostic::error() .with_message("Type mismatch") .with_labels(vec![Label::primary((), span) .with_message(format!("Expected {expected}, got {got}"))]) } Diagnostic::InferenceFail(id) => { let span = match id { InferenceId::Var(id) => module.source[*id].span(), InferenceId::Expr(id) => module.source[*id].span(), InferenceId::Type(id) => module.source[*id].span(), InferenceId::Pat(id) => module.source[*id].span(), }; let msg = match id { InferenceId::Var(_) => "variable", InferenceId::Expr(_) => "expr", InferenceId::Type(_) => "type", InferenceId::Pat(_) => "pattern", }; CodespanDiagnostic::error() .with_message("Could not infer type") .with_labels(vec![ Label::primary((), span).with_message(format!("Could not infer type of {msg}")) ]) } Diagnostic::ReturnNotInFn(expr) => { let span = module.source[*expr].span(); CodespanDiagnostic::error() .with_message("Return outside of function") .with_labels(vec![Label::primary((), span) .with_message("`return` is only allowed inside a function body")]) } Diagnostic::BreakNotInLoop(expr) => { let span = module.source[*expr].span(); CodespanDiagnostic::error() .with_message("Break outside of loop") .with_labels(vec![Label::primary((), span) .with_message("`break` is only allowed inside a loop body")]) } Diagnostic::ContinueNotInLoop(expr) => { let span = module.source[*expr].span(); CodespanDiagnostic::error() .with_message("Continue outside of loop") .with_labels(vec![Label::primary((), span) .with_message("`continue` is only allowed inside a loop body")]) } Diagnostic::CalledNonFn { expr, ty } => { let span = module.source[*expr].span(); let ty = ty.to_string(&module.hir); CodespanDiagnostic::error() .with_message("Called non function") .with_labels(vec![ Label::primary((), span).with_message(format!("{ty} is not a function type")) ]) } Diagnostic::ArgCountMismatch { expr, ty, expected, got, } => { let span = module.source[*expr].span(); let ty = ty.to_string(&module.hir); CodespanDiagnostic::error() .with_message("Called function with wrong number of arguments") .with_labels(vec![Label::primary((), span).with_message(format!( "The function type {ty} expects {expected} arguments, but {got} were passed \ to it" ))]) } Diagnostic::CannotApplyBinop { expr, lhs_type, op, rhs_type, } => { let span = module.source[*expr].span(); let lhs_type = lhs_type.to_string(&module.hir); let rhs_type = rhs_type.to_string(&module.hir); CodespanDiagnostic::error() .with_message("Applied operator to incompatible types") .with_labels(vec![Label::primary((), span).with_message(format!( "Cannot perform the operation {lhs_type} {op} {rhs_type}" ))]) } Diagnostic::NotLValue { lhs } => { let span = module.source[*lhs].span(); CodespanDiagnostic::error() .with_message("Not lvalue") .with_labels(vec![ Label::primary((), span).with_message("Can only assign to lvalue expressions") ]) } Diagnostic::NotMutable { def: definition, usage, } => { let def_syntax = &module.source[*definition]; let usage_syntax = &module.source[*usage]; CodespanDiagnostic::error() .with_message("Assignment to immutable variable") .with_labels(vec![ Label::primary((), usage_syntax.span()) .with_message("This variable was not bound with `mut`"), Label::secondary((), def_syntax.span()) .with_message("The variable is bound here"), ]) } Diagnostic::NotLocal { var, denotation } => { let syntax = &module.source[*var]; CodespanDiagnostic::error() .with_message("Assignment to non-local variable") .with_labels(vec![Label::primary((), syntax.span()).with_message( format!("This variable refers to a {denotation}, not a local variable",), )]) } Diagnostic::NoSuchField { parent, field, ty, possible_fields, } => { let span = match parent { Left(id) => module.source[*id].span(), Right(id) => module.source[*id].span(), }; let ty = ty.to_string(&module.hir); let msg = match possible_fields { None => format!("The type {ty} has no fields"), Some(Left(fields)) if fields.is_empty() => format!("The type {ty} has no fields"), Some(Right(fields)) if *fields == 0 => format!("The type {ty} has no fields"), Some(Left(fields)) => format!( "The type {ty} has the following possible fields: {}", fields .iter() .map(|field| &module.hir[field.name]) .map(|field| format!(".{field}")) .collect::<Vec<_>>() .join(", ") ), Some(Right(fields)) => format!( "The type {ty} has the following possible fields: {}", (0_usize..*fields) .map(|field| format!(".{field}")) .collect::<Vec<_>>() .join(", ") ), }; let field = match field { Field::Tuple(x) => x.to_string(), Field::Named(var) => module.hir[*var].as_str().to_string(), }; CodespanDiagnostic::error() .with_message(format!("No `.{field}` field")) .with_labels(vec![Label::primary((), span).with_message(msg)]) } Diagnostic::MissingField { id, field, ty, possible_fields, } => { let span = match id { Left(id) => module.source[*id].span(), Right(id) => module.source[*id].span(), }; let ty = ty.to_string(&module.hir); let field = &module.hir[*field]; let msg = format!( "The type {ty} has the following fields: {}", possible_fields .iter() .map(|field| &module.hir[field.name]) .map(|field| format!(".{field}")) .collect::<Vec<_>>() .join(", ") ); CodespanDiagnostic::error() .with_message(format!("Missing field `{field}`")) .with_labels(vec![Label::primary((), span).with_message(msg)]) } Diagnostic::FalliablePattern { id } => { let span = module.source[*id].span(); CodespanDiagnostic::error() .with_message("Falliable pattern") .with_labels(vec![ Label::primary((), span).with_message("Patterns in this context must not fail") ]) } } }
mod mks; Q!(self::mks, u32);
impl Solution { pub fn reverse(x: i32) -> i32 { let mut res = 0; let mut x = x; while x != 0{ //max 和 min in rust if res > i32::MAX / 10 || res < i32::MIN / 10{ return 0; } res = res * 10 + x % 10; x /= 10; } res } }
use super::{ AzureCliCredential, EnvironmentCredential, ImdsManagedIdentityCredential, TokenCredential, }; use azure_core::TokenResponse; #[derive(Debug, Default)] /// Provides a mechanism of selectively disabling credentials used for a `DefaultAzureCredential` instance pub struct DefaultAzureCredentialBuilder { include_environment_credential: bool, include_managed_identity_credential: bool, include_cli_credential: bool, } impl DefaultAzureCredentialBuilder { /// Create a new `DefaultAzureCredentialBuilder` pub fn new() -> Self { Self::default() } /// Exclude using credentials from the environment pub fn exclude_environment_credential(&mut self) -> &mut Self { self.include_environment_credential = false; self } /// Exclude using credentials from the cli pub fn exclude_cli_credential(&mut self) -> &mut Self { self.include_cli_credential = false; self } /// Exclude using managed identity credentials pub fn exclude_managed_identity_credential(&mut self) -> &mut Self { self.include_managed_identity_credential = false; self } pub fn build(&self) -> DefaultAzureCredential { let source_count = self.include_cli_credential as usize + self.include_cli_credential as usize + self.include_managed_identity_credential as usize; let mut sources = Vec::<DefaultAzureCredentialEnum>::with_capacity(source_count); if self.include_environment_credential { sources.push(DefaultAzureCredentialEnum::Environment( EnvironmentCredential::default(), )); } if self.include_managed_identity_credential { sources.push(DefaultAzureCredentialEnum::ManagedIdentity( ImdsManagedIdentityCredential {}, )) } if self.include_cli_credential { sources.push(DefaultAzureCredentialEnum::AzureCli(AzureCliCredential {})); } DefaultAzureCredential::with_sources(sources) } } #[non_exhaustive] #[derive(Debug, thiserror::Error)] pub enum DefaultAzureCredentialError { #[error("Error getting token credential from Azure CLI: {0}")] AzureCliCredentialError(#[from] super::AzureCliCredentialError), #[error("Error getting environment credential: {0}")] EnvironmentCredentialError(#[from] super::EnvironmentCredentialError), #[error("Error getting managed identity credential: {0}")] ManagedIdentityCredentialError(#[from] super::ManagedIdentityCredentialError), #[error( "Multiple errors were encountered while attempting to authenticate:\n{}", format_aggregate_error(.0) )] CredentialUnavailable(Vec<DefaultAzureCredentialError>), } /// Types of TokenCredential supported by DefaultAzureCredential pub enum DefaultAzureCredentialEnum { Environment(EnvironmentCredential), ManagedIdentity(ImdsManagedIdentityCredential), AzureCli(AzureCliCredential), } #[async_trait::async_trait] impl TokenCredential for DefaultAzureCredentialEnum { type Error = DefaultAzureCredentialError; async fn get_token(&self, resource: &str) -> Result<TokenResponse, Self::Error> { match self { DefaultAzureCredentialEnum::Environment(credential) => credential .get_token(resource) .await .map_err(DefaultAzureCredentialError::EnvironmentCredentialError), DefaultAzureCredentialEnum::ManagedIdentity(credential) => credential .get_token(resource) .await .map_err(DefaultAzureCredentialError::ManagedIdentityCredentialError), DefaultAzureCredentialEnum::AzureCli(credential) => credential .get_token(resource) .await .map_err(DefaultAzureCredentialError::AzureCliCredentialError), } } } /// Provides a default `TokenCredential` authentication flow for applications that will be deployed to Azure. /// /// The following credential types if enabled will be tried, in order: /// - EnvironmentCredential /// - ManagedIdentityCredential /// - AzureCliCredential /// Consult the documentation of these credential types for more information on how they attempt authentication. pub struct DefaultAzureCredential { sources: Vec<DefaultAzureCredentialEnum>, } impl DefaultAzureCredential { pub fn with_sources(sources: Vec<DefaultAzureCredentialEnum>) -> Self { DefaultAzureCredential { sources } } } impl Default for DefaultAzureCredential { fn default() -> Self { DefaultAzureCredential { sources: vec![ DefaultAzureCredentialEnum::Environment(EnvironmentCredential::default()), DefaultAzureCredentialEnum::ManagedIdentity(ImdsManagedIdentityCredential {}), DefaultAzureCredentialEnum::AzureCli(AzureCliCredential {}), ], } } } #[async_trait::async_trait] impl TokenCredential for DefaultAzureCredential { type Error = DefaultAzureCredentialError; /// Try to fetch a token using each of the credential sources until one succeeds async fn get_token(&self, resource: &str) -> Result<TokenResponse, Self::Error> { let mut errors = Vec::new(); for source in &self.sources { let token_res = source.get_token(resource).await; match token_res { Ok(token) => return Ok(token), Err(error) => errors.push(error), } } Err(DefaultAzureCredentialError::CredentialUnavailable(errors)) } } #[async_trait::async_trait] impl azure_core::TokenCredential for DefaultAzureCredential { async fn get_token( &self, resource: &str, ) -> Result<azure_core::TokenResponse, azure_core::Error> { TokenCredential::get_token(self, resource) .await .map_err(|error| azure_core::Error::GetTokenError(Box::new(error))) } } fn format_aggregate_error(errors: &[DefaultAzureCredentialError]) -> String { errors .iter() .map(|error| error.to_string()) .collect::<Vec<String>>() .join("\n") }
pub mod sync; pub use sync::*; pub fn nop() { unsafe { asm!("nop"); } } pub fn get_csr_hart_id() -> usize { let mut hart_id; unsafe { asm!("csrrs {0}, mhartid, zero", out(reg) hart_id, options(nostack)); } hart_id } pub fn get_csr_mcycle() -> usize { let mut mcycle; unsafe { asm!("csrrs {0}, mcycle, zero", out(reg) mcycle, options(nostack)); } mcycle }
fn read_nums() -> Vec<i32> { let mut input_str = String::new(); std::io::stdin().read_line(&mut input_str).expect("Read error."); input_str.split_whitespace() .map(|s| s.parse::<i32>().expect("Failed to parse number.")) .collect() } fn main() { let (alice, bob) = (read_nums(), read_nums()); let result = alice.iter().zip(bob.iter()) .fold((0, 0), |r, (a, b)| { if a < b { return (r.0, r.1 + 1); } if a > b { return (r.0 + 1, r.1); } (r.0, r.1) }); println!("{} {}", result.0, result.1); }
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{Serialize, Deserialize}; use std::collections::{HashMap, HashSet}; use std::convert::TryInto; use std::fmt; use std::future::Future; use std::io::Write; pub fn get(args: Vec<&str>) -> BoxedErrorResult<()> { check_joined()?; if args.len() != 2 { return Err("Usage: get distributed_filename local_path".into()) } let distributed_filename = args[0].to_string(); let local_path = args[1].to_string(); async_std::task::block_on(get_distributed_file(distributed_filename, local_path))?; Ok(()) } // args[0] = path to local file // args[1] = distributed filename pub fn put(args: Vec<&str>, sender: &OperationSender) -> BoxedErrorResult<()> { check_joined()?; if args.len() != 2 { return Err("Usage: put local_path distributed_filename".into()) } let local_path = args[0]; let distributed_filename = args[1]; // Figure out who I am giving this file to let dest_ids = gen_file_owners(&distributed_filename)?; // Gossip who has the file now sender.send( SendableOperation::for_successors(Box::new(NewFileOwnersOperation { distributed_filename: distributed_filename.to_string(), new_owners: dest_ids .iter() .map(|x| x.to_string()) .collect::<HashSet<_>>() })) )?; // Send them the file async_std::task::block_on(send_file_to_all(local_path.to_string(), distributed_filename.to_string(), &dest_ids))?; Ok(()) } pub fn ls(args: Vec<&str>) -> BoxedErrorResult<()> { check_joined()?; let invalid_args: BoxedErrorResult<()> = Err("Usage: ls [distributed_filename]".into()); match args.len() { 0 => { // All print_file_owners(None, true)?; Ok(()) }, 1 => { // Just File let distributed_filename = args[0]; print_file_owners(Some(distributed_filename), false)?; Ok(()) }, _ => invalid_args } } // TODO: You wrote this very late - maybe fix fn print_file_owners(maybe_distributed_filename: Option<&str>, full: bool) -> BoxedErrorResult<()> { let all_file_owners = globals::ALL_FILE_OWNERS.read(); match (maybe_distributed_filename, full) { (Some(_), true) => { Err("Cannot set distributed_filename and full to true when printing owners".into()) }, (Some(distributed_filename), false) => { // Print the files owners match all_file_owners.get(distributed_filename) { Some(owners) => { println!("{:?}", owners); }, None => { // A little unoptimal - change if above format changes println!("{{}}"); } } Ok(()) }, (None, true) => { // Print the whole map println!("{:?}", *all_file_owners); Ok(()) }, (None, false) => { Err("Cannot print owners of nonexistant distributed_filename with full set to false".into()) } } } async fn get_distributed_file(distributed_filename: String, local_path: String) -> BoxedErrorResult<()> { // TODO: Find owners let operation = SendableOperation::for_owners(&distributed_filename, Box::new(GetOperation { distributed_filename: distributed_filename.clone(), local_path: local_path })); let mut streams = operation .write_all_tcp_async() .await?; // TODO: Redo whatever tf going on here match streams.len() { 0 => Err(format!("No owners found for file {}", distributed_filename).into()), _ => { let (result, source) = streams[0] .try_read_operation() .await?; result.execute(source)?; Ok(()) } } } async fn read_file_to_buf(local_path: &String) -> BoxedErrorResult<Vec<u8>> { let mut data_buf: Vec<u8> = Vec::new(); let mut file = async_std::fs::File::open(&local_path).await?; file.read_to_end(&mut data_buf).await?; Ok(data_buf) } async fn send_file_to_all(local_path: String, distributed_filename: String, dest_ids: &Vec<String>) -> BoxedErrorResult<()> { let data_buf = read_file_to_buf(&local_path).await?; let operation = SendableOperation::for_id_list(dest_ids.clone(), Box::new(SendFileOperation { filename: distributed_filename, data: data_buf, is_distributed: true })); operation.write_all_tcp_async().await?; Ok(()) } pub async fn file_server<'a>(_sender: &'a OperationSender) -> BoxedErrorResult<()> { let server = globals::SERVER_SOCKET.read(); let mut incoming = server.incoming(); while let Some(stream) = incoming.next().await { let connection = stream?; log(format!("Handling connection from {:?}", connection.peer_addr())); spawn(handle_connection(connection)); } Ok(()) } async fn handle_connection(mut connection: async_std::net::TcpStream) -> BoxedErrorResult<()> { let (operation, source) = connection.try_read_operation().await?; // TODO: Think about what standard we want with these let _generated_operations = operation.execute(source)?; Ok(()) } // Helpers fn gen_file_owners(filename: &str) -> BoxedErrorResult<Vec<String>> { let file_idx = filename.easyhash(); heartbeat::gen_neighbor_list_from(file_idx as i32, 1, constants::NUM_OWNERS, true) } // TODO: This function makes the entire system assume there are always at least two nodes in the system // and the file must have an owner or else the operation will not work correctly. This is fine for now // but it is worth improving sooner rather than later (make distinct Error types to differentiate, etc). fn gen_new_file_owner(filename: &str) -> BoxedErrorResult<String> { match globals::ALL_FILE_OWNERS.read().get(filename) { Some(owners) => { let potential_owners = gen_file_owners(filename)?; for potential_owner in &potential_owners { if !owners.contains(potential_owner) { return Ok(potential_owner.clone()); } } Err(format!("No new owners available for file {}", filename).into()) }, None => Err(format!("No owner found for file {}", filename).into()) } } fn distributed_file_path(filename: &String) -> String { format!("{}/{}", constants::DATA_DIR, filename) } // Returns messages to be gossiped pub fn handle_failed_node(failed_id: &String) -> BoxedErrorResult<Vec<SendableOperation>> { match heartbeat::is_master() { true => { let mut generated_operations: Vec<SendableOperation> = Vec::new(); let myself_source = Source::myself(); // Find files they owned let mut lost_files: HashSet<String> = HashSet::new(); for (distributed_filename, owners) in globals::ALL_FILE_OWNERS.read().iter() { if owners.contains(failed_id) { lost_files.insert(distributed_filename.clone()); } } log("Found lost files".to_string()); // Send that they no longer own those files // Separate operation so that this acts like a confirmation to fully forget about the node from // the master. Can be used with a delay later if you want more error resistance. let lost_file_operation = LostFilesOperation { failed_owner: failed_id.clone(), lost_files: lost_files.clone() }; generated_operations.append(&mut lost_file_operation.execute(myself_source.clone())?); log("Executed lost files operation locally".to_string()); // Gen new owners of the file and propagate let mut new_owners: HashMap<String, HashSet<String>> = HashMap::new(); for lost_file in &lost_files { let new_owner = gen_new_file_owner(&lost_file)?; // TODO: Maybe optimize this into one fat packet - probably a new operation? let new_owner_operation = NewFileOwnersOperation { distributed_filename: lost_file.clone(), new_owners: vec![new_owner].iter().map(|x| x.to_string()).collect() }; generated_operations.append(&mut new_owner_operation.execute(myself_source.clone())?); } log("Executed all new_owner operations locally".to_string()); Ok(generated_operations) }, false => { Ok(vec![]) } } } // Operations #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GetOperation { pub distributed_filename: String, pub local_path: String } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct NewFileOwnersOperation { pub distributed_filename: String, pub new_owners: HashSet<String> } #[derive(Serialize, Deserialize, Clone)] pub struct SendFileOperation { pub filename: String, pub data: Vec<u8>, pub is_distributed: bool } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct LostFilesOperation { pub failed_owner: String, pub lost_files: HashSet<String> } // Trait Impls impl OperationWriteExecute for GetOperation { fn to_bytes(&self) -> BoxedErrorResult<Vec<u8>> { Ok(create_buf(&self, str_to_vec("GET "))) } fn execute(&self, source: Source) -> BoxedErrorResult<Vec<SendableOperation>> { let local_path = distributed_file_path(&self.distributed_filename); let data_buf = async_std::task::block_on(read_file_to_buf(&local_path))?; let operation = SendableOperation::for_single_tcp_stream( TryInto::<async_std::net::TcpStream>::try_into(source)?, Box::new(SendFileOperation { filename: self.local_path.clone(), data: data_buf, is_distributed: false })); async_std::task::block_on(operation.write_all_tcp_async()); Ok(vec![]) } fn to_string(&self) -> String { format!("{:?}", self) } } impl OperationWriteExecute for NewFileOwnersOperation { fn to_bytes(&self) -> BoxedErrorResult<Vec<u8>> { Ok(create_buf(&self, str_to_vec("NFO "))) } fn execute(&self, source: Source) -> BoxedErrorResult<Vec<SendableOperation>> { // TODO: Add this file to your map with the new people that have it let mut all_file_owners = globals::ALL_FILE_OWNERS.get_mut(); let mut file_owners = all_file_owners.entry(self.distributed_filename.clone()).or_insert(HashSet::new()); match (&self.new_owners - file_owners).len() { 0 => { Ok(vec![]) }, _ => { *file_owners = &self.new_owners | file_owners; Ok(vec![SendableOperation::for_successors(Box::new(self.clone()))]) } } } fn to_string(&self) -> String { format!("{:?}", self) } } impl OperationWriteExecute for SendFileOperation { fn to_bytes(&self) -> BoxedErrorResult<Vec<u8>> { Ok(create_buf(&self, str_to_vec("FILE"))) } fn execute(&self, source: Source) -> BoxedErrorResult<Vec<SendableOperation>> { // TODO: Check if the file exists before overwriting let filename = match self.is_distributed { true => format!("{}/{}", constants::DATA_DIR, self.filename), false => self.filename.clone() }; let mut file = std::fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(filename)?; file.write_all(&self.data); Ok(vec![]) } fn to_string(&self) -> String { format!("{:?}", self) } } impl fmt::Debug for SendFileOperation { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let formatted_data = if self.data.len() > 40 { format!("{:?}...", &self.data[..40]) } else { format!("{:?}", &self.data) }; fmt.debug_struct("SendFileOperation") .field("filename", &self.filename) .field("data", &formatted_data) .field("is_distributed", &self.is_distributed) .finish() } } impl OperationWriteExecute for LostFilesOperation { fn to_bytes(&self) -> BoxedErrorResult<Vec<u8>> { Ok(create_buf(&self, str_to_vec("LOST"))) } fn execute(&self, source: Source) -> BoxedErrorResult<Vec<SendableOperation>> { let mut did_remove = false; let mut all_file_owners = globals::ALL_FILE_OWNERS.get_mut(); for lost_file in &self.lost_files { if let Some(owners) = all_file_owners.get_mut(lost_file) { did_remove |= owners.remove(&self.failed_owner); } } if did_remove { Ok(vec![SendableOperation::for_successors(Box::new(self.clone()))]) } else { Ok(vec![]) } } fn to_string(&self) -> String { format!("{:?}", self) } }
//! An exfiltrator providing the raw [`siginfo_t`]. // Note on unsafety in this module: // * Implementing an unsafe trait, that one needs to ensure at least store is async-signal-safe. // That's done by delegating to the Channel (and reading an atomic pointer, but that one is // primitive op). // * A bit of juggling with atomic and raw pointers. In effect, that is just late lazy // initialization, the Slot is in line with Option would be, except that it is set atomically // during the init. Lifetime is ensured by not dropping until the Drop of the whole slot and that // is checked by taking `&mut self`. use std::sync::atomic::{AtomicPtr, Ordering}; use libc::{c_int, siginfo_t}; use super::sealed::Exfiltrator; use crate::low_level::channel::Channel; #[doc(hidden)] #[derive(Default, Debug)] pub struct Slot(AtomicPtr<Channel<siginfo_t>>); impl Drop for Slot { fn drop(&mut self) { let ptr = self.0.load(Ordering::Acquire); if !ptr.is_null() { drop(unsafe { Box::from_raw(ptr) }); } } } /// The [`Exfiltrator`][crate::iterator::exfiltrator::Exfiltrator] that produces the raw /// [`libc::siginfo_t`]. Note that it might look differently on different OSes and its API is a /// little bit more limited than its C counterpart. /// /// You might prefer the [`WithOrigin`][super::WithOrigin] if you simply need information about the /// origin of the signal. /// /// # Examples /// /// ```rust /// # use signal_hook::consts::SIGUSR1; /// # use signal_hook::iterator::SignalsInfo; /// # use signal_hook::iterator::exfiltrator::WithRawSiginfo; /// # /// # fn main() -> Result<(), std::io::Error> { /// // Subscribe to SIGUSR1, with information about the process. /// let mut signals = SignalsInfo::<WithRawSiginfo>::new(&[SIGUSR1])?; /// /// // Send ourselves a signal. /// signal_hook::low_level::raise(SIGUSR1)?; /// /// // Grab the signal and look into the details. /// let received = signals.wait().next().unwrap(); /// /// // Not much else is useful in a cross-platform way :-( /// assert_eq!(SIGUSR1, received.si_signo); /// # Ok(()) } /// ``` #[derive(Copy, Clone, Debug, Default)] pub struct WithRawSiginfo; unsafe impl Exfiltrator for WithRawSiginfo { type Storage = Slot; type Output = siginfo_t; fn supports_signal(&self, _: c_int) -> bool { true } fn store(&self, slot: &Slot, _: c_int, info: &siginfo_t) { let info = *info; // Condition just not to crash if someone forgot to call init. // // Lifetime is from init to our own drop, and drop needs &mut self. if let Some(slot) = unsafe { slot.0.load(Ordering::Acquire).as_ref() } { slot.send(info); } } fn load(&self, slot: &Slot, _: libc::c_int) -> Option<siginfo_t> { let slot = unsafe { slot.0.load(Ordering::Acquire).as_ref() }; // Condition just not to crash if someone forgot to call init. slot.and_then(|s| s.recv()) } fn init(&self, slot: &Self::Storage, _: c_int) { let new = Box::default(); let old = slot.0.swap(Box::into_raw(new), Ordering::Release); // We leak the pointer on purpose here. This is invalid state anyway and must not happen, // but if it still does, we can't drop that while some other thread might still be having // the raw pointer. assert!(old.is_null(), "Init called multiple times"); } }
#[macro_export] macro_rules! duk_error { ($msg: expr) => { return Err($crate::error::ErrorKind::Error($msg.to_owned()).into()); }; } #[macro_export] macro_rules! duk_type_error { ($msg: expr) => { return Err($crate::error::ErrorKind::TypeError($msg.to_owned()).into()); }; } #[macro_export] macro_rules! duk_reference_error { ($msg: expr) => { return Err($crate::error::ErrorKind::ReferenceError($msg.to_owned()).into()); }; }
/* MIT License Copyright (c) 2017 Frederik Delaere Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::env; use std::fs::create_dir_all; use std::fs::File; use std::fs::OpenOptions; use std::io::{self, BufRead, BufReader, Write}; use std::os::unix::fs::symlink; use std::path::Path; extern crate shellexpand; use super::rsmod::crash; use regex::Regex; use users::get_current_uid; fn read_input(msg: &str) -> String { read_input_shell(msg, "noshell") } pub fn read_input_shell(msg: &str, shell: &str) -> String { if shell == "noshell" { print!("{}", msg); } else { print_stderr!("{}", msg); } io::stdout().flush().unwrap(); let mut line = String::new(); let stdin = io::stdin(); stdin.lock().read_line(&mut line).expect("Could not read line"); line } pub fn is_yes(answer: &str) -> bool { if answer == "Y\n" || answer == "y\n" || answer == "\n" || answer == "yes\n" || answer == "Yes\n" || answer == "YES\n" { return true; } false } fn print_title(title: &str) { println!(" {}", title); println!(" {:=<1$}", "=", title.len()); println!(); } fn update_setup_rsmodules_c_sh(recursive: bool, path: &str) { // no point in setting the env var, we are not running in the alias // env::set_var("MODULEPATH", path); // just update the setup_rsmodules.(c)sh files and copy them to /etc/profile.d // if no permissions, tell them if they are an admin to run this as root // or just throw it in .bashrc and .personal_cshrc -> or first check if let executable_path = env::current_exe().unwrap(); let executable_path = executable_path.parent(); let current_path_sh: &str = &format!("{}/setup_rsmodules.sh", executable_path.unwrap().display()); let current_path_csh: &str = &format!("{}/setup_rsmodules.csh", executable_path.unwrap().display()); let bash_result: bool; let csh_result: bool; let bash_result2: bool; let csh_result2: bool; // update init files before we link them if !Path::new(current_path_sh).is_file() { crash!( super::CRASH_MISSING_INIT_FILES, "{} should be in the same folder as {}", current_path_sh, env::current_exe().unwrap().display() ); } else { // add path to the file // use detect_line but with a regex: export MODULEPATH="(randomblah)" // and replace with export MODULEPATH="(randomblah):OURNEWPATH" bash_result = add_path(path, current_path_sh, "MODULEPATH", true); bash_result2 = add_path( &format!("{}", executable_path.unwrap().display()), current_path_sh, "RSMODULES_INSTALL_DIR", false, ); } if !Path::new(current_path_csh).is_file() { crash!( super::CRASH_MISSING_INIT_FILES, "{} should be in the same folder as {}", current_path_csh, env::current_exe().unwrap().display() ); } else { // add path to the file // use detect_line but with a regex: setenv MODULEPATH "(randomblah)" // and replace with setenv MODULEPATH "(randomblah):OURNEWPATH" csh_result = add_path(path, current_path_csh, "MODULEPATH", true); csh_result2 = add_path( &format!("{}", executable_path.unwrap().display()), current_path_csh, "RSMODULES_INSTALL_DIR", false, ); } if (bash_result || bash_result2) && (csh_result || csh_result2) { println!(); println!(" Successfully modified:"); } if bash_result || bash_result2 { println!(" - {}", current_path_sh); } if csh_result || csh_result2 { println!(" - {}", current_path_csh); } if get_current_uid() == 0 { let path_sh: &str = "/etc/profile.d/rsmodules.sh"; let path_csh: &str = "/etc/profile.d/rsmodules.csh"; if !Path::new(path_sh).exists() || !Path::new(path_csh).exists() { println!(); if !recursive { print_title("ENVIRONMENT SETUP"); } if is_yes(&read_input( " * rsmodules is not setup yet to autoload when a user \ opens a terminal. Do you want to do this now ? [Y/n]: ", )) { let mut bash_success: bool = false; let mut csh_success: bool = false; println!(); match symlink(current_path_sh, path_sh) { Ok(_) => { println!(" - Created symlink {} -> {}", current_path_sh, path_sh); bash_success = true; } Err(msg) => println!(" - Could not create symlink {} -> {} ({})", current_path_sh, path_sh, msg), } match symlink(current_path_csh, path_csh) { Ok(_) => { println!(" - Created symlink {} => {}", current_path_csh, path_csh); csh_success = true; } Err(msg) => println!( " - Could not create symlink {} => {} ({})", current_path_csh, path_csh, msg ), } if bash_success || csh_success { println!("\n On next login the command 'module' will be available."); println!(" To have it active in the current terminal, type this:"); println!(" bash or zsh : source {}", current_path_sh); println!(" csh or tcsh : source {}", current_path_csh); } } } } else { let path_sh: &str = &shellexpand::tilde("~/.rsmodules.sh"); let path_csh: &str = &shellexpand::tilde("~/.rsmodules.csh"); if !Path::new(path_sh).exists() || !Path::new(path_csh).exists() || !detect_line("source ~/.rsmodules.sh", &shellexpand::tilde("~/.bashrc")) || !detect_line("source ~/.rsmodules.csh", &shellexpand::tilde("~/.cshrc")) { println!(); if !recursive { print_title("ENVIRONMENT SETUP"); } if is_yes(&read_input( " * rsmodules is not setup yet to autoload when you \ open a new terminal.\n Do you want to do this now ? [Y/n]: ", )) { // want to link rsmodules to /home and add it to bashrc // read .cshrc and .bashrc line by line // to detect if source ~/rsmodules.(c)sh exists in it // read filename line by line, and push it to modules println!(); match symlink(current_path_sh, path_sh) { Ok(_) => println!(" - Created symlink {} => {}", current_path_sh, path_sh), Err(msg) => println!(" - Could not create symlink {} => {} ({})", current_path_sh, path_sh, msg), } match symlink(current_path_csh, path_csh) { Ok(_) => println!(" - Created symlink {} => {}", current_path_csh, path_csh), Err(msg) => println!( " - Could not create symlink {} => {} ({})", current_path_csh, path_csh, msg ), } let mut bash_updated: bool = true; let mut csh_updated: bool = true; let detected_sh: bool = detect_line("source ~/.rsmodules.sh", &shellexpand::tilde("~/.bashrc")); let detected_csh: bool = detect_line("source ~/.rsmodules.csh", &shellexpand::tilde("~/.cshrc")); if !detected_sh || !detected_csh { println!(); } if !detected_sh { bash_updated = append_line("source ~/.rsmodules.sh", &shellexpand::tilde("~/.bashrc"), true, false); } if !detected_csh { csh_updated = append_line("source ~/.rsmodules.csh", &shellexpand::tilde("~/.cshrc"), true, false); } if bash_updated || csh_updated { println!("\n On next login the command 'module' will be available."); println!("\n To have it active in the current terminal, type this:"); } if bash_updated { println!(" bash or zsh : source ~/.rsmodules.sh"); } if csh_updated { println!(" csh or tcsh : source ~/.rsmodules.csh"); } println!(); // create a dummy modules append_line( "prepend_path(\"PATH\",\"~/bin\")", &format!("{}/testmodule", path), false, false, ); append_line( "description(\"This is just a sample module, which adds ~/bin to your path\")", &format!("{}/testmodule", path), false, false, ); // tell them to run the module avail command println!(" Now run the command: module available"); } } } } pub fn append_line(line: &str, filename: &str, verbose: bool, stderr: bool) -> bool { let mut file: File = match OpenOptions::new().write(true).append(true).create(true).open(filename) { Ok(fileresult) => fileresult, Err(e) => { if stderr { eprintln!(" Error: cannot append to file {} ({})", filename, e); } else { println!(" - Cannot append to file {} ({})", filename, e); } return false; } }; if let Err(e) = writeln!(file, "{}", line) { crash( super::CRASH_CANNOT_ADD_TO_ENV, &format!("Cannot append to file {} ({})", filename, e), ); } if verbose { if stderr { eprintln!(" Succesfully added '{}' to {}", line, filename); } else { println!(" - Succesfully added '{}' to {}", line, filename); } } true } pub fn detect_line(line: &str, file: &str) -> bool { if Path::new(file).is_file() { let file: File = match File::open(file) { Ok(file) => file, Err(_) => { return false; } }; let file = BufReader::new(file); for (_, entry) in file.lines().enumerate() { let buffer = entry.unwrap(); if buffer == line { return true; } } } false } // go over the file line by line, do we have // a export MODULEPATH="" match, replace it // same for setenv MODULEPATH "" fn add_path(newpath: &str, filename: &str, variable: &str, append: bool) -> bool { let mut newbuffer: Vec<String> = Vec::new(); if Path::new(filename).is_file() { let file: File = match File::open(filename) { Ok(file) => file, Err(_) => { return false; } }; let file = BufReader::new(file); for (_, entry) in file.lines().enumerate() { let buffer = entry.unwrap(); newbuffer.push(set_path(&buffer, newpath, variable, append)); } } if !newbuffer.is_empty() { let mut file: File = match OpenOptions::new().write(true).open(filename) { Ok(fileresult) => fileresult, Err(e) => { println!(" - Cannot write to file {} ({})", filename, e); return false; } }; for newline in newbuffer { if let Err(e) = writeln!(file, "{}", newline) { crash( super::CRASH_CANNOT_ADD_TO_ENV, &format!("Cannot write to file {} ({})", filename, e), ); } } } true } // match against export MODULEPATH="" and setenv MODULEPATH "" // and add the new path to it fn set_path(input: &str, path: &str, variable: &str, append: bool) -> String { let re = Regex::new(&format!( r#"^\s*(?P<export>export|setenv)\s+{}(?P<equals>[= ]?)"(?P<value>.*)""#, variable )) .unwrap(); let mut output: String = input.to_string(); for cap in re.captures_iter(input) { let value = &cap["value"]; let value: Vec<&str> = value.split(':').collect(); for existing_path in &value { if existing_path == &path { return String::from(input); } } if append { if !(value.len() == 1 && value[0] == "" || value.is_empty()) { output = format!( r#"{} {}{}"{}:{}""#, &cap["export"], variable, &cap["equals"], &cap["value"], path ); } else { output = format!(r#"{} {}{}"{}""#, &cap["export"], variable, &cap["equals"], path); } } else { output = format!(r#"{} {}{}"{}""#, &cap["export"], variable, &cap["equals"], path); } } output } // if no modulepath variable found, or it is empty // start a wizard to add one to the path // if uid = 0 suggest /usr/local/modulefiles as // module path // else : suggest ~/modulefiles as module path // once a path is created and added to the // $MODULEPATH envvar, start wizard to // create a modulefile // also update the setup_rsmodules.(c)sh files // and ask to put them in /etc/profile.d // // if modulepath found, but it is empty // start a wizard to add a module file // if .modulecache doesn't exist // suggest the cache make command // // if modulepath found, and there are // module files but there is no .modulecache file // suggest the cache make command // // else // crash with the help pub fn run(recursive: bool) -> bool { let module_paths: Vec<String> = super::rsmod::get_module_paths(true); if module_paths.is_empty() { // TODO: ask if we have to copy rsmodules to a different folder // before we continue // "it looks like rsmodules isn't setup yet, blabla, do you want to" println!(); let mut line = if !recursive { print_title("MODULEPATH configuration"); read_input(" * No $MODULEPATH found, want to add one ? [Y/n]:") } else { String::new() }; if is_yes(&line) || recursive { let home_modules = &shellexpand::tilde("~/modules"); let mut path = if get_current_uid() == 0 { "/usr/local/modules" } else { home_modules }; line = read_input( format!( " * Please enter a path where you want to save your module \ files [{}]: ", path ) .as_ref(), ); if line != "\n" { /* let len = line.len(); line.truncate(len - 1); path = line.as_ref(); */ path = line.trim_end_matches('\n'); } if Path::new(path).is_dir() { if is_yes(&read_input( " * Path already exists, are you sure you want to continue ? \ [Y/n]: ", )) { update_setup_rsmodules_c_sh(false, path); return true; } else { return run(true); } } else if Path::new(path).is_file() { crash(super::CRASH_MODULEPATH_IS_FILE, "Modulepath cannot be a file"); return false; } else if is_yes(&read_input( format!( " * The folder {} doesn't exist, do you want to \ create it ? [Y/n]: ", path ) .as_ref(), )) { create_dir_all(path).unwrap(); println!(); println!(" - Succesfully created {}", path); update_setup_rsmodules_c_sh(false, path); return true; } else { println!(); println!(" ==== WARNING: Don't forget to create: {} ====", path); update_setup_rsmodules_c_sh(false, path); return true; } } } false }
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //! Light client components. use sp_core::traits::{CodeExecutor, SpawnNamed}; use sp_runtime::traits::{Block as BlockT, HashFor}; use std::sync::Arc; pub mod backend; pub mod blockchain; pub mod call_executor; pub mod fetcher; pub use {backend::*, blockchain::*, call_executor::*, fetcher::*}; /// Create an instance of fetch data checker. pub fn new_fetch_checker<E, B: BlockT, S: BlockchainStorage<B>>( blockchain: Arc<Blockchain<S>>, executor: E, spawn_handle: Box<dyn SpawnNamed>, ) -> LightDataChecker<E, HashFor<B>, B, S> where E: CodeExecutor, { LightDataChecker::new(blockchain, executor, spawn_handle) } /// Create an instance of light client blockchain backend. pub fn new_light_blockchain<B: BlockT, S: BlockchainStorage<B>>(storage: S) -> Arc<Blockchain<S>> { Arc::new(Blockchain::new(storage)) } /// Create an instance of light client backend. pub fn new_light_backend<B, S>(blockchain: Arc<Blockchain<S>>) -> Arc<Backend<S, HashFor<B>>> where B: BlockT, S: BlockchainStorage<B>, { Arc::new(Backend::new(blockchain)) }
use futures::stream::{Stream, BoxStream, MergedItem}; use futures::{Async, Future, Poll}; pub use neovim_lib::{Neovim, NeovimApi, Session}; use slog::*; use std::sync::mpsc; use std::sync::Mutex; use std::collections::VecDeque; use broker::Event; mod rpc_types; pub use self::rpc_types::NeovimRPCEvent; pub type NeovimRPCError = (); pub fn attach_to_neovim(logger: Logger) -> (Neovim, NeovimEventStream) { let nvim_session = Session::new_tcp("127.0.0.1:6666").unwrap(); let mut nvim = Neovim::new(nvim_session); let event_handler = NeovimEventStream::new(logger, &mut nvim); (nvim, event_handler) } const NEOVIM_EVENT_TYPES: &'static [&'static str] = &[ "language_server_new_cursor_position", "language_server_text_changed", "lsp/bufread" ]; pub struct NeovimEventStream { logger: Logger, receiver: mpsc::Receiver<NeovimRPCEvent> } impl NeovimEventStream { pub fn new(logger: Logger, nvim: &mut Neovim) -> Self { let (sender, receiver) = mpsc::channel::<NeovimRPCEvent>(); info!(logger, "Starting the neovim event loop"); nvim.session.start_event_loop_cb(move |event, values| { sender.send(NeovimRPCEvent::new(event, values).unwrap()); }); info!(logger, "Subscribing to neovim events"); for event_type in NEOVIM_EVENT_TYPES { nvim.subscribe(event_type); } NeovimEventStream { logger: logger, receiver: receiver, } } } impl Stream for NeovimEventStream { type Item = NeovimRPCEvent; type Error = (); fn poll(&mut self) -> Poll<Option<NeovimRPCEvent>, ()> { match self.receiver.recv() { Ok(event) => Ok(Async::Ready(Some(event))), Err(_) => Ok(Async::NotReady), } } }
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Authorship Primitives #![cfg_attr(not(feature = "std"), no_std)] use sp_std::{prelude::*, result::Result}; use codec::{Decode, Encode}; use sp_inherents::{Error, InherentData, InherentIdentifier, IsFatalError}; use sp_runtime::RuntimeString; /// The identifier for the `uncles` inherent. pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"uncles00"; /// Errors that can occur while checking the authorship inherent. #[derive(Encode, sp_runtime::RuntimeDebug)] #[cfg_attr(feature = "std", derive(Decode))] pub enum InherentError { Uncles(RuntimeString), } impl IsFatalError for InherentError { fn is_fatal_error(&self) -> bool { match self { InherentError::Uncles(_) => true, } } } /// Auxiliary trait to extract uncles inherent data. pub trait UnclesInherentData<H: Decode> { /// Get uncles. fn uncles(&self) -> Result<Vec<H>, Error>; } impl<H: Decode> UnclesInherentData<H> for InherentData { fn uncles(&self) -> Result<Vec<H>, Error> { Ok(self.get_data(&INHERENT_IDENTIFIER)?.unwrap_or_default()) } } /// Provider for inherent data. #[cfg(feature = "std")] pub struct InherentDataProvider<F, H> { inner: F, _marker: std::marker::PhantomData<H>, } #[cfg(feature = "std")] impl<F, H> InherentDataProvider<F, H> { pub fn new(uncles_oracle: F) -> Self { InherentDataProvider { inner: uncles_oracle, _marker: Default::default() } } } #[cfg(feature = "std")] impl<F, H: Encode + std::fmt::Debug> sp_inherents::ProvideInherentData for InherentDataProvider<F, H> where F: Fn() -> Vec<H>, { fn inherent_identifier(&self) -> &'static InherentIdentifier { &INHERENT_IDENTIFIER } fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), Error> { let uncles = (self.inner)(); if !uncles.is_empty() { inherent_data.put_data(INHERENT_IDENTIFIER, &uncles) } else { Ok(()) } } fn error_to_string(&self, _error: &[u8]) -> Option<String> { Some(format!("no further information")) } }
use bevy::{ math::*, render2::{ color::Color, }, }; #[derive(Debug, Clone)] pub struct Bloom { pub threshold: f32, pub intensity: f32, pub scatter: f32, pub tint: Color, pub clamp: f32, } impl Default for Bloom { fn default() -> Self { Self { threshold: 0.9, intensity: 0.0, scatter: 0.7, tint: Color::WHITE, clamp: 65472.0, } } } #[derive(Debug, Clone)] pub struct ChannelMixing { red: Color, blue: Color, green: Color, } impl ChannelMixing { pub fn red(&self) -> Color { self.red.clone() } pub fn blue(&self) -> Color { self.blue.clone() } pub fn green(&self) -> Color { self.green.clone() } pub fn red_mut(&mut self) -> &mut Color { &mut self.red } pub fn blue_mut(&mut self) -> &mut Color { &mut self.blue } pub fn green_mut(&mut self) -> &mut Color { &mut self.green } } impl Default for ChannelMixing { fn default() -> Self { Self { red: Color::RED, blue: Color::BLUE, green: Color::GREEN, } } } impl From<ChannelMixing> for Mat3 { fn from(value: ChannelMixing) -> Self { Mat3::from_cols( Vec4::from(value.red).xyz(), Vec4::from(value.blue).xyz(), Vec4::from(value.green).xyz(), ).transpose() } } #[derive(Debug, Clone)] pub struct NormalTonemapping; #[derive(Debug, Clone)] pub struct ACESTonemapping;
pub mod api_info; pub mod api_response;
use uart_16550::SerialPort; use spin::Mutex; use lazy_static::lazy_static; use core::fmt; lazy_static! { static ref SERIAL1: Mutex<SerialPort> = { let mut sp = unsafe { SerialPort::new(0x03F8 as u16) }; sp.init(); Mutex::new(sp) }; } #[macro_export] macro_rules! serial_print { ($($arg:tt)*) => ($crate::serial::_print(format_args!($($arg)*))); } #[macro_export] macro_rules! serial_println { () => ($crate::print!("\n")); ($($arg:tt)*) => ($crate::serial_print!("{}\n", format_args!($($arg)*))); } #[doc(hidden)] pub fn _print(args: fmt::Arguments) { use core::fmt::Write; use x86_64::instructions::interrupts; interrupts::without_interrupts(|| { SERIAL1.lock().write_fmt(args).expect("Printing to serial port failed"); }); }
pub const CONVERT_TEMP: u8 = 0x44; pub const WRITE_SCRATCHPAD: u8 = 0x4E; pub const READ_SCRATCHPAD: u8 = 0xBE; pub const COPY_SCRATCHPAD: u8 = 0x48; pub const RECALL_EEPROM: u8 = 0xB8;
#[allow(non_camel_case_types,dead_code)] pub enum Layout { None = 0, PIP4_In = 1, PIP4_Out = 2, PIP3_Vert_1_2 = 3, PIP3_Vert_2_1 = 4, } pub fn layout(layout: Layout) -> Vec<String> { vec![String::from(format!("{}pL", layout as u8))] }
use std::io::stdout; use crossterm::{cursor, style, terminal, ExecutableCommand, Result}; /// Prints a string in the middle of the terminal output fn main() -> Result<()> { // get terminal size let (terminal_width, terminal_height) = terminal::size()?; // string to print out let string_to_print = "this string is in the middle of the terminal"; // define coordinates of where the string should be printed let move_to_x = (terminal_width / 2) - (string_to_print.len() as u16 / 2); let move_to_y = terminal_height / 2; // print string in the middle of the terminal stdout() .execute(terminal::Clear(terminal::ClearType::All))? // clear all other output in the terminal .execute(cursor::MoveTo(move_to_x, move_to_y))? // move cursor to the middle of the terminal .execute(style::SetForegroundColor(style::Color::Black))? // set the color of the text .execute(style::SetBackgroundColor(style::Color::Red))? // set the color of the background of the text .execute(style::Print(string_to_print))? // print the string .execute(cursor::MoveTo(terminal_width, terminal_height))? // move cursor to the end of the terminal .execute(style::ResetColor)?; // reset colors back to the default Ok(()) }
use diesel::{ pg::PgConnection, r2d2::{ConnectionManager, Pool as PgPool, PooledConnection}, }; /* * ========= * Internals * ========= */ pub type Connection = PooledConnection<ConnectionManager<PgConnection>>; #[derive(Clone)] pub struct Postgres { pool: PgPool<ConnectionManager<PgConnection>>, } impl Postgres { pub fn new(url: impl Into<String>) -> Postgres { let manager = ConnectionManager::<PgConnection>::new(url); let pool = PgPool::new(manager).unwrap(); Postgres { pool } } pub async fn with_conn<T, F>(&self, func: F) -> anyhow::Result<T> where F: FnOnce(Connection) -> T + Send + 'static, T: Send + 'static, { let pool = self.pool.clone(); tokio::task::spawn_blocking(move || Ok(func(pool.get()?))).await? } pub async fn try_with_conn<T, F>(&self, func: F) -> anyhow::Result<T> where F: FnOnce(Connection) -> anyhow::Result<T> + Send + 'static, T: Send + 'static, { self.with_conn(func).await? } }
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use super::{Address, EmailSubmission, Envelope, SetArguments, UndoStatus}; use crate::{core::set::SetObject, email::Email, Get, Set}; use ahash::AHashMap; impl EmailSubmission<Set> { pub fn identity_id(&mut self, identity_id: impl Into<String>) -> &mut Self { self.identity_id = Some(identity_id.into()); self } pub fn email_id(&mut self, email_id: impl Into<String>) -> &mut Self { self.email_id = Some(email_id.into()); self } pub fn envelope<S, T, U>(&mut self, mail_from: S, rcpt_to: T) -> &mut Self where S: Into<Address>, T: IntoIterator<Item = U>, U: Into<Address>, { self.envelope = Some(Envelope::new(mail_from, rcpt_to)); self } pub fn undo_status(&mut self, undo_status: UndoStatus) -> &mut Self { self.undo_status = Some(undo_status); self } } impl SetObject for EmailSubmission<Set> { type SetArguments = SetArguments; fn new(_create_id: Option<usize>) -> Self { EmailSubmission { _create_id, _state: Default::default(), id: None, identity_id: None, email_id: None, thread_id: None, envelope: None, send_at: None, undo_status: None, delivery_status: None, dsn_blob_ids: None, mdn_blob_ids: None, } } fn create_id(&self) -> Option<String> { self._create_id.map(|id| format!("c{}", id)) } } impl SetObject for EmailSubmission<Get> { type SetArguments = SetArguments; fn new(_create_id: Option<usize>) -> Self { unimplemented!() } fn create_id(&self) -> Option<String> { None } } impl Envelope { pub fn new<S, T, U>(mail_from: S, rcpt_to: T) -> Envelope where S: Into<Address>, T: IntoIterator<Item = U>, U: Into<Address>, { Envelope { mail_from: mail_from.into(), rcpt_to: rcpt_to.into_iter().map(|s| s.into()).collect(), } } } impl Address<Set> { pub fn new(email: impl Into<String>) -> Address<Set> { Address { _state: Default::default(), email: email.into(), parameters: None, } } pub fn parameter( mut self, parameter: impl Into<String>, value: Option<impl Into<String>>, ) -> Self { self.parameters .get_or_insert_with(AHashMap::new) .insert(parameter.into(), value.map(|s| s.into())); self } } impl From<String> for Address { fn from(email: String) -> Self { Address { _state: Default::default(), email, parameters: None, } } } impl From<&str> for Address { fn from(email: &str) -> Self { Address { _state: Default::default(), email: email.to_string(), parameters: None, } } } impl From<Address<Set>> for Address<Get> { fn from(addr: Address<Set>) -> Self { Address { _state: Default::default(), email: addr.email, parameters: addr.parameters, } } } impl From<Address<Get>> for Address<Set> { fn from(addr: Address<Get>) -> Self { Address { _state: Default::default(), email: addr.email, parameters: addr.parameters, } } } impl SetArguments { pub fn on_success_update_email(&mut self, id: impl Into<String>) -> &mut Email<Set> { self.on_success_update_email_(format!("#{}", id.into())) } pub fn on_success_update_email_id(&mut self, id: impl Into<String>) -> &mut Email<Set> { self.on_success_update_email_(id) } fn on_success_update_email_(&mut self, id: impl Into<String>) -> &mut Email<Set> { let id = id.into(); self.on_success_update_email .get_or_insert_with(AHashMap::new) .insert(id.clone(), Email::new(None)); self.on_success_update_email .as_mut() .unwrap() .get_mut(&id) .unwrap() } pub fn on_success_destroy_email(&mut self, id: impl Into<String>) -> &mut Self { self.on_success_destroy_email .get_or_insert_with(Vec::new) .push(format!("#{}", id.into())); self } pub fn on_success_destroy_email_id(&mut self, id: impl Into<String>) -> &mut Self { self.on_success_destroy_email .get_or_insert_with(Vec::new) .push(id.into()); self } }
#[doc = "Register `CTR` reader"] pub type R = crate::R<CTR_SPEC>; #[doc = "Register `CTR` writer"] pub type W = crate::W<CTR_SPEC>; #[doc = "Field `EN` reader - Cache enable"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - Cache enable"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PCACHEADDR` reader - Cacheable page index"] pub type PCACHEADDR_R = crate::FieldReader<u16>; #[doc = "Field `PCACHEADDR` writer - Cacheable page index"] pub type PCACHEADDR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 12, O, u16>; impl R { #[doc = "Bit 0 - Cache enable"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 1) != 0) } #[doc = "Bits 8:19 - Cacheable page index"] #[inline(always)] pub fn pcacheaddr(&self) -> PCACHEADDR_R { PCACHEADDR_R::new(((self.bits >> 8) & 0x0fff) as u16) } } impl W { #[doc = "Bit 0 - Cache enable"] #[inline(always)] #[must_use] pub fn en(&mut self) -> EN_W<CTR_SPEC, 0> { EN_W::new(self) } #[doc = "Bits 8:19 - Cacheable page index"] #[inline(always)] #[must_use] pub fn pcacheaddr(&mut self) -> PCACHEADDR_W<CTR_SPEC, 8> { PCACHEADDR_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 = "control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ctr::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 [`ctr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CTR_SPEC; impl crate::RegisterSpec for CTR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ctr::R`](R) reader structure"] impl crate::Readable for CTR_SPEC {} #[doc = "`write(|w| ..)` method takes [`ctr::W`](W) writer structure"] impl crate::Writable for CTR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CTR to value 0x04"] impl crate::Resettable for CTR_SPEC { const RESET_VALUE: Self::Ux = 0x04; }
#[doc = "Register `PCR3` reader"] pub type R = crate::R<PCR3_SPEC>; #[doc = "Register `PCR3` writer"] pub type W = crate::W<PCR3_SPEC>; #[doc = "Field `PWAITEN` reader - PWAITEN"] pub type PWAITEN_R = crate::BitReader; #[doc = "Field `PWAITEN` writer - PWAITEN"] pub type PWAITEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PBKEN` reader - PBKEN"] pub type PBKEN_R = crate::BitReader; #[doc = "Field `PBKEN` writer - PBKEN"] pub type PBKEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PTYP` reader - PTYP"] pub type PTYP_R = crate::BitReader; #[doc = "Field `PTYP` writer - PTYP"] pub type PTYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PWID` reader - PWID"] pub type PWID_R = crate::FieldReader; #[doc = "Field `PWID` writer - PWID"] pub type PWID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `ECCEN` reader - ECCEN"] pub type ECCEN_R = crate::BitReader; #[doc = "Field `ECCEN` writer - ECCEN"] pub type ECCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TCLR` reader - TCLR"] pub type TCLR_R = crate::FieldReader; #[doc = "Field `TCLR` writer - TCLR"] pub type TCLR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `TAR` reader - TAR"] pub type TAR_R = crate::FieldReader; #[doc = "Field `TAR` writer - TAR"] pub type TAR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `ECCPS` reader - ECCPS"] pub type ECCPS_R = crate::FieldReader; #[doc = "Field `ECCPS` writer - ECCPS"] pub type ECCPS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; impl R { #[doc = "Bit 1 - PWAITEN"] #[inline(always)] pub fn pwaiten(&self) -> PWAITEN_R { PWAITEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - PBKEN"] #[inline(always)] pub fn pbken(&self) -> PBKEN_R { PBKEN_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - PTYP"] #[inline(always)] pub fn ptyp(&self) -> PTYP_R { PTYP_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bits 4:5 - PWID"] #[inline(always)] pub fn pwid(&self) -> PWID_R { PWID_R::new(((self.bits >> 4) & 3) as u8) } #[doc = "Bit 6 - ECCEN"] #[inline(always)] pub fn eccen(&self) -> ECCEN_R { ECCEN_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bits 9:12 - TCLR"] #[inline(always)] pub fn tclr(&self) -> TCLR_R { TCLR_R::new(((self.bits >> 9) & 0x0f) as u8) } #[doc = "Bits 13:16 - TAR"] #[inline(always)] pub fn tar(&self) -> TAR_R { TAR_R::new(((self.bits >> 13) & 0x0f) as u8) } #[doc = "Bits 17:19 - ECCPS"] #[inline(always)] pub fn eccps(&self) -> ECCPS_R { ECCPS_R::new(((self.bits >> 17) & 7) as u8) } } impl W { #[doc = "Bit 1 - PWAITEN"] #[inline(always)] #[must_use] pub fn pwaiten(&mut self) -> PWAITEN_W<PCR3_SPEC, 1> { PWAITEN_W::new(self) } #[doc = "Bit 2 - PBKEN"] #[inline(always)] #[must_use] pub fn pbken(&mut self) -> PBKEN_W<PCR3_SPEC, 2> { PBKEN_W::new(self) } #[doc = "Bit 3 - PTYP"] #[inline(always)] #[must_use] pub fn ptyp(&mut self) -> PTYP_W<PCR3_SPEC, 3> { PTYP_W::new(self) } #[doc = "Bits 4:5 - PWID"] #[inline(always)] #[must_use] pub fn pwid(&mut self) -> PWID_W<PCR3_SPEC, 4> { PWID_W::new(self) } #[doc = "Bit 6 - ECCEN"] #[inline(always)] #[must_use] pub fn eccen(&mut self) -> ECCEN_W<PCR3_SPEC, 6> { ECCEN_W::new(self) } #[doc = "Bits 9:12 - TCLR"] #[inline(always)] #[must_use] pub fn tclr(&mut self) -> TCLR_W<PCR3_SPEC, 9> { TCLR_W::new(self) } #[doc = "Bits 13:16 - TAR"] #[inline(always)] #[must_use] pub fn tar(&mut self) -> TAR_W<PCR3_SPEC, 13> { TAR_W::new(self) } #[doc = "Bits 17:19 - ECCPS"] #[inline(always)] #[must_use] pub fn eccps(&mut self) -> ECCPS_W<PCR3_SPEC, 17> { ECCPS_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 = "PC Card/NAND Flash control register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pcr3::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 [`pcr3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PCR3_SPEC; impl crate::RegisterSpec for PCR3_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`pcr3::R`](R) reader structure"] impl crate::Readable for PCR3_SPEC {} #[doc = "`write(|w| ..)` method takes [`pcr3::W`](W) writer structure"] impl crate::Writable for PCR3_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets PCR3 to value 0x18"] impl crate::Resettable for PCR3_SPEC { const RESET_VALUE: Self::Ux = 0x18; }
fn factorial(n:i32) { let mut fac = n; let mut index = n; if fac < 0 { fac = 0; } else if fac == 0 { fac = 1; } else { while (index - 1) >= 1 { fac *= index - 1; index -= 1; } } println!("{}", fac); } fn main() { factorial(3); }
pub use glyph_brush::Layout as TextLayout; pub use glyph_brush::Section as TextSection; pub use glyph_brush::Text;
//! # Adafruit_gps //! This is a port from the adafruit python code that reads the output from their GPS systems. //! This crate has been tested on a MTK3339 chip on a raspberry pi zero. //! //! ## Links //! - Python code: https://github.com/adafruit/Adafruit_CircuitPython_GPS //! - GPS module docs: https://learn.adafruit.com/adafruit-ultimate-gps/ //! - PMTK commands https://cdn-shop.adafruit.com/datasheets/PMTK_A11.pdf //! //! ## Modules //! The PMTK module is a way of easily sending command to the GPS, changing it's settings. //! //! The nmea module reads the data given by the GPS. Use the gps.update() trait to get easy to use //! data, but for specific use cases custom commands can be read. //! //! ## Hardware specs //! Please read the docs for the specific GPS module you are using. //! //! Update rate is likely 1Hz to 10Hz. //! If increasing the update rate, the baud rate may also need to be increased. //! A rule of thumb is, one sentence is 256 bytes -> at 9600 baud rate, 37.5 sentences per second. //! //! # Module Outputs //! gps.update() outputs a GpsSentence enum which mostly gives other structs for different sentence types //! //! GpsSentence enum types: //! - GGA(GgaData) -> [GgaData](nmea/gga/struct.GgaData.html): Latitude, Longitude, Position fix, Satellites seen, HDOP, altitude, Geoidal Seperation, Age of difference correction. //! - VTG(VtgData) -> [VtgData](nmea/vtg/struct.VtgData.html): Course (true), Course (magnetic), speed knots, speed kph. //! - GSA(GsaData) -> [GsaData](nmea/gsa/struct.GsaData.html): List of satellites used, PDOP, HDOP, VDOP. //! - GSV(Vec<Satellites>) -> [Satellites](nmea/gsv/struct.Satellites.html): Satellites in view data: sat id, elevation, azimuth and SNR for each sat seen. //! - GLL(GllData) -> [GllData](nmea/gll/struct.GllData.html): Latitude, Longitude only. //! - RMC(RmcData) -> [RmcData](nmea/rmc/struct.RmcData.html): UTC, Latitude, Longitude, speed, course, date, magnetic variation. //! - NoConnection -> The gps is not connected, no bytes are being received //! - InvalidBytes -> Bytes being received are not valid, probably port baud rate and gps baud rate mismatch //! - InvalidSentence -> Sentence outputted has incorrect checksum, the sentence was probably incomplete. //! //! # Some technical information //! ## Dilution of precision //! DOP is dilution of precision, a measure of error based on the position of the satellites. //! The smaller the number the better (1 is excellent). //! //! The DOP is determined by the arrangement of the satellites being tracked. //! The DOP can be either vertical or horizontal as different satellite arrangements affect the //! vertical and horizontal DOP differently. //! //! See [This wikipeia page](https://en.wikipedia.org/wiki/Dilution_of_precision_(navigation)) for details //! //! ## Geoid and Mean sea level //! Measuring height is difficult because where 0m is exactly is hard to establish. //! //! The geoid is the shape that the ocean would take under the influence of gravity and the earth's //! rotation alone, ignoring tides and wind. //! //! The WGS84 ellipsoid is the ideal smooth surface shape of the earth, with no mountains or trenches. //! //! The height of the geoid given by GgaData geoidal_sep is the difference between the geoid and the //! WGS84 ellipsoid. It ranges from +85 m to -106 m. //! //! A reading of +47 for geoidal_sep means the geoid is 47 metres above the WGS84 ellipsoid. //! //! Mean sea level is locally defined and changes depending on location. Therefore, altitude given //! by the gps is, in my opinion, not overly useful for precise elevation, but rather is useful in //! measuring the difference in height between objects. //! //! ## Saving data //! GpsSentence types can be written and read to a bytes file using the the append_to() and read_from() //! traits: See examples/example_io.rs for details. //! ``` //! use adafruit_gps::GpsSentence; //! use adafruit_gps::gga::GgaData; //! let data: Vec<GpsSentence> = GpsSentence::read_from("file"); // Read from file //! //! GpsSentence::GGA(GgaData::default()).append_to("file"); // Append a single item to a file //! ``` //! //! //! pub use crate::nmea::{gga, gll, gsa, gsv, rmc, vtg}; pub use crate::open_gps::gps::{Gps, GpsSentence}; pub use crate::pmtk::send_pmtk::{set_baud_rate, NmeaOutput}; mod nmea; mod pmtk; mod open_gps;
pub mod active_lineager_sampler; pub mod emigration_exit; pub mod event_sampler;
#[doc = "Register `ITLINE15` reader"] pub type R = crate::R<ITLINE15_SPEC>; #[doc = "Field `TIM2` reader - TIM2"] pub type TIM2_R = crate::BitReader; impl R { #[doc = "Bit 0 - TIM2"] #[inline(always)] pub fn tim2(&self) -> TIM2_R { TIM2_R::new((self.bits & 1) != 0) } } #[doc = "interrupt line 15 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`itline15::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ITLINE15_SPEC; impl crate::RegisterSpec for ITLINE15_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`itline15::R`](R) reader structure"] impl crate::Readable for ITLINE15_SPEC {} #[doc = "`reset()` method sets ITLINE15 to value 0"] impl crate::Resettable for ITLINE15_SPEC { const RESET_VALUE: Self::Ux = 0; }
use day02::{part_1, part_2}; fn main() { let result_1 = part_1(12, 2); println!("The result of the program part 1 is {}", result_1); match part_2(19690720) { Some((input_1, input_2)) => { println!("The noun={} and the verb={}", input_1, input_2); println!("Thus the answer is {}", input_1* 100 + input_2); }, None => eprintln!("No input could be found to given output") }; }
mod app; mod gif; mod camera; mod wgpu_state; mod draw; pub use wgpu_state::WgpuState; pub use self::app::render_window; #[cfg(target_arch = "wasm32")] pub use self::app::render_window_wasm; pub use self::gif::render_gif; pub use self::gif::render_gif_blocking;
#![feature(split_ascii_whitespace)] use lazy_static::lazy_static; type Datum = u8; struct Node { children: Vec<Node>, metadata: Vec<Datum>, } impl Node { fn build<I: Iterator<Item = Datum>>(iter: &mut I) -> Self { let num_children = iter.next().unwrap(); let num_metadata = iter.next().unwrap(); Node { children: (0..num_children).map(|_| Node::build(iter)).collect(), metadata: (0..num_metadata).map(|_| iter.next().unwrap()).collect(), } } fn sum_metadata(&self) -> u32 { let mut sum = self.metadata.iter().map(|&x| u32::from(x)).sum::<u32>(); for child in &self.children { sum += child.sum_metadata(); } sum } fn value(&self) -> u32 { if self.children.is_empty() { self.metadata.iter().map(|&x| u32::from(x)).sum::<u32>() } else { self.metadata .iter() .filter(|&&i| i > 0 && i as usize <= self.children.len()) .fold(0, |acc, &i| acc + self.children[i as usize - 1].value()) } } } lazy_static! { static ref TREE: Node = { let mut input = include_str!("input.txt") .split_ascii_whitespace() .map(|s| s.parse().unwrap()); Node::build(&mut input) }; } fn part1() { println!("{}", TREE.sum_metadata()); } fn part2() { println!("{}", TREE.value()); } fn main() { part1(); part2(); }
pub mod models; pub mod operations; #[allow(dead_code)] pub const API_VERSION: &str = "2021-10-15";
// TODO : In the future registry will be downloaded from this repository. // https://github.com/vincent-herlemont/short-template-index use std::collections::HashSet; use std::fs::{read_dir, read_to_string}; use std::path::Path; use anyhow::{Context, Result}; use git2::Repository; use crate::template::template::Template; const DEFAULT_REPOSITORY_URL: &'static str = "https://github.com/vincent-herlemont/short-template-index"; #[derive(Debug)] pub struct Registry { index: HashSet<Template>, } impl Registry { pub fn checkout(target_dir: &Path) -> Result<Self> { let url = option_env!("SHORT_REPOSITORY_URL").unwrap_or(DEFAULT_REPOSITORY_URL); Repository::clone(url, target_dir).context("fail to clone registry repository")?; let mut registry = Registry { index: HashSet::new(), }; for dir_entry in read_dir(target_dir)? { let dir_entry = dir_entry?; let path = dir_entry.path(); if path.is_file() { if let Some(extension) = path.extension() { if extension != "json" { continue; } } let content = read_to_string(&path)?; let mut template: Template = serde_json::from_str(&content)?; let name = path .file_stem() .context("fail to get file name")? .to_string_lossy() .into_owned(); template.set_name(name); registry.index.insert(template); } } Ok(registry) } pub fn index(&self) -> &HashSet<Template> { &self.index } pub fn get(&self, name: &str) -> Result<Template> { let template = self .index .iter() .find(|template| template.name() == name) .context(format!("template `{}` not found", name))?; let template = Template::new(template.name().clone(), template.url().clone()); Ok(template) } } #[cfg(test)] mod tests { use cli_integration_test::IntegrationTestEnvironment; use serde_json::from_str; use crate::template::Registry; use crate::template::Template; #[test] fn deserialize_json() { let entry: Template = from_str( "{ \"url\" : \"https://github.com/vincent-herlemont/test-short-template.git\" }", ) .unwrap(); assert_eq!( entry.url(), "https://github.com/vincent-herlemont/test-short-template.git" ); } #[test] fn checkout() { let e = IntegrationTestEnvironment::new("registry_checkout"); let registry = Registry::checkout(e.path().unwrap().as_ref()).unwrap(); let _template = registry.get("test").unwrap(); } }
fn main() { // 変数のポインタを取得する let a: i32 = 10 ; let a_ptr: *const i32 = &a ; println!("a is {:?}", a ); println!("a_ptr is {:?}", a_ptr ); // 文字列のポインタを取得する let a = "rust" ; println!("a is {:?}", a ); println!("a_ptr is {:?}", a.as_ptr() ); } fn main2() { let a = Person{name: "masuda", age: 50 }; println!("a is {:?}", a ); // 変数b に move する let b = a ; println!("b is {:?}", b ); // 既に move しているので使えない // println!("a is {:?}", a ); } fn main3(){ let a = Person{name: "masuda", age: 50 }; let a_ptr: *const Person = &a; println!("a is {:?}", a ); println!("a_ptr is {:?}", a_ptr ); println!("a.name.ptr is {:?}", a.name.as_ptr()); // 変数b に move する let b = a ; let b_ptr: *const Person = &b; println!("b is {:?}", b ); println!("b_ptr is {:?}", b_ptr ); println!("b.name.ptr is {:?}", b.name.as_ptr()); // 既に move しているので使えない // println!("a is {:?}", a ); } fn main4() { let a = Person{name: "masuda", age: 50 }; let a_ptr: *const Person = &a; println!("a is {:?}", a ); println!("a_ptr is {:?}", a_ptr ); println!("a.name.ptr is {:?}", a.name.as_ptr()); // 変数b に borrow する let b = &a ; let b_ptr: *const Person = b; println!("b is {:?}", b ); println!("b_ptr is {:?}", b_ptr ); println!("b.name.ptr is {:?}", b.name.as_ptr()); // 借用なので変数aが利用できる println!("a is {:?}", a ); } fn main5() { let a: i32 = 100; println!("a is {:?}", a ); // 変数b に copy する let b = a ; let b_ptr: *const i32 = &b; println!("b is {:?}", b ); // copy なので変数aが利用できる println!("a is {:?}", a ); } fn main6() { let a: i32 = 100; let a_ptr: *const i32 = &a; println!("a is {:?}", a ); println!("a_ptr is {:?}", a_ptr ); // 変数b に copy する let b = a ; let b_ptr: *const i32 = &b; println!("b is {:?}", b ); println!("b_ptr is {:?}", b_ptr ); // copy なので変数aが利用できる println!("a is {:?}", a ); } #[derive(Debug)] struct Person { name: &'static str, age: i32, }
#![allow(non_snake_case)] use aes_gcm::Aes256Gcm; use aead::{NewAead, AeadInPlace}; use crate::utils; use crate::encoder::EncoderBasicTrait; #[derive(Clone)] pub struct AES256GCM { key_bytes: [u8;32], size_xor_bytes: [u8;32], cipher: Aes256Gcm, } impl AES256GCM { pub fn new(KEY:&'static str, otp:u32) -> AES256GCM { AES256GCM { key_bytes:utils::get_key_bytes(KEY, otp), size_xor_bytes: utils::get_size_xor_bytes(KEY, otp), cipher: Aes256Gcm::new(&utils::get_key_bytes(KEY,otp).into()), } } fn encode_data_size(&self, size: usize, random_bytes:&[u8]) -> [u8;2] { //assert!(size<=65536); [ (size >> 8) as u8 ^ self.size_xor_bytes[(random_bytes[0] % 32) as usize], (size & 0xff) as u8 ^ self.size_xor_bytes[(random_bytes[1] % 32) as usize] ] } fn decode_data_size(&self, bytes: &[u8], random_bytes: &[u8]) -> usize { ( (((bytes[0] as u16) ^ (self.size_xor_bytes[(random_bytes[0] % 32) as usize]) as u16) << 8) + (bytes[1] ^ self.size_xor_bytes[(random_bytes[1] % 32) as usize]) as u16 ) as usize } fn encode_random_size(&self, random_bytes:&[u8]) -> u8 { (random_bytes.len() as u8) ^ (self.size_xor_bytes[(random_bytes[0] % 32) as usize ]) } fn decode_random_size(&self, random_size:u8, random_bytes_0:u8) -> usize { (random_size ^ (self.size_xor_bytes[(random_bytes_0 % 32) as usize])) as usize } } impl EncoderBasicTrait for AES256GCM{ fn encode(&self, data: &mut [u8], data_len:usize) -> usize { let (random_size, random_bytes) = utils::get_random_bytes(); let nounce = &random_bytes[ .. 12]; let aad = &self.key_bytes[ .. 8]; let data_start = 1 + random_size + 2 + 16; let tag = self.cipher.encrypt_in_place_detached(nounce.into(), aad, &mut data[..data_len]).unwrap(); data.copy_within(0..data_len, data_start); data[0] = self.encode_random_size(&random_bytes); data[1 .. random_size+ 1].copy_from_slice(&random_bytes); data[1 + random_size .. 1 + random_size + 2].copy_from_slice(&self.encode_data_size(data_len, &random_bytes[..2])); data[data_start - 16 .. data_start].copy_from_slice(&tag); data_start + data_len } fn decode(&self, data: &mut [u8]) -> (usize, i32) { let input_len = data.len(); let random_size = self.decode_random_size(data[0], data[1]); let left_shall_be_read:i32 = (1 + random_size + 2 + 16) as i32 - (input_len as i32); if left_shall_be_read > 33 || random_size < 12 { return (0, -1) } else if left_shall_be_read > 0 { return (0, left_shall_be_read) } let mut random_bytes = vec![0u8; random_size]; random_bytes.copy_from_slice(&data[1 .. random_size + 1]); let data_start = 1 + random_size + 2 + 16; let data_len = self.decode_data_size(&data[1+random_size..1+random_size+2], &random_bytes[..2]); let left_shall_be_read: i32 = (1 + random_size + 2 + 16 + data_len) as i32 - (input_len as i32); if left_shall_be_read > 4096 { return (0, -1) } else if left_shall_be_read > 0 { return (0, left_shall_be_read) } let nounce = &random_bytes[..12]; let aad = &self.key_bytes[ .. 8]; let mut tag = vec![0u8;16]; tag.copy_from_slice(&data[data_start -16 .. data_start]); let data = &mut data[data_start .. data_start + data_len]; match self.cipher.decrypt_in_place_detached(nounce.into(), aad, data, tag[..].into()) { Ok(_) => (data_len, (data_start + data_len) as i32), Err(_) => (0, -1) } } }
use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; #[derive(Serialize, Deserialize, Debug)] pub struct Stat { tutorial_version: String, current_lesson: String, finished_lessons: Vec<String>, total_lessons: u32, hints_used: HashMap<String, u32>, } impl Stat { pub fn get_tutorial_version(&self) -> String { self.tutorial_version.clone() } pub fn get_current_lesson(&self) -> String { self.current_lesson.clone() } pub fn get_hints_used(&self, lesson: String) -> Result<u32, String> { //TODO check if the lesson is a valid string and return error if invalid if self.hints_used.contains_key(&lesson) { Ok(*self.hints_used.get(&lesson).unwrap()) } else { Ok(0) } } pub fn set_current_lesson(&mut self, lesson: String) { self.current_lesson = lesson; } } pub fn new(tutorial_version: String, current_lesson: String, total_lessons: u32) -> Stat { Stat { tutorial_version, current_lesson, finished_lessons: Vec::<String>::new(), total_lessons, hints_used: HashMap::<String, u32>::new(), } } pub fn read_tutorstat() -> Option<Stat> { if let Ok(mut stat_file) = File::open("tutorstat.toml") { let mut contents = String::new(); stat_file .read_to_string(&mut contents) .expect("Error reading tutorstat.toml file"); Some(toml::from_str::<Stat>(contents.as_str()).expect("Error parsing tutorstat.toml file")) } else { println!("tutorstat.toml file not found"); None } } pub fn write_tutorstat(stat: Stat) { let mut stat_file = OpenOptions::new() .create(true) .write(true) .truncate(true) .open("tutorstat.toml") .expect("Cannot open tutorstat.toml for writing"); stat_file.write_all(toml::to_string_pretty(&stat).unwrap().as_bytes()); }
use crate::{ topic, BundleFor, BundleReceiver, GossipMessage, GossipMessageHandler, GossipValidator, LOG_TARGET, }; use futures::{future, FutureExt, StreamExt}; use parity_scale_codec::{Decode, Encode}; use parking_lot::Mutex; use sc_network_gossip::GossipEngine; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; /// A worker plays the executor gossip protocol. pub struct GossipWorker<CBlock, Block, Executor> where CBlock: BlockT, Block: BlockT, Executor: GossipMessageHandler<CBlock, Block>, { gossip_validator: Arc<GossipValidator<CBlock, Block, Executor>>, gossip_engine: Arc<Mutex<GossipEngine<Block>>>, bundle_receiver: BundleReceiver<Block, CBlock>, } impl<CBlock, Block, Executor> GossipWorker<CBlock, Block, Executor> where CBlock: BlockT, Block: BlockT, Executor: GossipMessageHandler<CBlock, Block>, { pub(super) fn new( gossip_validator: Arc<GossipValidator<CBlock, Block, Executor>>, gossip_engine: Arc<Mutex<GossipEngine<Block>>>, bundle_receiver: BundleReceiver<Block, CBlock>, ) -> Self { Self { gossip_validator, gossip_engine, bundle_receiver, } } fn gossip_bundle(&self, bundle: BundleFor<Block, CBlock>) { let outgoing_message: GossipMessage<CBlock, Block> = bundle.into(); let encoded_message = outgoing_message.encode(); self.gossip_validator.note_rebroadcasted(&encoded_message); self.gossip_engine .lock() .gossip_message(topic::<Block>(), encoded_message, false); } pub(super) async fn run(mut self) { let mut incoming = Box::pin( self.gossip_engine .lock() .messages_for(topic::<Block>()) .filter_map(|notification| async move { GossipMessage::<CBlock, Block>::decode(&mut &notification.message[..]).ok() }), ); loop { let engine = self.gossip_engine.clone(); let gossip_engine = future::poll_fn(|cx| engine.lock().poll_unpin(cx)); futures::select! { gossip_message = incoming.next().fuse() => { if let Some(message) = gossip_message { tracing::debug!(target: LOG_TARGET, ?message, "Rebroadcasting an executor gossip message"); match message { GossipMessage::Bundle(bundle) => self.gossip_bundle(bundle), } } else { return } } bundle = self.bundle_receiver.next().fuse() => { if let Some(bundle) = bundle { self.gossip_bundle(bundle); } } _ = gossip_engine.fuse() => { tracing::error!(target: LOG_TARGET, "Gossip engine has terminated."); return; } } } } }
#[macro_use] extern crate log; extern crate env_logger; extern crate lapin_futures as lapin; extern crate futures; extern crate tokio; extern crate uuid; use futures::future::Future; use futures::Stream; use tokio::executor::current_thread::CurrentThread; use tokio::net::TcpStream; use tokio::io::{ AsyncRead, AsyncWrite }; use uuid::Uuid; use lapin::client::ConnectionOptions; use lapin::channel::{ Channel, BasicConsumeOptions, BasicPublishOptions,BasicProperties, QueueDeclareOptions }; use lapin::types::FieldTable; fn main () { env_logger::init(); let addr = "127.0.0.3:5672".parse().unwrap(); let mut current_thread = CurrentThread::new(); let task = TcpStream::connect(&addr).and_then(|stream| { lapin::client::Client::connect(stream, &ConnectionOptions::default()) }).and_then(|(client, _heartbeat_future_fn)| { client.create_channel() }).and_then(|channel| { let name = format!("{}", Uuid::new_v4()); Handler::queue_declare(channel, name) }).map(|_| ()).map_err(|_| ()); current_thread.spawn(task); current_thread.run().unwrap(); } struct Handler; impl Handler { pub fn queue_declare<T>(channel: Channel<T>, name: String) -> Box<Future<Item = (), Error = std::io::Error>> where T: AsyncRead + AsyncWrite + Sync + Send + 'static { let declare = channel.queue_declare(&name, &QueueDeclareOptions::default(), &FieldTable::new()).and_then(move |_| { let correlation = Uuid::new_v4(); let correlation = format!("{}", correlation); let text = b"Hello from client"; Handler::basic_consume(channel, name, text, correlation) }); Box::new(declare) } pub fn basic_consume<T>(channel: Channel<T>, name: String, text: &'static [u8], correlation: String) -> Box<Future<Item = (), Error = std::io::Error>> where T: AsyncRead + AsyncWrite + Sync + Send + 'static { let consume = channel.basic_consume(&name, &name, &BasicConsumeOptions::default(), &FieldTable::new()) .and_then(move |stream| { info!("[.] Asking a request and waiting a response..."); let properties = BasicProperties::default() .with_correlation_id(correlation.clone()) .with_reply_to(name); channel.basic_publish("", "sif", text, &BasicPublishOptions::default(), properties); stream.for_each(move |message| { if message.properties.correlation_id.clone().unwrap() == correlation.clone() { info!("[x] Got a response!"); debug!("Message: {:?}", message); debug!("Message's content: {:?}", std::str::from_utf8(&message.data).unwrap()); std::process::exit(0); } Ok(()) }) }); Box::new(consume) } }
pub use self::metrics::{ levenshtein_distance, word_error_rate, word_accuracy }; mod metrics { use itertools::Itertools; use len_trait::len::Len; use std::ops::Index; use std::cmp::min; use crate::graphemes_struct::Graphemes; /// Calculates the levenshtein distance between two words /// /// # Arguments /// * `graphemes1` - Graphemes to compare with `graphemes2` /// * `graphemes2` - Graphemes to compare with `graphemes1` /// * `sub_cost` - Cost of substituting a character with another /// /// # Example /// ``` /// use nlp::metrics::levenshtein_distance; /// use nlp::graphemes_struct::Graphemes; /// assert_eq!(levenshtein_distance(&Graphemes::from("book"), &Graphemes::from("back"), 1), 2); /// assert_eq!(levenshtein_distance(&Graphemes::from("back"), &Graphemes::from("book"), 1), 2); /// assert_eq!(levenshtein_distance(&Graphemes::from("kitten"), &Graphemes::from("sitting"), 1), 3); /// ``` pub fn levenshtein_distance<'a, T, U>(graphemes1 : &T, graphemes2: &T, sub_cost : usize) -> usize where T : Len + Index<usize, Output = U>, U: PartialEq + 'a { levenshtein_distance_recurrence_matrix(graphemes1, graphemes2, sub_cost)[graphemes1.len()][graphemes2.len()] } fn levenshtein_distance_recurrence_matrix<'a, T, U>(graphemes1 : &T, graphemes2 : &T, sub_cost : usize) -> Vec<Vec<usize>> where T : Len + Index<usize, Output = U>, U : PartialEq + 'a { let num_rows = graphemes1.len() + 1; let num_cols = graphemes2.len() + 1; let mut recurrence_matrix : Vec<Vec<usize>> = vec![vec![0; num_cols]; num_rows]; // graphemes1 → row // graphemes2 → column for row in 1..num_rows { recurrence_matrix[row][0] = row; } for col in 1..num_cols { recurrence_matrix[0][col] = col; } for (row, col) in (1..num_rows).cartesian_product(1..num_cols) { recurrence_matrix[row][col] = min(min( recurrence_matrix[row-1][col]+1, recurrence_matrix[row][col-1]+1 ), recurrence_matrix[row-1][col-1] + if graphemes1[row-1] == graphemes2[col-1] {0} else {sub_cost}) } recurrence_matrix } /// Calculates the word error rate (word insertions + deletions + substitutions) / (length of the correct sentence) /// /// # Arguments /// * `actual_sentence` - actual sentence /// * `predict_sentence` - predicted sentence /// /// # Example /// ``` /// use nlp::metrics::word_error_rate; /// use nlp::graphemes_struct::Graphemes; /// use nlp::max_match; /// use std::collections::HashSet; /// let mut dictionary : HashSet<Graphemes> = HashSet::new(); /// dictionary.insert(Graphemes::from("we")); /// dictionary.insert(Graphemes::from("canon")); /// dictionary.insert(Graphemes::from("see")); /// dictionary.insert(Graphemes::from("ash")); /// dictionary.insert(Graphemes::from("ort")); /// dictionary.insert(Graphemes::from("distance")); /// dictionary.insert(Graphemes::from("ahead")); /// let predicted_sentence = max_match(&Graphemes::from("wecanonlyseeashortdistanceahead"), &dictionary); /// let actual_sentence = Graphemes::from("we can only see a short distance ahead"); /// assert_eq!(word_error_rate(&actual_sentence, &predicted_sentence),0.625); /// ``` pub fn word_error_rate(actual_sentence : &Graphemes, predict_sentence : &Graphemes) -> f64 { let actual_split_sentence = actual_sentence.split(" "); let lev_distance = levenshtein_distance(&actual_split_sentence, &predict_sentence.split(" "), 1); lev_distance as f64 / actual_split_sentence.len() as f64 } /// Calculates the word accuracy 1 - (word insertions + deletions + substitutions) / (length of the correct sentence) /// /// # Arguments /// * `actual_sentence` - actual sentence /// * `predict_sentence` - predicted sentence /// /// # Example /// ``` /// use nlp::metrics::word_accuracy; /// use nlp::graphemes_struct::Graphemes; /// use nlp::max_match; /// use std::collections::HashSet; /// let mut dictionary : HashSet<Graphemes> = HashSet::new(); /// dictionary.insert(Graphemes::from("we")); /// dictionary.insert(Graphemes::from("canon")); /// dictionary.insert(Graphemes::from("see")); /// dictionary.insert(Graphemes::from("ash")); /// dictionary.insert(Graphemes::from("ort")); /// dictionary.insert(Graphemes::from("distance")); /// dictionary.insert(Graphemes::from("ahead")); /// let predicted_sentence = max_match(&Graphemes::from("wecanonlyseeashortdistanceahead"), &dictionary); /// let actual_sentence = Graphemes::from("we can only see a short distance ahead"); /// assert_eq!(word_accuracy(&actual_sentence, &predicted_sentence),0.375); /// ``` pub fn word_accuracy(actual_sentence : &Graphemes, predict_sentence : &Graphemes) -> f64 { 1.0 - word_error_rate(actual_sentence, predict_sentence) } } #[cfg(tests)] mod test_cases { use crate::metrics::{levenshtein_distance, word_error_rate}; use crate::graphemes_struct::Graphemes; use crate::max_match; use std::collections::HashSet; #[test] fn edit_distance_basic_test() { // empty string assert_eq!(levenshtein_distance(&Graphemes::from(""), &Graphemes::from(""), 1), 0); // empty string symmetry assert_eq!(levenshtein_distance(&Graphemes::from(""), &Graphemes::from("a"), 1), 1); assert_eq!(levenshtein_distance(&Graphemes::from("a"), &Graphemes::from(""), 1), 1); assert_eq!(levenshtein_distance(&Graphemes::from("a"), &Graphemes::from("a"), 1), 0); assert_eq!(levenshtein_distance(&Graphemes::from("a"), &Graphemes::from("b"), 1), 1); assert_eq!(levenshtein_distance(&Graphemes::from("a"), &Graphemes::from("b"), 2), 2); assert_eq!(levenshtein_distance(&Graphemes::from("ab"), &Graphemes::from("a"), 1), 1); assert_eq!(levenshtein_distance(&Graphemes::from("a"), &Graphemes::from("ab"), 1), 1); } #[test] fn edit_distance_vec_of_graphemes_test() { assert_eq!(levenshtein_distance(&vec![Graphemes::from("")] , &vec![Graphemes::from(""),], 1), 0); assert_eq!(levenshtein_distance(&vec![Graphemes::from("hello"), Graphemes::from("world")] , &vec![Graphemes::from("bye"), Graphemes::from("bye")], 1), 2); assert_eq!(levenshtein_distance(&vec![Graphemes::from("hello")] , &vec![Graphemes::from("bye"), Graphemes::from("bye")], 2), 3); assert_eq!(levenshtein_distance(&vec![Graphemes::from("hello"), Graphemes::from("world")] , &vec![Graphemes::from("bye")], 2), 3); } #[test] fn edit_distance_example_test() { assert_eq!(levenshtein_distance(&Graphemes::from("book"), &Graphemes::from("back"), 1), 2); assert_eq!(levenshtein_distance(&Graphemes::from("back"), &Graphemes::from("book"), 1), 2); assert_eq!(levenshtein_distance(&Graphemes::from("kitten"), &Graphemes::from("sitting"), 1), 3); assert_eq!(levenshtein_distance(&Graphemes::from("sitting"), &Graphemes::from("kitten"), 1), 3); assert_eq!(levenshtein_distance(&Graphemes::from("longstring"), &Graphemes::from("short"), 1), 9); assert_eq!(levenshtein_distance(&Graphemes::from("short"), &Graphemes::from("longstring"), 1), 9); assert_eq!(levenshtein_distance(&Graphemes::from("superman"), &Graphemes::from("batman"), 1), 5); assert_eq!(levenshtein_distance(&Graphemes::from("batman"), &Graphemes::from("superman"), 1), 5); assert_eq!(levenshtein_distance(&Graphemes::from(""), &Graphemes::from("aaaaaaaaaaaaaaaaa"), 1), 17); assert_eq!(levenshtein_distance(&Graphemes::from("aaaaaaaaaaaaaaaaa"), &Graphemes::from(""), 1), 17); } #[test] fn edit_distance_chinese_test() { assert_eq!(levenshtein_distance(&Graphemes::from("己所不欲勿施于人"), &Graphemes::from("back"), 1), 8); assert_eq!(levenshtein_distance(&Graphemes::from("back"), &Graphemes::from("己所不欲勿施于人"), 1), 8); assert_eq!(levenshtein_distance(&Graphemes::from("己所不欲勿施于人"), &Graphemes::from("不患人之不己知患不知人也"), 1), 10); assert_eq!(levenshtein_distance(&Graphemes::from("不患人之不己知患不知人也"), &Graphemes::from("己所不欲勿施于人"), 1), 10); } #[test] fn word_error_rate_test() { let mut dictionary : HashSet<Graphemes> = HashSet::new(); dictionary.insert(Graphemes::from("we")); dictionary.insert(Graphemes::from("canon")); dictionary.insert(Graphemes::from("see")); dictionary.insert(Graphemes::from("ash")); dictionary.insert(Graphemes::from("ort")); dictionary.insert(Graphemes::from("distance")); dictionary.insert(Graphemes::from("ahead")); let predicted_sentence = max_match(&Graphemes::from("wecanonlyseeashortdistanceahead"), &dictionary); let actual_sentence = Graphemes::from("we can only see a short distance ahead"); assert_eq!(word_error_rate(&actual_sentence, &predicted_sentence),0.625); assert_eq!(word_error_rate(&actual_sentence, &actual_sentence),0.0) } }
use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::ToTokens; use crate::attr_parser::ProvidesAttr; use crate::component::type_to_inject::TypeToInject; use crate::component::{generate_dependencies_create_code, generate_inject_dependencies_tuple}; use std::ops::Deref; use syn::spanned::Spanned; use syn::{Error, GenericParam, ItemFn, ItemImpl, ItemStruct, Path, ReturnType, Type}; pub(crate) fn generate_component_provider_impl_struct(component: ItemStruct) -> TokenStream { let comp_name = component.ident; let comp_generics = component.generics.clone(); let create_component_code = quote::quote! { #comp_name::__inexor_rgf_core_di_create(self) }; let inject_deferred_code = quote::quote! { #comp_name::__inexor_rgf_core_di_inject_deferred(self, &component); }; generate_component_provider_impl( quote::quote! { #comp_name #comp_generics }, component.generics.params.iter().collect(), vec![], create_component_code, inject_deferred_code, ) } pub(crate) fn generate_component_provider_impl_fn(provides: ProvidesAttr, factory: ItemFn, force_type: TokenStream2) -> Result<TokenStream, Error> { let comp_name = if force_type.is_empty() { let ret_value = if let ReturnType::Type(_, type_) = &factory.sig.output { if let Type::Path(type_path) = type_.deref() { type_path.path.segments.to_token_stream() } else { return Err(Error::new(factory.span(), "Unsupported return type for factory function")); } } else { return Err(Error::new(factory.span(), "Return type must be specified for factory function")); }; ret_value } else { force_type.clone() }; let fn_name = factory.sig.ident.to_token_stream(); let fn_name_prefix = if force_type.is_empty() { force_type } else { quote::quote! { #force_type :: } }; let dependencies_code = generate_dependencies_create_code( factory .sig .inputs .iter() .map(|arg| TypeToInject::from_fn_arg(arg.clone())) .collect::<Result<Vec<_>, _>>()?, ); let factory_code = generate_inject_dependencies_tuple(factory.sig.inputs.len()); let create_component_code = quote::quote! { { let container = &mut *self; #dependencies_code #fn_name_prefix #fn_name #factory_code } }; let inject_deferred_code = quote::quote! {}; Ok(generate_component_provider_impl( comp_name, factory .sig .generics .params .iter() .filter(|p| if let GenericParam::Lifetime(_) = p { true } else { false }) .collect(), provides.profiles, create_component_code, inject_deferred_code, )) } pub fn generate_component_provider_impl( comp_name: TokenStream2, comp_generics: Vec<&GenericParam>, profiles: Vec<Path>, create_component_code: TokenStream2, inject_deferred_code: TokenStream2, ) -> TokenStream { let (profiles, provider_generics) = if profiles.is_empty() { let generic_profile = quote::quote! { PROFILE }; let provider_generics = if comp_generics.is_empty() { quote::quote! { <PROFILE> } } else { quote::quote! { <#(#comp_generics),*, PROFILE> } }; (vec![generic_profile], provider_generics) } else { let profiles = profiles.iter().map(|p| p.to_token_stream()).collect(); (profiles, quote::quote! { <#(#comp_generics),*> }) }; let result = quote::quote! {#( impl #provider_generics inexor_rgf_core_di::Provider<#comp_name> for inexor_rgf_core_di::Container<#profiles> { type Impl = #comp_name; fn get(&mut self) -> inexor_rgf_core_di::Wrc<Self::Impl> { let type_id = std::any::TypeId::of::<#comp_name>(); if !self.components.contains_key(&type_id) { let component = inexor_rgf_core_di::Wrc::new(#create_component_code); self.components.insert(type_id, component.clone()); #inject_deferred_code } let any = self.components.get(&type_id) .unwrap(); return any.clone() .downcast::<#comp_name>() .unwrap(); } fn create(&mut self) -> Self::Impl { let component = #create_component_code; #inject_deferred_code return component; } } )*}; return TokenStream::from(result); } pub(crate) fn generate_interface_provider_impl(provides: ProvidesAttr, impl_block: ItemImpl) -> TokenStream { let interface = match impl_block.trait_ { Some((_, interface, _)) => interface, None => return TokenStream::from(Error::new(impl_block.span(), "#[provides] can be used only on impl blocks for traits").to_compile_error()), }; let comp_name = if let Type::Path(comp_path) = *impl_block.self_ty { comp_path.path.segments.first().unwrap().ident.clone() } else { return TokenStream::from(Error::new(impl_block.self_ty.span(), "Failed to create provider").to_compile_error()); }; let provider_body = quote::quote! {{ type Impl = #comp_name; fn get(&mut self) -> inexor_rgf_core_di::Wrc<Self::Impl> { inexor_rgf_core_di::Provider::<#comp_name>::get(self) } fn create(&mut self) -> Self::Impl { inexor_rgf_core_di::Provider::<#comp_name>::create(self) } }}; let profiles = provides.profiles; let result = if profiles.is_empty() { quote::quote! { impl<P> inexor_rgf_core_di::Provider<dyn #interface> for inexor_rgf_core_di::Container<P> #provider_body } } else { quote::quote! { #(impl inexor_rgf_core_di::Provider<dyn #interface> for inexor_rgf_core_di::Container<#profiles> #provider_body)* } }; return TokenStream::from(result); }
use chrono::prelude::*; use chrono_tz::{Europe::London, Tz}; macro_rules! term { // "to" the day on which term ends (usually a Friday). ($name:ident, $sy:literal-$sm:literal-$sd:literal to $ey:literal-$em:literal-$ed:literal) => {{ let start = London.ymd($sy, $sm, $sd).and_hms(0, 0, 0); let end = London.ymd($ey, $em, $ed).succ().and_hms(0, 0, 0); Term { name: $name, start, end, } }}; } macro_rules! terms { ($($name:ident: $sy:literal-$sm:literal-$sd:literal to $ey:literal-$em:literal-$ed:literal),+$(,)?) => { [ $( term!($name, $sy-$sm-$sd to $ey-$em-$ed) ),+ ] }; } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum TermName { Autumn, Spring, Summer, } use TermName::*; impl TermName { fn shortname(&self) -> &'static str { match self { Autumn => "Aut", Spring => "Spr", Summer => "Sum", } } fn longname(&self) -> &'static str { match self { Autumn => "Autumn", Spring => "Spring", Summer => "Summer", } } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] struct Term { name: TermName, /// The first instant of the term. start: DateTime<Tz>, /// The instant after the term ends. end: DateTime<Tz>, } impl Term { fn name(&self) -> TermName { self.name } fn start(&self) -> DateTime<Tz> { self.start } fn end(&self) -> DateTime<Tz> { self.end } /// Returns `s`, where `s <= start && s.weekday() == Mon`. fn loose_start(&self) -> DateTime<Tz> { let mut s = self.start.date(); while s.weekday() != Weekday::Mon { s = s.pred(); } s.and_hms(0, 0, 0) } /// Returns `e`, where `e >= end && e.weekday() == Mon`. fn loose_end(&self) -> DateTime<Tz> { let mut e = self.end.date(); while e.weekday() != Weekday::Mon { e = e.succ(); } e.and_hms(0, 0, 0) } } fn get_term(terms: &[Term], now: DateTime<Tz>) -> Option<&Term> { terms .iter() .filter(|&term| term.loose_start() <= now && now <= term.loose_end()) .last() } fn get_strict_term(terms: &[Term], now: DateTime<Tz>) -> Option<&Term> { terms .iter() .filter(|&term| term.start() <= now && now <= term.end()) .last() } fn main() { // <https://www.york.ac.uk/about/term-dates/> let mut terms = terms!( // 2018-19 Autumn: 2018-09-24 to 2018-11-30, Spring: 2019-01-07 to 2019-03-15, Summer: 2019-04-15 to 2019-06-21, // 2019-20 Autumn: 2019-09-30 to 2019-12-06, Spring: 2020-01-06 to 2020-03-13, Summer: 2020-04-14 to 2020-06-19, // 2020-21 Autumn: 2020-09-28 to 2020-12-03, Spring: 2021-01-11 to 2021-03-19, Summer: 2021-04-19 to 2021-06-25, // 2021-22 Autumn: 2021-09-27 to 2021-12-03, Spring: 2022-01-10 to 2022-03-18, Summer: 2022-04-19 to 2022-06-24, // 2022-23 Autumn: 2022-09-26 to 2022-12-02, Spring: 2023-01-09 to 2023-03-17, Summer: 2023-04-17 to 2023-06-23, // 2023-24 Autumn: 2023-09-25 to 2023-12-01, Spring: 2024-01-08 to 2024-03-15, Summer: 2024-04-15 to 2024-06-21, // 2024-25 Autumn: 2024-09-23 to 2024-11-29, Spring: 2025-01-06 to 2024-03-14, Summer: 2025-04-22 to 2025-06-27, // 2025-26 Autumn: 2025-09-29 to 2025-12-05, Spring: 2026-01-12 to 2026-03-20, Summer: 2026-04-20 to 2026-06-26, // 2026-27 Autumn: 2026-09-28 to 2026-12-04, Spring: 2027-01-11 to 2027-03-19, Summer: 2027-04-19 to 2027-06-25, // 2027-28 Autumn: 2027-09-27 to 2027-12-03, Spring: 2028-01-10 to 2028-03-17, Summer: 2028-04-24 to 2028-06-30, ); terms.sort_unstable_by_key(|term| term.start()); let terms = terms; let now = London.from_utc_datetime(&Utc::now().naive_utc()); if let Some(term) = get_term(&terms, now) { let termname = term.name().shortname(); // FIXME: this is broken when going between years (e.g. before the first term of the year // starts) -- fix when euclidean_division is stable // (<https://github.com/rust-lang/rust/issues/49048>) // OTOH, it shouldn't actually matter -- there's no term that runs between two years. let weeknum = now.iso_week().week() as i32 - term.start().iso_week().week() as i32 + 1; let day = now.format("%a"); if let Some(strict_term) = get_strict_term(&terms, now) { assert_eq!(strict_term, term); // We're in real term. println!("{}/{}/{}", termname, weeknum, day); } else { // We're not in real term (i.e. another part of this week is real term). println!("({}/{}/{})", termname, weeknum, day); } } else { // Giving a term date would be nonsensical. println!("n/a"); } }
#![feature(libc)] #![feature(rustc_private)] extern crate libc; use libc::{c_char, int32_t, c_int}; use std::ffi::CString; /* * For Initialization */ extern {fn register_all_sql_mappers();} extern {fn mcsql_set_db_file(dbname: *const c_char);} /* * Database Handle */ extern {fn mcsql_arc_get_all() -> *mut c_char;} extern {fn mcsql_arc_get_params(file_no: int32_t, group: *const c_char) -> *mut c_char;} extern {fn mcsql_bookprogram_get_all() -> *mut c_char;} extern {fn mcsql_dynamics_get_all() -> *mut c_char;} extern {fn mcsql_dynamics_get_by_id(id: *const c_char) -> *mut c_char;} extern {fn mcsql_enum_get_all() -> *mut c_char;} extern {fn mcsql_extaxis_get_all() -> *mut c_char;} extern {fn mcsql_interference_get_all() -> *mut c_char;} extern {fn mcsql_ios_get_all(group: *const c_char, lang: *const c_char, auth: int32_t, tech: int32_t) -> *mut c_char;} extern {fn mcsql_metadata_get_all(lang: *const c_char) -> *mut c_char;} extern {fn mcsql_params_get_params() -> *mut c_char;} extern {fn mcsql_params_get_valid_param_by_id(md_id: *const c_char) -> *mut c_char;} extern {fn mcsql_params_get_valid_param_by_group(group: *const c_char) -> *mut c_char;} extern {fn mcsql_operation_record_get_all(created_time: int32_t, start: int32_t, page_size: int32_t) -> *mut c_char;} extern {fn mcsql_ref_get_all() -> *mut c_char;} extern {fn mcsql_toolframe_get_all() -> *mut c_char;} extern {fn mcsql_toolframe_get_by_toolno(tool_no: int32_t) -> *mut c_char;} extern {fn mcsql_userframe_get_all() -> *mut c_char;} extern {fn mcsql_userframe_get_by_userno(user_no: int32_t) -> *mut c_char;} extern {fn mcsql_zeropoint_get_all() -> *mut c_char;} /* * Database Backup */ extern {fn mcsql_manager_backup_db(db_dir: *const c_char) -> c_int;} extern {fn mcsql_manager_restore_db(db_dir: *const c_char, db_bak_name: *const c_char, db_dir: c_char) -> c_int;} extern {fn mcsql_manager_upgrade_db(db_dir: *const c_char, upgrade_pkg: *const c_char) -> c_int;} // Turn C result into String, responded to caller fn result_into_string_response(c_result: *mut c_char) -> String { if c_result.is_null() { return String::from("null"); } let c_string = unsafe { CString::from_raw(c_result) }; match c_string.into_string() { Ok(s) => {return s;}, Err(_) => { return String::from("fails to get result"); }, } } pub fn arc_get_all() -> String { let c_result = unsafe { mcsql_arc_get_all() }; result_into_string_response(c_result) } pub fn arc_get_params(file_no: i32, group: String) -> String { let group = match CString::new(group) { Ok(group) => group, Err(_) => { return String::from(""); } }; let c_result = unsafe { mcsql_arc_get_params(file_no, group.as_ptr()) }; result_into_string_response(c_result) } pub fn bookprogram_get_all() -> String { let c_result = unsafe { mcsql_bookprogram_get_all() }; result_into_string_response(c_result) } pub fn dynamics_get_all() -> String { let c_result = unsafe { mcsql_dynamics_get_all() }; result_into_string_response(c_result) } pub fn dynamics_get_by_id(id: String) -> String { let id = match CString::new(id) { Ok(id) => id, Err(_) => { return String::from(""); } }; let c_result = unsafe { mcsql_dynamics_get_by_id(id.as_ptr()) }; result_into_string_response(c_result) } pub fn enum_get_all() -> String { let c_result = unsafe { mcsql_enum_get_all() }; result_into_string_response(c_result) } pub fn extaxis_get_all() -> String { let c_result = unsafe { mcsql_extaxis_get_all() }; result_into_string_response(c_result) } pub fn interference_get_all() -> String { let c_result = unsafe { mcsql_interference_get_all() }; result_into_string_response(c_result) } pub fn ios_get_all(group: String, lang: String, auth: i32, tech: i32) -> String { let group = match CString::new(group) { Ok(group) => group, Err(_) => { return String::from(""); } }; let lang = match CString::new(lang) { Ok(lang) => lang, Err(_) => { return String::from(""); } }; let c_result = unsafe { mcsql_ios_get_all(group.as_ptr(), lang.as_ptr(), auth, tech) }; result_into_string_response(c_result) } pub fn metadata_get_all(lang: String) -> String { let lang = match CString::new(lang) { Ok(lang) => lang, Err(_) => { return String::from(""); } }; let c_result = unsafe { mcsql_metadata_get_all(lang.as_ptr()) }; result_into_string_response(c_result) } pub fn params_get_params() -> String { let c_result = unsafe { mcsql_params_get_params() }; result_into_string_response(c_result) } pub fn params_get_valid_param_by_id(md_id: String) -> String { let md_id = match CString::new(md_id) { Ok(md_id) => md_id, Err(_) => { return String::from(""); } }; let c_result = unsafe { mcsql_params_get_valid_param_by_id(md_id.as_ptr()) }; result_into_string_response(c_result) } pub fn params_get_valid_param_by_group(group: String) -> String { let group = match CString::new(group) { Ok(group) => group, Err(_) => { return String::from(""); } }; let c_result = unsafe { mcsql_params_get_valid_param_by_group(group.as_ptr()) }; result_into_string_response(c_result) } pub fn operation_record_get_all(created_time: i32, start: i32, page_size: i32) -> String { let c_result = unsafe { mcsql_operation_record_get_all(created_time, start, page_size) }; result_into_string_response(c_result) } pub fn ref_get_all() -> String { let c_result = unsafe { mcsql_ref_get_all() }; result_into_string_response(c_result) } pub fn toolframe_get_all() -> String { let c_result = unsafe { mcsql_toolframe_get_all() }; result_into_string_response(c_result) } pub fn toolframe_get_by_toolno(tool_no: i32) -> String { let c_result = unsafe { mcsql_toolframe_get_by_toolno(tool_no) }; result_into_string_response(c_result) } pub fn userframe_get_all() -> String { let c_result = unsafe { mcsql_userframe_get_all() }; result_into_string_response(c_result) } pub fn userframe_get_by_userno(user_no: i32) -> String { let c_result = unsafe { mcsql_userframe_get_by_userno(user_no) }; result_into_string_response(c_result) } pub fn zeropoint_get_all() -> String { let c_result = unsafe { mcsql_zeropoint_get_all() }; result_into_string_response(c_result) } pub fn manager_backup_db(db_dir: String) -> i32 { let db_dir = match CString::new(db_dir) { Ok(db_dir) => db_dir, Err(_) => { return -1; } }; unsafe { mcsql_manager_backup_db(db_dir.as_ptr()) } } pub fn manager_restore_db(db_dir: String, db_bak_name: String, force: u8) -> i32 { let db_dir = match CString::new(db_dir) { Ok(db_dir) => db_dir, Err(_) => { return -1; } }; let db_bak_name = match CString::new(db_bak_name) { Ok(db_bak_name) => db_bak_name, Err(_) => { return -1; } }; unsafe { mcsql_manager_restore_db(db_dir.as_ptr(), db_bak_name.as_ptr(), force) } } pub fn manager_upgrade_db(db_dir: String, upgrade_pkg: String) -> i32 { let db_dir = match CString::new(db_dir) { Ok(db_dir) => db_dir, Err(_) => { return -1; } }; let upgrade_pkg = match CString::new(upgrade_pkg) { Ok(upgrade_pkg) => upgrade_pkg, Err(_) => { return -1; } }; unsafe { mcsql_manager_upgrade_db(db_dir.as_ptr(), upgrade_pkg.as_ptr()) } } pub fn init() { let conn = CString::new("/rbctrl/db/elibotDB.db").unwrap(); unsafe { register_all_sql_mappers(); mcsql_set_db_file(conn.as_ptr()); } }
use std::borrow::Cow; use std::convert::Into; use std::str::Chars; use unicode_normalization::UnicodeNormalization; const CHARS_TO_DELIMIT: &'static [char] = &[' ', ',', '.', '/', '\\', '-', '_', '=']; const CHARS_TO_REMOVE: &'static [char] = &['\'']; const DEFAULT_DELIMITER: char = '-'; pub struct Slugger<'a> { delimiter: char, chars_to_delimit: &'a [char], chars_to_remove: &'a [char], } #[derive(Debug,PartialEq)] enum NormalizedSpecialChar { Char(char), Delimiter, ManyChars(Vec<char>), } impl<'a> Slugger<'a> { pub fn default() -> Slugger<'a> { Slugger::new(DEFAULT_DELIMITER, CHARS_TO_DELIMIT, CHARS_TO_REMOVE) } pub fn new(delimiter: char, delimit_chars: &'a [char], remove_chars: &'a [char]) -> Slugger<'a> { Slugger { delimiter: delimiter, chars_to_delimit: delimit_chars, chars_to_remove: remove_chars, } } pub fn create<T: Into<Cow<'a, str>>>(s: T) -> String { Slugger::default().create_slug(s) } pub fn create_slug<T: Into<Cow<'a, str>>>(&self, s: T) -> String { let s = s.into().into_owned(); let chars = s.chars(); let (slug_chars, _) = self.to_slug(chars); slug_chars.into_iter().collect() } fn to_slug(&self, chars: Chars) -> (Vec<char>, bool) { chars.fold((Vec::new(), false), |(mut acc, should_delimit), c| { let mut needs_delimiter = false; match c { 'a'...'z' | 'A'...'Z' | '0'...'9' => { let c = alphanum_c_to_lower(c); self.maybe_add_delimiter(&mut acc, should_delimit); acc.push(c); } _ => { if self.should_remove(&c) { return (acc, should_delimit); } else if self.should_delimit(&c) { needs_delimiter = true; } else { match normalize_special_c(c) { NormalizedSpecialChar::Char(c) => { self.maybe_add_delimiter(&mut acc, should_delimit); acc.push(c); } NormalizedSpecialChar::Delimiter => { needs_delimiter = true; } NormalizedSpecialChar::ManyChars(cs) => { self.maybe_add_delimiter(&mut acc, should_delimit); acc.extend(cs); } } } } } (acc, needs_delimiter) }) } fn should_delimit(&self, c: &char) -> bool { self.chars_to_delimit.contains(c) } fn should_remove(&self, c: &char) -> bool { self.chars_to_remove.contains(c) } fn maybe_add_delimiter(&self, acc: &mut Vec<char>, should_delimit: bool) { if should_delimit && acc.len() > 0 { acc.push(self.delimiter); } } } fn alphanum_c_to_lower(c: char) -> char { c.to_lowercase().next().unwrap() } fn get_c_or_delimiter(c: char) -> NormalizedSpecialChar { match c { 'a'...'z' | 'A'...'Z' | '0'...'9' => { let c = alphanum_c_to_lower(c); NormalizedSpecialChar::Char(c) } _ => NormalizedSpecialChar::Delimiter, } } fn normalize_special_c(c: char) -> NormalizedSpecialChar { let str = &c.to_string(); let decomposed_c = str.nfkd(); if decomposed_c.clone().count() > 1 { let cs = decomposed_c.fold(Vec::new(), |mut acc, c| { match get_c_or_delimiter(c) { NormalizedSpecialChar::Char(c) => { acc.push(c); } _ => {} } acc }); NormalizedSpecialChar::ManyChars(cs) } else { get_c_or_delimiter(c) } }
use core::fmt; use std::fmt::Formatter; use std::marker::PhantomData; use serde::de; use serde::de::Visitor; use crate::{AnyBin, AnyStr}; pub struct ReIntegrationStrVisitor<TReIntegrator> { _phantom: PhantomData<TReIntegrator>, } impl<TReIntegrator> ReIntegrationStrVisitor<TReIntegrator> { pub fn new() -> Self { Self { _phantom: PhantomData::default(), } } } pub trait StrReIntegrator { type TBin: AnyBin; fn re_integrate_str(str: &str) -> AnyStr<Self::TBin>; fn re_integrate_string(string: String) -> AnyStr<Self::TBin>; } impl<'de, TReIntegrator> Visitor<'de> for ReIntegrationStrVisitor<TReIntegrator> where TReIntegrator: StrReIntegrator, { type Value = AnyStr<TReIntegrator::TBin>; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { formatter.write_str("expecting a string") } #[inline] fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { Ok(TReIntegrator::re_integrate_str(v)) } #[inline] fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: de::Error, { Ok(TReIntegrator::re_integrate_string(v)) } }
const REPO_OWNER: &str = "GlebIrovich"; const REPO_NAME: &str = "rudo"; const EXE_NAME: &str = "rudo"; pub const CURRENT_APP_VERSION: &str = "0.2.3"; pub fn update() -> Result<String, Box<dyn ::std::error::Error>> { let status = self_update::backends::github::Update::configure() .repo_owner(REPO_OWNER) .repo_name(REPO_NAME) .bin_name(EXE_NAME) .show_download_progress(true) .current_version(CURRENT_APP_VERSION) .build()? .update()?; let version = status.version().to_string(); Ok(version) }
pub mod client_error; pub mod clientlog; pub mod race_event; pub mod logline_generator; use common::race_run::ZoneEntry; use common::race_run::LevelUp; use client::clientlog::ClientLogLine; use self::race_event::SimpleEvent; use chrono::Local; use chrono::DateTime; use self::client_error::{ClientResult, ClientError}; use std::io; pub type EventTime = (DateTime<Local>, SimpleEvent); pub fn get_race_iter<I: Iterator<Item = io::Result<String>>>( i: I, ) -> impl Iterator<Item = ClientResult<EventTime>> { i.map(|line_result| -> ClientResult<EventTime> { let line = line_result?; let cll: ClientLogLine = line.parse()?; let event: SimpleEvent = cll.message.parse()?; Ok((cll.date, event)) }).filter_map(|event_result| match event_result { Err(ClientError::EventParseError) => None, item @ _ => Some(item), }) } pub fn wait_for_start_of_run<T: Iterator<Item = ClientResult<EventTime>>>( i: &mut T, ) -> ClientResult<DateTime<Local>> { info!("waiting for start command!"); while let Some(item) = i.next() { match item? { (start, SimpleEvent::StartRun) => return Ok(start), _ => continue, } } Err("Ended before start!".to_owned().into()) } pub fn fill_vec_and_return_end_time<T: Iterator<Item = ClientResult<EventTime>>>( i: &mut T, v: &mut Vec<EventTime>, ) -> ClientResult<DateTime<Local>> { while let Some(item) = i.next() { let item = item?; if let (time, SimpleEvent::EndRun) = item { return Ok(time); } else { v.push(item); } } Err("Ended before race end!".to_owned().into()) } pub fn get_level_ups(start: DateTime<Local>, v: &[EventTime]) -> Vec<LevelUp> { v.iter() .filter_map(|event| match event { &(time, SimpleEvent::LevelUp(level)) => { Some(LevelUp::new( level, time.signed_duration_since(start).num_seconds() as u64, )) } _ => None, }) .collect() } pub fn get_zone_entries(start: DateTime<Local>, v: &[EventTime]) -> Vec<ZoneEntry> { v.iter() .filter_map(|event| match event { &(time, SimpleEvent::EnterZone(ref name)) => { Some(ZoneEntry::new( name.clone(), time.signed_duration_since(start).num_seconds() as u64, )) } _ => None, }) .collect() } #[cfg(test)] mod tests { const RUN_LINES: &[u8] = include_bytes!("../../test_runs/ok_run.txt"); use super::*; use super::logline_generator::{DefaultLogLineGenerator, LogLineGenerator}; #[test] fn test_wait_for_start_run() { let log_line_generator = DefaultLogLineGenerator::from_reader(RUN_LINES); let mut event_iter = get_race_iter(log_line_generator); if let Ok(_) = wait_for_start_of_run(&mut event_iter) { } else { assert!(false) } } }
mod builder; mod method; pub use self::builder::*; pub use self::method::{Instance, Method}; pub fn build<'a>() -> Builder<'a> { Builder::default() } #[cfg(test)] pub mod tests { use super::super::types::Object; use super::super::Context; use super::method::Instance; #[test] fn class_builder() { let ctx = Context::new().unwrap(); let mut b = super::build(); b.method("testMethodNoArg", |ctx: &Context, this: &mut Instance| { ctx.push_string("Hello, World!"); Ok(1) }) .method( "testMethodArg", (1, |ctx: &Context, this: &mut Instance| Ok(0)), ); ctx.push_class(b).unwrap(); ctx.construct(0).unwrap(); let out = ctx.getp::<Object>().unwrap(); let greeting = out.call::<_, _, String>("testMethodNoArg", ()).unwrap(); assert_eq!(greeting, "Hello, World!"); } }
use cgmath::{ElementWise, Vector2}; use std::f32; use std::cmp::Ordering; use std::cmp::Ordering::*; use math::IntAabb; const EPSILON: f32 = 1e-7; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum AabbRelation { Disjoint, Intersects, Contains, ContainedBy, } #[derive(Copy, Clone, Debug)] pub struct Aabb { pub min: Vector2<f32>, pub max: Vector2<f32>, } impl Aabb { pub fn empty() -> Self { Aabb { min: Vector2 { x: f32::MAX, y: f32::MAX, }, max: Vector2 { x: f32::MIN, y: f32::MIN, }, } } pub fn new(min: Vector2<f32>, max: Vector2<f32>) -> Self { Aabb { min, max } } pub fn relation_to(&self, other: &Aabb) -> AabbRelation { let cmps = self.gen_comparisons(other); if cmps.min_min_x != Greater && cmps.min_min_y != Greater && cmps.max_max_x != Less && cmps.max_max_y != Less { return AabbRelation::Contains; } if cmps.min_min_x != Less && cmps.min_min_y != Less && cmps.max_max_x != Greater && cmps.max_max_y != Greater { return AabbRelation::ContainedBy; } if cmps.min_max_x == Greater || cmps.min_max_y == Greater { return AabbRelation::Disjoint; } if cmps.max_min_x == Less || cmps.max_min_y == Less { return AabbRelation::Disjoint; } AabbRelation::Intersects } pub fn disjoint_from(&self, other: &Aabb) -> bool { self.relation_to(other) == AabbRelation::Disjoint } pub fn overlaps(&self, other: &Aabb) -> bool { self.relation_to(other) != AabbRelation::Disjoint } pub fn intersects(&self, other: &Aabb) -> bool { self.relation_to(other) == AabbRelation::Intersects } pub fn contains(&self, other: &Aabb) -> bool { self.relation_to(other) == AabbRelation::Contains } pub fn contained_by(&self, other: &Aabb) -> bool { self.relation_to(other) == AabbRelation::ContainedBy } pub fn contains_point(&self, point: Vector2<f32>) -> bool { point.x >= self.min.x && point.x <= self.max.x && point.y >= self.min.y && point.y <= self.max.y } pub fn contains_point_xy(&self, x: f32, y: f32) -> bool { self.contains_point(Vector2 { x, y }) } pub fn expand(&mut self, aabb: Aabb) -> &mut Self { self.expand_point(aabb.min).expand_point(aabb.max) } pub fn expand_point(&mut self, point: Vector2<f32>) -> &mut Self { self.min.x = self.min.x.min(point.x); self.min.y = self.min.y.min(point.y); self.max.x = self.max.x.max(point.x); self.max.y = self.max.y.max(point.y); self } pub fn scaled(self, scale: Vector2<f32>) -> Aabb { let mut new = Aabb::empty(); new.expand_point(self.min.mul_element_wise(scale)); new.expand_point(self.max.mul_element_wise(scale)); new } pub fn to_int(self) -> IntAabb { IntAabb { min_x: self.min.x.floor() as i32, min_y: self.min.y.floor() as i32, max_x: self.max.x.ceil() as i32, max_y: self.max.y.ceil() as i32, } } fn gen_comparisons(&self, other: &Aabb) -> AabbCmp { use self::AabbField::*; AabbCmp { min_min_x: self.compare_fields(other, MinX, MinX), min_max_x: self.compare_fields(other, MinX, MaxX), max_min_x: self.compare_fields(other, MaxX, MinX), max_max_x: self.compare_fields(other, MaxX, MaxX), min_min_y: self.compare_fields(other, MinY, MinY), min_max_y: self.compare_fields(other, MinY, MaxY), max_min_y: self.compare_fields(other, MaxY, MinY), max_max_y: self.compare_fields(other, MaxY, MaxY), } } fn compare_fields( &self, other: &Aabb, left_field: AabbField, right_field: AabbField, ) -> Ordering { let left = self.get_field(left_field); let right = other.get_field(right_field); if (left - right).abs() <= EPSILON { Equal } else if left < right { Less } else { Greater } } fn get_field(&self, field: AabbField) -> f32 { match field { AabbField::MinX => self.min.x, AabbField::MinY => self.min.y, AabbField::MaxX => self.max.x, AabbField::MaxY => self.max.y, } } } enum AabbField { MinX, MinY, MaxX, MaxY, } struct AabbCmp { min_min_x: Ordering, min_max_x: Ordering, max_min_x: Ordering, max_max_x: Ordering, min_min_y: Ordering, min_max_y: Ordering, max_min_y: Ordering, max_max_y: Ordering, }
use super::*; use crate::{Client, Error, HyperTransport}; use std::collections::HashMap; #[derive(Clone)] pub struct Writer(Arc<EavesdropRecorder>); impl Writer { pub fn write_as_fixture(&self) { self.0.write_as_fixture() } } pub async fn new_eavesdrop_device( uri: http::Uri, ) -> Result< ( DeviceInfo, Client<EavesdropTransport<HyperTransport>>, Writer, ), Error, > { let device = Client::new(HyperTransport::default(), uri.clone()); let device_info = DeviceInfo::retrieve(&device).await; let device_info = device_info?; let recorder = EavesdropRecorder::new(device_info.clone()); let recorder = Arc::new(recorder); let writer = Writer(recorder.clone()); Ok(( device_info, device.replace_transport(move |_| EavesdropTransport { recorder, transport: HyperTransport::default(), }), writer, )) } pub struct EavesdropRecorder { recording: Mutex<Option<Recording>>, } impl EavesdropRecorder { fn new(device_info: DeviceInfo) -> Self { Self { recording: Mutex::new(Some(Recording { device_info, transactions: HashMap::new(), })), } } fn get(&self, req: &RecordedHttpRequest) -> Option<RecordedHttpResponse> { self.recording .lock() .unwrap() .as_ref() .unwrap() .transactions .get(req) .cloned() } fn push(&self, transaction: RecordedTransaction) { self.recording .lock() .unwrap() .as_mut() .unwrap() .transactions .insert(transaction.request, transaction.response); } fn write_as_fixture(&self) { let lock = self.recording.lock().unwrap(); let recording = lock.as_ref().unwrap(); let f = std::fs::File::create(fixture_filename(&recording.device_info)).expect("open file"); serde_json::to_writer_pretty(&f, recording).expect("write fixture"); f.sync_all().expect("write fixture"); } } impl Drop for EavesdropRecorder { fn drop(&mut self) { self.write_as_fixture() } } pub struct EavesdropTransport<T: Transport> { recorder: Arc<EavesdropRecorder>, transport: T, } impl<T: Transport> EavesdropTransport<T> { pub fn get(&self, request: &http::Request<Vec<u8>>) -> Option<RecordedHttpResponse> { let request = RecordedHttpRequest::new(&request); self.recorder.get(&request) } } impl<T: Transport> Transport for EavesdropTransport<T> { type Output = EavesdropTransportOutput<T>; type Body = EavesdropTransportBody<T>; type Chunk = T::Chunk; fn roundtrip(&self, request: http::Request<Vec<u8>>) -> Self::Output { let recorded_request = RecordedHttpRequest::new(&request); let future = self.transport.roundtrip(request); EavesdropTransportOutput { inner: future, req: Some((self.recorder.clone(), recorded_request)), } } } #[pin_project] pub struct EavesdropTransportOutput<T: Transport> { #[pin] inner: T::Output, req: Option<(Arc<EavesdropRecorder>, RecordedHttpRequest)>, } impl<T: Transport> Future for EavesdropTransportOutput<T> { type Output = Result<http::Response<EavesdropTransportBody<T>>, crate::transport::Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); match this.inner.poll(cx) { Poll::Ready(Ok(resp)) => { let (resp, body) = resp.into_parts(); let (recorder, req) = this.req.take().unwrap(); let resp_builder = RecordedHttpResponseBuilder::new(&resp); let body = EavesdropTransportBody { inner: body, state: Some((recorder, req, resp_builder)), }; Poll::Ready(Ok(http::Response::from_parts(resp, body))) } Poll::Ready(Err(e)) => Poll::Ready(Err(e)), Poll::Pending => Poll::Pending, } } } #[pin_project] pub struct EavesdropTransportBody<T: Transport> { #[pin] inner: T::Body, state: Option<( Arc<EavesdropRecorder>, RecordedHttpRequest, RecordedHttpResponseBuilder, )>, } impl<T: Transport> futures::Stream for EavesdropTransportBody<T> { type Item = Result<T::Chunk, crate::transport::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.project(); match this.inner.poll_next(cx) { Poll::Ready(Some(Ok(chunk))) => { this.state .as_mut() .unwrap() .2 .add_body_chunk(chunk.as_ref()); Poll::Ready(Some(Ok(chunk))) } Poll::Ready(Some(Err(e))) => { this.state.take(); Poll::Ready(Some(Err(e.into()))) } Poll::Ready(None) => { // done let (recorder, request, response) = this.state.take().unwrap(); let response = response.build(); let tx = RecordedTransaction { request, response }; recorder.push(tx); Poll::Ready(None) } Poll::Pending => Poll::Pending, } } }
extern crate sd12; use sd12::pixels::Color; use std::thread; fn main() { let sd1_context = sd12::init().video().build().unwrap(); // 创建窗口 let window = sd1_context .window("ArcadeRS Shooter", 800, 600) .position_centered() .opengl() .build() .unwrap(); let mut renderer = window.renderer().accelerated().build.unwrap(); renderer.set_draw_color(Color::RGB(0, 0, 0)); renderer.clear(); renderer.present(); thread::sleep_ms(3000); }
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module translates the bytecode of a module to Boogie code. use std::collections::BTreeSet; use itertools::Itertools; use log::info; use stackless_bytecode_generator::{ stackless_bytecode::StacklessBytecode::{self, *}, stackless_bytecode_generator::{StacklessFunction, StacklessModuleGenerator}, }; use crate::boogie_helpers::{ boogie_field_name, boogie_function_name, boogie_local_type, boogie_struct_name, boogie_struct_type_value, boogie_type_check, boogie_type_value, boogie_type_values, }; use crate::env::{ FunctionEnv, GlobalEnv, GlobalType, ModuleEnv, Parameter, StructEnv, TypeParameter, }; use crate::spec_translator::SpecTranslator; use libra_types::account_address::AccountAddress; use libra_types::language_storage::ModuleId; pub struct BoogieTranslator<'env> { pub env: &'env GlobalEnv, } pub struct ModuleTranslator<'env> { pub parent: &'env BoogieTranslator<'env>, pub module_env: ModuleEnv<'env>, pub stackless_bytecode: Vec<StacklessFunction>, } /// Returns true if for the module no code should be produced because its already defined /// in the prelude. pub fn is_module_provided_by_prelude(id: &ModuleId) -> bool { id.name().as_str() == "Vector" && *id.address() == AccountAddress::from_hex_literal("0x0").unwrap() } impl<'env> BoogieTranslator<'env> { pub fn new(env: &'env GlobalEnv) -> Self { Self { env } } pub fn translate(&mut self) -> String { let mut res = String::new(); // generate definitions for all modules. for module_env in self.env.get_modules() { let mut mt = ModuleTranslator::new(self, module_env); res.push_str(&mt.translate()); } res } } impl<'env> ModuleTranslator<'env> { /// Creates a new module translator. Calls the stackless bytecode generator and wraps /// result into the translator. fn new(parent: &'env BoogieTranslator, module: ModuleEnv<'env>) -> Self { let stackless_bytecode = StacklessModuleGenerator::new(module.get_verified_module().as_inner()) .generate_module(); Self { parent, module_env: module, stackless_bytecode, } } /// Translates this module. fn translate(&mut self) -> String { let mut res = String::new(); if !is_module_provided_by_prelude(self.module_env.get_id()) { info!("translating module {}", self.module_env.get_id().name()); res.push_str(&self.translate_structs()); res.push_str(&self.translate_functions()); } res } /// Translates all structs in the module. fn translate_structs(&self) -> String { let mut res = String::new(); res.push_str(&format!( "\n\n// ** structs of module {}\n\n", self.module_env.get_id().name() )); for struct_env in self.module_env.get_structs() { res.push_str(&self.translate_struct_type(&struct_env)); if !struct_env.is_native() { res.push_str(&self.translate_struct_accessors(&struct_env)); } } res } /// Translates the given struct. fn translate_struct_type(&self, struct_env: &StructEnv<'_>) -> String { let mut res = String::new(); // Emit TypeName let struct_name = boogie_struct_name(&struct_env); res.push_str(&format!("const unique {}: TypeName;\n", struct_name)); // Emit FieldNames for (i, field_env) in struct_env.get_fields().enumerate() { let field_name = boogie_field_name(&field_env); res.push_str(&format!( "const {}: FieldName;\naxiom {} == {};\n", field_name, field_name, i )); } // Emit TypeValue constructor function. let type_args = struct_env .get_type_parameters() .iter() .enumerate() .map(|(i, _)| format!("tv{}: TypeValue", i)) .join(", "); let mut field_types = String::from("EmptyTypeValueArray"); for field_env in struct_env.get_fields() { field_types = format!( "ExtendTypeValueArray({}, {})", field_types, boogie_type_value(self.module_env.env, &field_env.get_type()) ); } let type_value = format!("StructType({}, {})", struct_name, field_types); if struct_name == "LibraAccount_T" { // Special treatment of well-known resource LibraAccount_T. The type_value // function is forward-declared in the prelude, here we only add an axiom for // it. res.push_str(&format!( "axiom {}_type_value() == {};\n", struct_name, type_value )); } else { res.push_str(&format!( "function {}_type_value({}): TypeValue {{\n {}\n}}\n", struct_name, type_args, type_value )); } res } /// Translates struct accessors (pack/unpack). fn translate_struct_accessors(&self, struct_env: &StructEnv<'_>) -> String { let mut res = String::new(); // Pack function let type_args_str = struct_env .get_type_parameters() .iter() .map(|TypeParameter(ref i, _)| format!("{}: TypeValue", i)) .join(", "); let args_str = struct_env .get_fields() .map(|field_env| format!("{}: Value", field_env.get_name())) .join(", "); res.push_str(&format!( "procedure {{:inline 1}} Pack_{}({}) returns (_struct: Value)\n{{\n", boogie_struct_name(struct_env), if !args_str.is_empty() && !type_args_str.is_empty() { format!("{}, {}", type_args_str, args_str) } else if args_str.is_empty() { type_args_str } else { args_str.clone() } )); let mut fields_str = String::from("EmptyValueArray"); for field_env in struct_env.get_fields() { let type_check = boogie_type_check( self.module_env.env, field_env.get_name().as_str(), &field_env.get_type(), ); if !type_check.is_empty() { res.push_str(&format!(" {}", type_check)); } fields_str = format!("ExtendValueArray({}, {})", fields_str, field_env.get_name()); } res.push_str(&format!(" _struct := Vector({});\n", fields_str)); res.push_str("\n}\n\n"); // Unpack function res.push_str(&format!( "procedure {{:inline 1}} Unpack_{}(_struct: Value) returns ({})\n{{\n", boogie_struct_name(struct_env), args_str )); res.push_str(" assume is#Vector(_struct);\n"); for field_env in struct_env.get_fields() { res.push_str(&format!( " {} := SelectField(_struct, {});\n", field_env.get_name(), boogie_field_name(&field_env) )); let type_check = boogie_type_check( self.module_env.env, field_env.get_name().as_str(), &field_env.get_type(), ); if !type_check.is_empty() { res.push_str(&format!(" {}", type_check)); } } res.push_str("}\n\n"); res } /// Translates all functions in the module. fn translate_functions(&self) -> String { let mut res = String::new(); res.push_str(&format!( "\n\n// ** functions of module {}\n\n", self.module_env.get_id().name() )); for func_env in self.module_env.get_functions() { res.push_str(&self.translate_function(&func_env)); } res } /// Translates the given function. fn translate_function(&self, func_env: &FunctionEnv<'_>) -> String { let mut res = String::new(); if func_env.is_native() { if self.module_env.env.options.native_stubs { res.push_str(&self.generate_function_sig(func_env, true)); res.push_str(";"); res.push_str(&self.generate_function_spec(func_env)); res.push_str("\n"); } return res; } // generate inline function with function body res.push_str(&self.generate_function_sig(func_env, true)); // inlined version of function res.push_str(&self.generate_function_spec(func_env)); res.push_str(&self.generate_inline_function_body(func_env)); // generate function body res.push_str("\n"); // generate the _verify version of the function which calls inline version for standalone // verification. res.push_str(&self.generate_function_sig(func_env, false)); // no inline res.push_str(&self.generate_verify_function_body(func_env)); // function body just calls inlined version res } /// Translates one bytecode instruction. fn translate_bytecode( &self, func_env: &FunctionEnv<'_>, _offset: usize, bytecode: &StacklessBytecode, ) -> (String, String) { let var_decls = String::new(); let mut res = String::new(); let propagate_abort = "if (abort_flag) { goto Label_Abort; }".to_string(); let stmts = match bytecode { Branch(target) => vec![format!("goto Label_{};", target)], BrTrue(target, idx) => { vec![format!( "tmp := GetLocal(m, old_size + {});\n if (b#Boolean(tmp)) {{ goto Label_{}; }}", idx, target, )] } BrFalse(target, idx) => { vec![format!( "tmp := GetLocal(m, old_size + {});\n if (!b#Boolean(tmp)) {{ goto Label_{}; }}", idx, target, )] } MoveLoc(dest, src) => { if self.get_local_type(func_env, *dest).is_reference() { vec![format!( "call t{} := CopyOrMoveRef({});", dest, func_env.get_local_name(*src) )] } else { vec![ format!( "call tmp := CopyOrMoveValue(GetLocal(m, old_size + {}));", src ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } } CopyLoc(dest, src) => { if self.get_local_type(func_env, *dest).is_reference() { vec![format!( "call t{} := CopyOrMoveRef({});", dest, func_env.get_local_name(*src) )] } else { vec![ format!( "call tmp := CopyOrMoveValue(GetLocal(m, old_size + {}));", src ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } } StLoc(dest, src) => { if self.get_local_type(func_env, *dest as usize).is_reference() { vec![format!( "call {} := CopyOrMoveRef(t{});", func_env.get_local_name(*dest), src )] } else { vec![ format!( "call tmp := CopyOrMoveValue(GetLocal(m, old_size + {}));", src ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } } BorrowLoc(dest, src) => vec![format!("call t{} := BorrowLoc(old_size+{});", dest, src)], ReadRef(dest, src) => vec![ format!("call tmp := ReadRef(t{});", src), boogie_type_check(self.module_env.env, "tmp", &self.get_local_type(func_env, *dest)), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], WriteRef(dest, src) => vec![format!( "call WriteRef(t{}, GetLocal(m, old_size + {}));", dest, src )], FreezeRef(dest, src) => vec![format!("call t{} := FreezeRef(t{});", dest, src)], Call(dests, callee_index, type_actuals, args) => { let (callee_module_env, callee_def_idx) = self.module_env.get_callee_info(callee_index); let callee_env = callee_module_env.get_function(&callee_def_idx); let mut dest_str = String::new(); let mut args_str = String::new(); let mut dest_type_assumptions = vec![]; let mut tmp_assignments = vec![]; args_str.push_str(&boogie_type_values(func_env.module_env.env, &func_env.module_env.get_type_actuals(*type_actuals))); if !args_str.is_empty() && !args.is_empty() { args_str.push_str(", "); } args_str.push_str( &args.iter().map(|arg_idx| { if self.get_local_type(func_env, *arg_idx).is_reference() { format!("t{}", arg_idx) } else { format!("GetLocal(m, old_size + {})", arg_idx) } }).join(", ")); dest_str.push_str(&dests.iter().map(|dest_idx| { let dest = format!("t{}", dest_idx); let dest_type = &self.get_local_type(func_env, *dest_idx); dest_type_assumptions.push(boogie_type_check(self.module_env.env, &dest, dest_type)); if !dest_type.is_reference() { tmp_assignments.push(format!( "m := UpdateLocal(m, old_size + {}, t{});", dest_idx, dest_idx )); } dest }).join(", ")); let mut res_vec = vec![]; if dest_str == "" { res_vec.push(format!("call {}({});", boogie_function_name(&callee_env), args_str)) } else { res_vec.push(format!( "call {} := {}({});", dest_str, boogie_function_name(&callee_env), args_str )); } res_vec.push(propagate_abort); res_vec.extend(dest_type_assumptions); res_vec.extend(tmp_assignments); res_vec } Pack(dest, struct_def_index, type_actuals, fields) => { let struct_env = func_env.module_env.get_struct(struct_def_index); let args_str = func_env.module_env.get_type_actuals(*type_actuals) .iter() .map(|s| boogie_type_value(self.module_env.env, s)) .chain( fields.iter() .map(|i| format!("GetLocal(m, old_size + {})", i)) ) .join(", "); let mut res_vec = vec![]; res_vec.push(format!("call tmp := Pack_{}({});", boogie_struct_name(&struct_env), args_str)); res_vec.push(format!("m := UpdateLocal(m, old_size + {}, tmp);", dest)); res_vec } Unpack(dests, struct_def_index, _, src) => { let struct_env = &func_env.module_env.get_struct(struct_def_index); let mut dests_str = String::new(); let mut tmp_assignments = vec![]; for dest in dests.iter() { if !dests_str.is_empty() { dests_str.push_str(", "); } let dest_str = &format!("t{}", dest); let dest_type = &self.get_local_type(func_env, *dest); dests_str.push_str(dest_str); if !dest_type.is_reference() { tmp_assignments.push(format!( "m := UpdateLocal(m, old_size + {}, t{});", dest, dest )); } } let mut res_vec = vec![format!( "call {} := Unpack_{}(GetLocal(m, old_size + {}));", dests_str, boogie_struct_name(struct_env), src )]; res_vec.extend(tmp_assignments); res_vec } BorrowField(dest, src, field_def_index) => { let struct_env = self.module_env.get_struct_of_field(field_def_index); let field_env = &struct_env.get_field(field_def_index); vec![format!( "call t{} := BorrowField(t{}, {});", dest, src, boogie_field_name(field_env) )] } Exists(dest, addr, struct_def_index, type_actuals) => { let resource_type = boogie_struct_type_value(self.module_env.env, self.module_env.get_module_idx(), struct_def_index, &self.module_env.get_type_actuals(*type_actuals)); vec![ format!( "call tmp := Exists(GetLocal(m, old_size + {}), {});", addr, resource_type ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } BorrowGlobal(dest, addr, struct_def_index, type_actuals) => { let resource_type = boogie_struct_type_value(self.module_env.env, self.module_env.get_module_idx(), struct_def_index, &self.module_env.get_type_actuals(*type_actuals)); vec![format!( "call t{} := BorrowGlobal(GetLocal(m, old_size + {}), {});", dest, addr, resource_type, ), propagate_abort] } MoveToSender(src, struct_def_index, type_actuals) => { let resource_type = boogie_struct_type_value(self.module_env.env, self.module_env.get_module_idx(), struct_def_index, &self.module_env.get_type_actuals(*type_actuals)); vec![format!( "call MoveToSender({}, GetLocal(m, old_size + {}));", resource_type, src, ), propagate_abort] } MoveFrom(dest, src, struct_def_index, type_actuals) => { let resource_type = boogie_struct_type_value(self.module_env.env, self.module_env.get_module_idx(), struct_def_index, &self.module_env.get_type_actuals(*type_actuals)); vec![ format!( "call tmp := MoveFrom(GetLocal(m, old_size + {}), {});", src, resource_type, ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), boogie_type_check(self.module_env.env, &format!("t{}", dest), &self.get_local_type(func_env, *dest)), propagate_abort ] } Ret(rets) => { let mut ret_assignments = vec![]; for (i, r) in rets.iter().enumerate() { if self.get_local_type(func_env, *r).is_reference() { ret_assignments.push(format!("ret{} := t{};", i, r)); } else { ret_assignments.push(format!("ret{} := GetLocal(m, old_size + {});", i, r)); } } ret_assignments.push("return;".to_string()); ret_assignments } LdTrue(idx) => vec![ "call tmp := LdTrue();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], LdFalse(idx) => vec![ "call tmp := LdFalse();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], LdU8(idx, num) => vec![ format!("call tmp := LdConst({});", num), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], LdU64(idx, num) => vec![ format!("call tmp := LdConst({});", num), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], LdU128(idx, num) => vec![ format!("call tmp := LdConst({});", num), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], CastU8(dest, src) => vec![ format!("call tmp := CastU8(GetLocal(m, old_size + {}));", src), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], CastU64(dest, src) => vec![ format!("call tmp := CastU64(GetLocal(m, old_size + {}));", src), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], CastU128(dest, src) => vec![ format!("call tmp := CastU128(GetLocal(m, old_size + {}));", src), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], LdAddr(idx, addr_idx) => { let addr_int = self.module_env.get_address(addr_idx); vec![ format!("call tmp := LdAddr({});", addr_int), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ] } Not(dest, operand) => vec![ format!("call tmp := Not(GetLocal(m, old_size + {}));", operand), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Add(dest, op1, op2) => { let add_type = match self.get_local_type(func_env, *dest) { GlobalType::U8 => "U8", GlobalType::U64 => "U64", GlobalType::U128 => "U128", _ => unreachable!() }; vec![ format!( "call tmp := Add{}(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", add_type, op1, op2 ), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } Sub(dest, op1, op2) => vec![ format!( "call tmp := Sub(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Mul(dest, op1, op2) => { let mul_type = match self.get_local_type(func_env, *dest) { GlobalType::U8 => "U8", GlobalType::U64 => "U64", GlobalType::U128 => "U128", _ => unreachable!() }; vec![ format!( "call tmp := Mul{}(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", mul_type, op1, op2 ), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } Div(dest, op1, op2) => vec![ format!( "call tmp := Div(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Mod(dest, op1, op2) => vec![ format!( "call tmp := Mod(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), propagate_abort, format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Lt(dest, op1, op2) => vec![ format!( "call tmp := Lt(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Gt(dest, op1, op2) => vec![ format!( "call tmp := Gt(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Le(dest, op1, op2) => vec![ format!( "call tmp := Le(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Ge(dest, op1, op2) => vec![ format!( "call tmp := Ge(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Or(dest, op1, op2) => vec![ format!( "call tmp := Or(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], And(dest, op1, op2) => vec![ format!( "call tmp := And(GetLocal(m, old_size + {}), GetLocal(m, old_size + {}));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ], Eq(dest, op1, op2) => { vec![ format!( "tmp := Boolean(IsEqual(GetLocal(m, old_size + {}), GetLocal(m, old_size + {})));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } Neq(dest, op1, op2) => { vec![ format!( "tmp := Boolean(!IsEqual(GetLocal(m, old_size + {}), GetLocal(m, old_size + {})));", op1, op2 ), format!("m := UpdateLocal(m, old_size + {}, tmp);", dest), ] } BitOr(_, _, _) | BitAnd(_, _, _) | Xor(_, _, _) => { vec!["// bit operation not supported".into()] } Abort(_) => vec!["goto Label_Abort;".into()], GetGasRemaining(idx) => vec![ "call tmp := GetGasRemaining();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], GetTxnSequenceNumber(idx) => vec![ "call tmp := GetTxnSequenceNumber();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], GetTxnPublicKey(idx) => vec![ "call tmp := GetTxnPublicKey();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], GetTxnSenderAddress(idx) => vec![ "call tmp := GetTxnSenderAddress();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], GetTxnMaxGasUnits(idx) => vec![ "call tmp := GetTxnMaxGasUnits();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], GetTxnGasUnitPrice(idx) => vec![ "call tmp := GetTxnGasUnitPrice();".to_string(), format!("m := UpdateLocal(m, old_size + {}, tmp);", idx), ], _ => vec!["// unimplemented instruction".into()], }; for code in stmts { res.push_str(&format!(" {}\n", code)); } res.push('\n'); (var_decls, res) } /// Return a string for a boogie procedure header. /// if inline = true, add the inline attribute and use the plain function name /// for the procedure name. Also inject pre/post conditions if defined. /// Else, generate the function signature without the ":inline" attribute, and /// append _verify to the function name. fn generate_function_sig(&self, func_env: &FunctionEnv<'_>, inline: bool) -> String { let (args, rets) = self.generate_function_args_and_returns(func_env); if inline { format!( "procedure {{:inline 1}} {} ({}) returns ({})", boogie_function_name(func_env), args, rets, ) } else { format!( "procedure {}_verify ({}) returns ({})", boogie_function_name(func_env), args, rets ) } } /// Generate boogie representation of function args and return args. fn generate_function_args_and_returns(&self, func_env: &FunctionEnv<'_>) -> (String, String) { let args = func_env .get_type_parameters() .iter() .map(|TypeParameter(ref i, _)| format!("{}: TypeValue", i)) .chain( func_env .get_parameters() .iter() .map(|Parameter(ref i, ref s)| format!("{}: {}", i, boogie_local_type(s))), ) .join(", "); let rets = func_env .get_return_types() .iter() .enumerate() .map(|(i, ref s)| format!("ret{}: {}", i, boogie_local_type(s))) .join(", "); (args, rets) } /// Return string for the function specification. fn generate_function_spec(&self, func_env: &FunctionEnv<'_>) -> String { format!("\n{}", &SpecTranslator::new(func_env).translate()) } /// Return string for body of verify function, which is just a call to the /// inline version of the function. fn generate_verify_function_body(&self, func_env: &FunctionEnv<'_>) -> String { let args = func_env .get_type_parameters() .iter() .map(|TypeParameter(i, _)| i.as_str().to_string()) .chain( func_env .get_parameters() .iter() .map(|Parameter(i, _)| i.as_str().to_string()), ) .join(", "); let rets = (0..func_env.get_return_types().len()) .map(|i| format!("ret{}", i)) .join(", "); let assumptions = " assume ExistsTxnSenderAccount(m, txn);\n"; if rets.is_empty() { format!( "\n{{\n{} call {}({});\n}}\n\n", assumptions, boogie_function_name(func_env), args ) } else { format!( "\n{{\n{} call {} := {}({});\n}}\n\n", assumptions, rets, boogie_function_name(func_env), args ) } } /// This generates boogie code for everything after the function signature /// The function body is only generated for the "inline" version of the function. fn generate_inline_function_body(&self, func_env: &FunctionEnv<'_>) -> String { let mut var_decls = String::new(); let mut res = String::new(); let code = &self.stackless_bytecode[func_env.get_def_idx().0 as usize]; var_decls.push_str("{\n"); var_decls.push_str(" // declare local variables\n"); let num_args = func_env.get_parameters().len(); let mut arg_assignment_str = String::new(); let mut arg_value_assumption_str = String::new(); for (i, local_type) in code.local_types.iter().enumerate() { let local_name = func_env.get_local_name(i as u8); let local_type = &self.module_env.globalize_signature(local_type); if i < num_args { if !local_type.is_reference() { arg_assignment_str.push_str(&format!( " m := UpdateLocal(m, old_size + {}, {});\n", i, local_name )); } arg_value_assumption_str.push_str(&format!( " {}", boogie_type_check(self.module_env.env, &local_name, local_type) )); } else { var_decls.push_str(&format!( " var {}: {}; // {}\n", local_name, boogie_local_type(local_type), boogie_type_value(self.module_env.env, local_type) )); } } var_decls.push_str("\n var tmp: Value;\n"); var_decls.push_str(" var old_size: int;\n"); res.push_str("\n var saved_m: Memory;\n"); res.push_str(" assume !abort_flag;\n"); res.push_str(" saved_m := m;\n"); res.push_str("\n // assume arguments are of correct types\n"); res.push_str(&arg_value_assumption_str); res.push_str("\n old_size := local_counter;\n"); res.push_str(&format!( " local_counter := local_counter + {};\n", code.local_types.len() )); res.push_str(&arg_assignment_str); res.push_str("\n // bytecode translation starts here\n"); // identify all the branching targets so we can insert labels in front of them let mut branching_targets: BTreeSet<usize> = BTreeSet::new(); for bytecode in code.code.iter() { match bytecode { Branch(target) | BrTrue(target, _) | BrFalse(target, _) => { branching_targets.insert(*target as usize); } _ => {} } } for (offset, bytecode) in code.code.iter().enumerate() { // uncomment to print out bytecode for debugging purpose // println!("{:?}", bytecode); // insert labels for branching targets if branching_targets.contains(&offset) { res.push_str(&format!("Label_{}:\n", offset)); } let (new_var_decls, new_res) = self.translate_bytecode(func_env, offset, bytecode); var_decls.push_str(&new_var_decls); res.push_str(&new_res); } res.push_str("Label_Abort:\n"); res.push_str(" abort_flag := true;\n"); res.push_str(" m := saved_m;\n"); for (i, ref sig) in func_env.get_return_types().iter().enumerate() { if sig.is_reference() { res.push_str(&format!(" ret{} := DefaultReference;\n", i)); } else { res.push_str(&format!(" ret{} := DefaultValue;\n", i)); } } res.push_str("}\n"); var_decls.push_str(&res); var_decls } /// Looks up the type of a local in the stackless bytecode representation. fn get_local_type(&self, func_env: &FunctionEnv<'_>, local_idx: usize) -> GlobalType { self.module_env.globalize_signature( &self.stackless_bytecode[func_env.get_def_idx().0 as usize].local_types[local_idx], ) } }
// Copyright 2019, 2020 Wingchain // // 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 rust_crypto::blake2b; use crate::hash::Hash; use crate::HashLength; pub struct Blake2b160; impl Hash for Blake2b160 { fn name(&self) -> String { "blake2b_160".to_string() } fn length(&self) -> HashLength { HashLength::HashLength20 } fn hash(&self, out: &mut [u8], data: &[u8]) { let len: usize = self.length().into(); assert_eq!(out.len(), len); blake2b::Blake2b::blake2b(out, data, &[]); } } pub struct Blake2b256; impl Hash for Blake2b256 { fn name(&self) -> String { "blake2b_256".to_string() } fn length(&self) -> HashLength { HashLength::HashLength32 } fn hash(&self, out: &mut [u8], data: &[u8]) { let len: usize = self.length().into(); assert_eq!(out.len(), len); blake2b::Blake2b::blake2b(out, data, &[]); } } pub struct Blake2b512; impl Hash for Blake2b512 { fn name(&self) -> String { "blake2b_512".to_string() } fn length(&self) -> HashLength { HashLength::HashLength64 } fn hash(&self, out: &mut [u8], data: &[u8]) { let len: usize = self.length().into(); assert_eq!(out.len(), len); blake2b::Blake2b::blake2b(out, data, &[]); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_blake2b_256() { let data = [1u8, 2u8, 3u8]; let mut out = [0u8; 32]; Blake2b256.hash(&mut out, &data); assert_eq!( out, [ 17, 192, 231, 155, 113, 195, 151, 108, 205, 12, 2, 209, 49, 14, 37, 22, 192, 142, 220, 157, 139, 111, 87, 204, 214, 128, 214, 58, 77, 142, 114, 218 ] ); } #[test] fn test_blake2b_160() { let data = [1u8, 2u8, 3u8]; let mut out = [0u8; 20]; Blake2b160.hash(&mut out, &data); assert_eq!( out, [ 197, 117, 145, 134, 122, 108, 242, 5, 233, 74, 212, 142, 167, 139, 236, 142, 103, 194, 14, 98 ] ); } #[test] fn test_blake2b_512() { let data = [1u8, 2u8, 3u8]; let mut out = [0u8; 64]; Blake2b512.hash(&mut out, &data); let expect: [u8; 64] = [ 207, 148, 246, 214, 5, 101, 126, 144, 197, 67, 176, 201, 25, 7, 12, 218, 175, 114, 9, 197, 225, 234, 88, 172, 184, 243, 86, 143, 162, 17, 66, 104, 220, 154, 195, 186, 254, 18, 175, 39, 125, 40, 111, 206, 125, 197, 155, 124, 12, 52, 137, 115, 196, 233, 218, 203, 231, 148, 133, 229, 106, 194, 167, 2, ]; assert_eq!(out.to_vec(), expect.to_vec(),); } }
// A demonstration of an offchain worker that sends onchain callbacks which originally attributed from FRAME example-offchain-worker // More detail of original FRAME example can find here https://github.com/paritytech/substrate/blob/master/frame/example-offchain-worker/src/lib.rs #![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod tests; /// A runtime module template with necessary imports use frame_support::{ debug, decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, }; use parity_scale_codec::{Decode, Encode}; use frame_system::{ self as system, ensure_none, ensure_signed, offchain::{ AppCrypto, CreateSignedTransaction, SendSignedTransaction, SendUnsignedTransaction, SignedPayload, Signer, SigningTypes, SubmitTransaction, }, }; use sp_core::crypto::KeyTypeId; use sp_runtime::{ offchain as rt_offchain, transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, ValidTransaction, }, RuntimeDebug, }; use sp_std::{collections::vec_deque::VecDeque, prelude::*, str}; /// Defines application identifier for crypto keys of this module. /// /// Every module that deals with signatures needs to declare its unique identifier for /// its crypto keys. /// When an offchain worker is signing transactions it's going to request keys from type /// `KeyTypeId` via the keystore to sign the transaction. /// The keys can be inserted manually via RPC (see `author_insertKey`). pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"demo"); pub const NUM_VEC_LEN: usize = 10; /// The type to sign and send transactions. pub const UNSIGNED_TXS_PRIORITY: u64 = 100; pub const HTTP_REMOTE_REQUEST: &str = "https://api.bit.coutrny/getBlockNumber"; pub const HTTP_HEADER_USER_AGENT: &str = "application/json"; pub const FETCH_TIMEOUT_PERIOD: u64 = 3000; /// in milli-seconds pub const LOCK_TIMEOUT_EXPIRATION: u64 = FETCH_TIMEOUT_PERIOD + 1000; /// in milli-seconds pub const LOCK_BLOCK_EXPIRATION: u32 = 3; /// in block number /// Based on the above `KeyTypeId` we need to generate a pallet-specific crypto type wrapper. /// We can utilize the supported crypto kinds (`sr25519`, `ed25519` and `ecdsa`) and augment /// them with the pallet-specific identifier. pub mod crypto { use crate::KEY_TYPE; use sp_core::sr25519::Signature as Sr25519Signature; use sp_runtime::app_crypto::{app_crypto, sr25519}; use sp_runtime::{traits::Verify, MultiSignature, MultiSigner}; app_crypto!(sr25519, KEY_TYPE); pub struct TestAuthId; /// implemented for ocw-runtime impl frame_system::offchain::AppCrypto<MultiSigner, MultiSignature> for TestAuthId { type RuntimeAppPublic = Public; type GenericSignature = sp_core::sr25519::Signature; type GenericPublic = sp_core::sr25519::Public; } /// implemented for mock runtime in test impl frame_system::offchain::AppCrypto<<Sr25519Signature as Verify>::Signer, Sr25519Signature> for TestAuthId { type RuntimeAppPublic = Public; type GenericSignature = sp_core::sr25519::Signature; type GenericPublic = sp_core::sr25519::Public; } } #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] pub struct Payload<Public> { number: u64, public: Public, } impl<T: SigningTypes> SignedPayload<T> for Payload<T::Public> { fn public(&self) -> T::Public { self.public.clone() } } /// This is the pallet's configuration trait pub trait Config: system::Config + CreateSignedTransaction<Call<Self>> { /// The identifier type for an offchain worker. type AuthorityId: AppCrypto<Self::Public, Self::Signature>; /// The overarching dispatch call type. type Call: From<Call<Self>>; /// The overarching event type. type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>; } decl_storage! { trait Store for Module<T: Config> as Example { /// A vector of recently submitted numbers. Bounded by NUM_VEC_LEN Numbers get(fn numbers): VecDeque<u64>; } } decl_event!( /// Events generated by the module. pub enum Event<T> where AccountId = <T as system::Config>::AccountId, { /// Event generated when a new number is accepted to contribute to the average. NewNumber(Option<AccountId>, u64), } ); decl_error! { pub enum Error for Module<T: Config> { /// Error returned when not sure which ocw function to executed UnknownOffchainMux, /// Error returned when making signed transactions in off-chain worker NoLocalAcctForSigning, OffchainSignedTxError, /// Error returned when making unsigned transactions in off-chain worker OffchainUnsignedTxError, /// Error returned when making unsigned transactions with signed payloads in off-chain worker OffchainUnsignedTxSignedPayloadError, /// Error returned when fetching github info HttpFetchingError, } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { fn deposit_event() = default; #[weight = 10000] pub fn submit_number_signed(origin, number: u64) -> DispatchResult { let who = ensure_signed(origin)?; debug::info!("submit_number_signed: ({}, {:?})", number, who); Self::append_or_replace_number(number); Self::deposit_event(RawEvent::NewNumber(Some(who), number)); Ok(()) } #[weight = 10000] pub fn submit_number_unsigned(origin, number: u64) -> DispatchResult { let _ = ensure_none(origin)?; debug::info!("submit_number_unsigned: {}", number); Self::append_or_replace_number(number); Self::deposit_event(RawEvent::NewNumber(None, number)); Ok(()) } #[weight = 10000] pub fn submit_number_unsigned_with_signed_payload(origin, payload: Payload<T::Public>, _signature: T::Signature) -> DispatchResult { let _ = ensure_none(origin)?; /// we don't need to verify the signature here because it has been verified in /// `validate_unsigned` function when sending out the unsigned tx. let Payload { number, public } = payload; debug::info!("submit_number_unsigned_with_signed_payload: ({}, {:?})", number, public); Self::append_or_replace_number(number); Self::deposit_event(RawEvent::NewNumber(None, number)); Ok(()) } fn offchain_worker(block_number: T::BlockNumber) { debug::info!("Entering off-chain worker"); } } } impl<T: Config> Module<T> { /// Append a new number to the tail of the list, removing an element from the head if reaching /// the bounded length. fn append_or_replace_number(number: u64) { Numbers::mutate(|numbers| { if numbers.len() == NUM_VEC_LEN { let _ = numbers.pop_front(); } numbers.push_back(number); debug::info!("Number vector: {:?}", numbers); }); } fn offchain_unsigned_tx(_block_number: T::BlockNumber) -> Result<(), Error<T>> { /// let number: u64 = block_number.try_into().unwrap_or(0) as u64; let number: u64 = 0 as u64; let call = Call::submit_number_unsigned(number); /// `submit_unsigned_transaction` returns a type of `Result<(), ()>` /// ref: https://substrate.dev/rustdocs/v2.0.0/frame_system/offchain/struct.SubmitTransaction.html#method.submit_unsigned_transaction SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()).map_err(|_| { debug::error!("Failed in offchain_unsigned_tx"); <Error<T>>::OffchainUnsignedTxError }) } fn offchain_unsigned_tx_signed_payload(_block_number: T::BlockNumber) -> Result<(), Error<T>> { /// Retrieve the signer to sign the payload let signer = Signer::<T, T::AuthorityId>::any_account(); /// let number: u64 = block_number.try_into().unwrap_or(0) as u64; let number: u64 = 0 as u64; /// `send_unsigned_transaction` is returning a type of `Option<(Account<T>, Result<(), ()>)>`. /// Similar to `send_signed_transaction`, they account for: /// - `None`: no account is available for sending transaction /// - `Some((account, Ok(())))`: transaction is successfully sent /// - `Some((account, Err(())))`: error occured when sending the transaction if let Some((_, res)) = signer.send_unsigned_transaction( |acct| Payload { number, public: acct.public.clone(), }, Call::submit_number_unsigned_with_signed_payload, ) { return res.map_err(|_| { debug::error!("Failed in offchain_unsigned_tx_signed_payload"); <Error<T>>::OffchainUnsignedTxSignedPayloadError }); } /// The case of `None`: no account is available for sending debug::error!("No local account available"); Err(<Error<T>>::NoLocalAcctForSigning) } } impl<T: Config> frame_support::unsigned::ValidateUnsigned for Module<T> { type Call = Call<T>; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { let valid_tx = |provide| { ValidTransaction::with_tag_prefix("ocw-demo") .priority(UNSIGNED_TXS_PRIORITY) .and_provides([&provide]) .longevity(3) .propagate(true) .build() }; match call { Call::submit_number_unsigned(_number) => valid_tx(b"submit_number_unsigned".to_vec()), Call::submit_number_unsigned_with_signed_payload(ref payload, ref signature) => { if !SignedPayload::<T>::verify::<T::AuthorityId>(payload, signature.clone()) { return InvalidTransaction::BadProof.into(); } valid_tx(b"submit_number_unsigned_with_signed_payload".to_vec()) } _ => InvalidTransaction::Call.into(), } } } impl<T: Config> rt_offchain::storage_lock::BlockNumberProvider for Module<T> { type BlockNumber = T::BlockNumber; fn current_block_number() -> Self::BlockNumber { <frame_system::Module<T>>::block_number() } }
#![allow(dead_code)] use core::convert::TryInto; use core::convert::TryFrom; #[derive(Debug)] struct BillAmount { value: f32 } impl From<i32> for BillAmount { fn from(amount: i32) -> Self { BillAmount { value: amount as f32 } } } impl TryFrom<String> for BillAmount { type Error = (); fn try_from (value: String) -> Result<Self, Self::Error> { let number = value.parse::<f32>(); match number { Ok(val) => Ok(BillAmount { value: val }), Err(_reason) => Err(()) } } } pub fn conversion_from_into_test() { let amount = 12; let nbill = BillAmount::from(amount); println!("Created with From -> {:?}", nbill); let nbill_into: BillAmount = amount.into(); println!("Created with Into -> {:?}", nbill_into); let amount_string = "200"; let result: Result<BillAmount, ()> = BillAmount::try_from(amount_string.to_string()); println!("nBill string (try from) -> {:?}", result); let result: Result<BillAmount, ()> = amount_string.to_string().try_into(); println!("nBill string (try into) -> {:?}", result); }
use crate::core::{ authentication_barcode, authentication_nfc, authentication_password, Account, Permission, Pool, ServiceResult, }; use crate::identity_policy::{Action, RetrievedAccount}; use crate::login_required; use crate::web::utils::{EmptyToNone, HbData}; use actix_web::{http, web, HttpRequest, HttpResponse}; use handlebars::Handlebars; #[derive(Debug, Serialize, Deserialize)] pub struct FormSettings { pub name: String, pub mail: String, pub username: String, pub receives_monthly_report: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct FormChangePassword { pub old_password: String, pub new_password: String, pub new_password2: String, } #[derive(Debug, Serialize, Deserialize)] pub struct FormRevoke { pub revoke: String, } impl FormRevoke { pub fn revoke(&self) -> bool { self.revoke == "on" } } /// GET route for `/settings` pub async fn get_settings( pool: web::Data<Pool>, hb: web::Data<Handlebars<'_>>, logged_account: RetrievedAccount, request: HttpRequest, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let conn = &pool.get()?; let has_password = authentication_password::has_password(&conn, &logged_account.account)?; let has_qr_code = !authentication_barcode::get_barcodes(&conn, &logged_account.account)?.is_empty(); let has_nfc_card = !authentication_nfc::get_nfcs(&conn, &logged_account.account)?.is_empty(); let has_mail_address = logged_account.account.mail.is_some(); let receives_monthly_report = logged_account.account.receives_monthly_report; let body = HbData::new(&request) .with_account(logged_account) .with_data("has_password", &has_password) .with_data("has_qr_code", &has_qr_code) .with_data("has_nfc_card", &has_nfc_card) .with_data("has_mail_address", &has_mail_address) .with_data("receives_monthly_report", &receives_monthly_report) .render(&hb, "default_settings")?; // TODO: Checkbox is not checked although checking it works already Ok(HttpResponse::Ok().body(body)) } /// POST route for `/settings` pub async fn post_settings( pool: web::Data<Pool>, logged_account: RetrievedAccount, account: web::Form<FormSettings>, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let conn = &pool.get()?; let mut server_account = Account::get(&conn, &logged_account.account.id)?; server_account.name = account.name.clone(); let new_mail = account.mail.empty_to_none(); // only enable monthly reports when mail address is existent server_account.receives_monthly_report = new_mail.is_some() && (account.receives_monthly_report == Some("on".to_string())); server_account.mail = new_mail; server_account.username = account.username.empty_to_none(); server_account.update(&conn)?; Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings") .finish()) } /// GET route for `/settings/change-password` pub async fn get_change_password( hb: web::Data<Handlebars<'_>>, request: HttpRequest, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let body = HbData::new(&request) .with_data("error", &request.query_string().contains("error")) .render(&hb, "default_settings_change_password")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/settings/change-password` pub async fn post_change_password( pool: web::Data<Pool>, params: web::Form<FormChangePassword>, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let conn = &pool.get()?; if !authentication_password::verify_password( &conn, &logged_account.account, &params.old_password, )? { return Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings/change-password?error") .finish()); } if params.new_password != params.new_password2 { return Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings/change-password?error") .finish()); } authentication_password::register(&conn, &logged_account.account, &params.new_password)?; Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings") .finish()) } /// GET route for `/settings/revoke-password` pub async fn get_revoke_password( hb: web::Data<Handlebars<'_>>, request: HttpRequest, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let body = HbData::new(&request).render(&hb, "default_settings_revoke_password")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/settings/revoke-password` pub async fn post_revoke_password( pool: web::Data<Pool>, params: web::Form<FormRevoke>, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let conn = &pool.get()?; if params.revoke() { authentication_password::remove(&conn, &logged_account.account)?; } Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings") .finish()) } /// GET route for `/settings/revoke-qr` pub async fn get_revoke_qr( hb: web::Data<Handlebars<'_>>, request: HttpRequest, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let body = HbData::new(&request).render(&hb, "default_settings_revoke_qr")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/settings/revoke-qr` pub async fn post_revoke_qr( pool: web::Data<Pool>, params: web::Form<FormRevoke>, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let conn = &pool.get()?; if params.revoke() { authentication_barcode::remove(&conn, &logged_account.account)?; } Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings") .finish()) } /// GET route for `/settings/revoke-nfc` pub async fn get_revoke_nfc( hb: web::Data<Handlebars<'_>>, request: HttpRequest, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let _logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let body = HbData::new(&request).render(&hb, "default_settings_revoke_nfc")?; Ok(HttpResponse::Ok().body(body)) } /// POST route for `/settings/revoke-nfc` pub async fn post_revoke_nfc( pool: web::Data<Pool>, params: web::Form<FormRevoke>, logged_account: RetrievedAccount, ) -> ServiceResult<HttpResponse> { let logged_account = login_required!(logged_account, Permission::DEFAULT, Action::REDIRECT); let conn = &pool.get()?; if params.revoke() { authentication_nfc::remove(&conn, &logged_account.account)?; } Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings") .finish()) } /// GET route for `/settings/theme/{theme}` pub async fn get_theme( theme: web::Path<String>, ) -> ServiceResult<HttpResponse> { let expires = time::now() + time::Duration::days(365); Ok(HttpResponse::Found() .header(http::header::LOCATION, "/settings") .cookie( http::Cookie::build("theme", theme.into_inner()) .path("/") .expires(expires) .finish(), ) .finish()) }
//! The backend target code. pub use self::registry::Registry; pub use self::machine::Machine; pub use self::compilation::Compilation; // Reexports. pub use sys::target::FileType; pub mod registry; pub mod machine; pub mod compilation; use SafeWrapper; use sys; use std::{ffi, fmt}; /// A target triple. pub struct Triple(pub String); /// A CPU name. pub struct CPU(pub String); /// An LLVM target. pub struct Target(sys::TargetRef); impl Target { /// Gets the name of the target. pub fn name(&self) -> String { unsafe { let ptr = sys::LLVMRustTargetGetName(self.0); ffi::CStr::from_ptr(ptr).to_str().unwrap().to_owned() } } /// Gets the short description of the target. pub fn short_description(&self) -> String { unsafe { let ptr = sys::LLVMRustTargetGetShortDescription(self.0); ffi::CStr::from_ptr(ptr).to_str().unwrap().to_owned() } } /// Creates a machine object. pub fn create_machine(&self, triple: &str, cpu: &str, features: &str) -> Machine { let triple = ffi::CString::new(triple).unwrap(); let cpu = ffi::CString::new(cpu).unwrap(); let features = ffi::CString::new(features).unwrap(); unsafe { let inner = sys::LLVMRustTargetCreateTargetMachine(self.0, triple.as_ptr(), cpu.as_ptr(), features.as_ptr()); Machine::from_inner(inner) } } /// Checks if the target has defined an `MCAsmBackend`. pub fn has_mc_asm_backend(&self) -> bool { unsafe { sys::LLVMRustTargetHasMCAsmBackend(self.0) } } /// Checks if the target has defined a `TargetMachine`. pub fn has_target_machine(&self) -> bool { unsafe { sys::LLVMRustTargetHasTargetMachine(self.0) } } /// Checks if the target supports just-in-time compilation. pub fn has_jit(&self) -> bool { unsafe { sys::LLVMRustTargetHasJIT(self.0) } } } impl SafeWrapper for Target { type Inner = sys::TargetRef; unsafe fn from_inner(inner: sys::TargetRef) -> Self { Target(inner) } fn inner(&self) -> sys::TargetRef { self.0 } } impl fmt::Debug for Target { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Target({} - \"{}\")", self.name(), self.short_description()) } } impl CPU { /// Gets the CPU name of the host CPU. pub fn native() -> Self { CPU("native".to_owned()) } } impl Default for Triple { fn default() -> Self { let s = unsafe { sys::DefaultTargetTriple() }; Triple(s.as_string().expect("default target triple is not valid utf-8")) } } impl Default for CPU { fn default() -> Self { CPU("".to_owned()) } } impl fmt::Display for Triple { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(fmt) } } impl fmt::Display for CPU { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(fmt) } }
use std::cell::{RefCell}; use std::rc::{Rc, Weak}; pub type ColumnIndex = usize; pub type RowIndex = usize; /// `NodeExtra` contains the information specific to a node's /// type. For instance, only constraint (column) header nodes require /// a count of how many nodes are contained in the column. The type of /// node (header, inner, or root) can be directly inferred by the enum /// value. #[derive(Debug)] pub enum NodeExtra { Row(RowIndex), // The node is an inner node, representing part of an action. Count(usize), // The node is a header for a constraints. Root // Root node. } /// A `Node` represents multiple types in the DLX algorithm. Most nodes /// are 'inner' nodes, essentially representing 1's in the sparse /// matrix representation of the problem. Headers `Node`s contain a /// current count of how many actions can be used to satisfy the /// constaint. /// /// Throughout the code, nodes are almost never dealt with /// directly. Instead, nodes are handled either through `WeakNode`s or /// `OwnedNode`s. /// /// `Node`s exclusively store neighbor pointers as `WeakNode`s to /// prevent memory leaks via cyclical references. #[derive(Debug)] pub struct Node { up: Weak<RefCell<Node>>, down: Weak<RefCell<Node>>, left: Weak<RefCell<Node>>, right: Weak<RefCell<Node>>, at_self: Weak<RefCell<Node>>, pub column: Option<ColumnIndex>, header: Weak<RefCell<Node>>, extra: NodeExtra } pub type OwnedNode = Rc<RefCell<Node>>; pub type WeakNode = Weak<RefCell<Node>>; impl Node { pub fn new_header(col: Option<usize>) -> OwnedNode { Self::new(col, None, NodeExtra::Count(0)) } pub fn new_inner(header: &OwnedNode, row: usize) -> OwnedNode { Self::new(header.borrow().column, Some(&Rc::downgrade(&header)), NodeExtra::Row(row)) } pub fn new_root() -> OwnedNode { Self::new(None, None, NodeExtra::Root) } /// Create new node that circularly points to itself. fn new(col: Option<usize>, header: Option<&WeakNode>, e: NodeExtra) -> OwnedNode { let rc = Rc::new(RefCell::new(Node { up: Weak::new(), down: Weak::new(), left: Weak::new(), right: Weak::new(), at_self: Weak::new(), header: Weak::new(), column: col, extra: e })); { let mut nc = (*rc).borrow_mut(); let w = Rc::downgrade(&rc); nc.up = w.clone(); nc.down = w.clone(); nc.left = w.clone(); nc.right = w.clone(); nc.at_self = w.clone(); nc.header = match header { Some(n) => n.clone(), None => w.clone() } } rc } /// return the down link pub fn down(&self) -> WeakNode { self.down.clone() } /// return the up link pub fn up(&self) -> WeakNode { self.up.clone() } /// return the left link pub fn left(&self) -> WeakNode { self.left.clone() } /// return the right link pub fn right(&self) -> WeakNode { self.right.clone() } /// Return the count for a header node, and None for other nodes. pub fn get_count(&self) -> Option<usize> { match self.extra { NodeExtra::Count(i) => Some(i), _ => None } } pub fn dec_count(&mut self) { let c = match self.extra { NodeExtra::Count(i) => i, _ => return }; self.extra = NodeExtra::Count(c-1); } pub fn inc_count(&mut self) { let c = match self.extra { NodeExtra::Count(i) => i, _ => return }; self.extra = NodeExtra::Count(c+1); } /// Return the associated row index for an inner node, and None /// for other nodes. pub fn get_row(&self) -> Option<usize> { match self.extra { NodeExtra::Row(i) => Some(i), _ => None } } /// Return the constraint header of this node. pub fn get_header(&self) -> WeakNode { self.header.clone() } /// Return true iff this is a header node and the column has /// already been chosen. pub fn is_already_chosen(&self) -> bool { if let NodeExtra::Count(_) = self.extra { let r = self.right.upgrade().unwrap(); let l = r.borrow().left().upgrade().unwrap(); let lc = l.borrow().column; lc != self.column } else { false } } /// Remove a node from its column pub fn remove_from_column(&mut self) { let up_weak = self.up.clone(); let down_weak = self.down.clone(); let up = up_weak.upgrade().unwrap(); up.borrow_mut().down = down_weak.clone(); let down = down_weak.upgrade().unwrap(); down.borrow_mut().up = up_weak; } /// Remove a node from its row pub fn remove_from_row(&mut self) { let l = self.left.clone(); let r = self.right.clone(); let lrc = self.left.upgrade().unwrap(); (*lrc).borrow_mut().right = r; let rrc = self.right.upgrade().unwrap(); (*rrc).borrow_mut().left = l; } /// Re-add a node to its column pub fn reinsert_into_column(&mut self) { let urc = self.up.upgrade().unwrap(); (*urc).borrow_mut().down = self.at_self.clone(); let drc = self.down.upgrade().unwrap(); (*drc).borrow_mut().up = self.at_self.clone(); } /// Re-add a node to its row pub fn reinsert_into_row(&mut self) { let lrc = self.left.upgrade().unwrap(); (*lrc).borrow_mut().right = self.at_self.clone(); let rrc = self.right.upgrade().unwrap(); (*rrc).borrow_mut().left = self.at_self.clone(); } } pub fn get_header(n: &WeakNode) -> WeakNode { let s = n.upgrade().unwrap(); let h = s.borrow().get_header(); h.clone() } // impl fmt::Display for Node { // fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // write!(f, "({:?}, {:?})", self.row, self.column) // } // } /// Prepend `node` to the left of `root. pub fn prepend_left(root: &OwnedNode, node: &WeakNode) { let l = (*node).upgrade().unwrap(); { let mut n = l.borrow_mut(); n.right = Rc::downgrade(&root); n.left = root.borrow_mut().left.clone(); } { let mut head = root.borrow_mut(); head.left = (*node).clone(); } { let pleft = l.borrow_mut(); let prev_left = pleft.left.upgrade().unwrap(); prev_left.borrow_mut().right = (*node).clone(); } } /// Prepend node above root. pub fn prepend_up(root: &OwnedNode, node: &WeakNode) { let u = (*node).upgrade().unwrap(); { let mut n = u.borrow_mut(); n.down = Rc::downgrade(&root); n.up = root.borrow_mut().up.clone(); } { let mut head = root.borrow_mut(); head.up = (*node).clone(); } { let pup = u.borrow_mut(); let prev_up = pup.up.upgrade().unwrap(); prev_up.borrow_mut().down = (*node).clone(); } } #[derive(Debug)] pub struct Row<Action: Copy> { nodes: Vec<Rc<RefCell<Node>>>, id: usize, action: Action } impl<Action: Copy> Row<Action> { pub fn new(nodes: Vec<OwnedNode>, action: Action, index: usize) -> Self { let l = nodes.len(); for i in l..(2*l) { let mut n = nodes[i % l].borrow_mut(); n.left = Rc::downgrade(&nodes[(i-1) % l]); n.right = Rc::downgrade(&nodes[(i+1) % l]); } Row {nodes: nodes, id: index, action: action } } pub fn first_node(&self) -> WeakNode { Rc::downgrade(&self.nodes[0]) } pub fn iter(&self) -> FullRowIterator { FullRowIterator::new(&self) } pub fn action(&self) -> Action { self.action } } /// Iterator for row nodes (not header rwos) pub struct FullRowIterator { head_column: ColumnIndex, curr: OwnedNode, started: bool } impl FullRowIterator { pub fn new<A: Copy>(row: &Row<A>) -> FullRowIterator { FullRowIterator{ head_column: row.nodes[0].borrow().column.unwrap(), curr: row.nodes[0].clone(), started: false } } } impl Iterator for FullRowIterator { type Item = WeakNode; fn next(&mut self) -> Option<WeakNode> { let ret = self.curr.clone(); if self.started { if ret.borrow().column.unwrap() == self.head_column { return None } } self.curr = { let r = self.curr.borrow().right(); r.upgrade().unwrap() }; self.started = true; Some(Rc::downgrade(&ret)) } }
//use futures::future; use linkerd_app_core::{svc::stack::Predicate, svc::stack::Switch, Error}; /// A connection policy that drops #[derive(Copy, Clone, Debug)] pub struct PreventLoop { port: u16, } #[derive(Copy, Clone, Debug)] pub struct LoopPrevented { port: u16, } impl From<u16> for PreventLoop { fn from(port: u16) -> Self { Self { port } } } impl<T> Predicate<T> for PreventLoop where for<'t> &'t T: Into<std::net::SocketAddr>, { type Request = T; fn check(&mut self, t: T) -> Result<T, Error> { let addr = (&t).into(); tracing::debug!(%addr, self.port); if addr.port() == self.port { return Err(LoopPrevented { port: self.port }.into()); } Ok(t) } } impl<T> Switch<T> for PreventLoop where for<'t> &'t T: Into<std::net::SocketAddr>, { fn use_primary(&self, target: &T) -> bool { let addr = target.into(); tracing::debug!(%addr, self.port); addr.port() != self.port } } impl std::fmt::Display for LoopPrevented { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "inbound requests must not target localhost:{}", self.port ) } } impl std::error::Error for LoopPrevented {}
pub type HttpParserResult<T> = Result<T, HttpParserError>; pub enum HttpParserError { }
use std::fs::{File, read_dir}; use std::io::{Error, Read}; /// Obtains a list of video extensions from the `/etc/mime.types` file on Linux. pub fn get_extensions(kind: &'static str) -> Result<Vec<String>, Error> { let mut extension_list = Vec::new(); let mut buffer = String::new(); for extension_file in read_dir(&["/usr/share/mime/", kind].concat())? { let extension_file = extension_file?; let mut file = File::open(extension_file.path())?; let capacity = file.metadata().map(|x| x.len()).unwrap_or(0); buffer.reserve(capacity as usize); file.read_to_string(&mut buffer)?; for line in buffer.split('\n') { let line = line.trim(); if line.starts_with("<glob pattern=\"") { let extension = line.split('"').nth(1) .and_then(|extension| extension.split('.').last()); if let Some(extension) = extension { extension_list.push(extension.to_owned()); } } } } Ok(extension_list) }
#[test] fn test() { }
//! An almost exact copy of the example of a custom drawing widget from Druid itself //! We plan to draw tablature use core::f64; use druid::kurbo::Line; use druid::piet::{FontFamily, ImageFormat, InterpolationMode, Text, TextLayoutBuilder}; use druid::widget::prelude::*; use druid::{ Affine, AppLauncher, Color, FontDescriptor, LocalizedString, Rect, TextLayout, WindowDesc, }; use std::sync::Arc; use num::rational::Rational32; struct FretNumber(u32); struct StringNumber(u32); /// How many beats in a bar, so 4, for 4:4 time and two for 2:4 time struct BeatsPerBar(u32); /// The duration of one beat, usually a power of two, a crotchet for 2:4 or 4:4 struct NoteValue(u32); struct Signature { bpb: BeatsPerBar, value: NoteValue, } /// An ugly little helper, approximate a rational /// by a float, this is potentially lossy, consider 1/3 => 1.33333... fn as_float(r: &Rational32) -> f64 { (*(r.numer()) as f64) / (*(r.denom()) as f64) } /// The units here are beats, we allow for fractional positions, such as half a beat /// and for accuracy store that as a private ratio n/d struct BarPosition(Rational32); impl BarPosition { fn new() -> BarPosition { BarPosition(num::zero()) } fn from_ratio(n: i32, d: i32) -> BarPosition { BarPosition(Rational32::new(n, d)) } fn as_float(&self) -> f64 { as_float(&self.0) } } /// A notation gives a fret, a string, and a bar position enum Action { Unused(), Simple(BarPosition), Muted(), } struct Notation { fret: FretNumber, action: Action, } struct Chord { notations: Vec<Notation>, // One per string position: BarPosition, } struct Bar { size: f64, // relative, 1.0 == default, 2.0 == twice default, etc... signature: Signature, notations: Vec<Notation>, } #[derive(Clone, Data)] struct AppData { bars: Arc<Vec<Bar>>, } impl AppData { pub fn new() -> AppData { AppData { bars: Arc::new(Vec::new()), } } } struct TablatureWidget { t: f64, image_width: usize, image_height: usize, image_data: Vec<u8>, } impl TablatureWidget { pub const STRING_COLOR: Color = Color::rgb8(0, 128, 0); fn get_image_data(&mut self, width: usize, height: usize) -> &Vec<u8> { if width != self.image_width || height != self.image_height { let mut result = vec![0; width * height * 4]; for y in 0..height { for x in 0..width { let ix = (y * width + x) * 4; result[ix] = x as u8; result[ix + 1] = y as u8; result[ix + 2] = !(x as u8); result[ix + 3] = 127; } } self.image_data = result; } &self.image_data } pub fn new() -> TablatureWidget { TablatureWidget { t: 0.0, image_width: 0, image_height: 0, image_data: Vec::new(), } } } // If this widget has any child widgets it should call its event, update and layout // (and lifecycle) methods as well to make sure it works. Some things can be filtered, // but a general rule is to just pass it through unless you really know you don't want it. impl Widget<AppData> for TablatureWidget { fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut AppData, _env: &Env) { match event { Event::MouseDown(_) => { self.t = 0.0; ctx.request_anim_frame(); } Event::AnimFrame(interval) => { ctx.request_paint(); self.t += (*interval as f64) * 1e-9; ctx.request_anim_frame(); } _ => (), } } fn lifecycle( &mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &AppData, _env: &Env, ) { } fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &AppData, _data: &AppData, _env: &Env) {} fn layout( &mut self, _layout_ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &AppData, _env: &Env, ) -> Size { // BoxConstraints are passed by the parent widget. // This method can return any Size within those constraints: // bc.constrain(my_size) // // To check if a dimension is infinite or not (e.g. scrolling): // bc.is_width_bounded() / bc.is_height_bounded() // // bx.max() returns the maximum size of the widget. Be careful // using this, since always make sure the widget is bounded. // If bx.max() is used in a scrolling widget things will probably // not work correctly. if bc.is_width_bounded() | bc.is_height_bounded() { let size = Size::new(100.0, 100.0); bc.constrain(size) } else { bc.max() } } // The paint method gets called last, after an event flow. // It goes event -> update -> layout -> paint, and each method can influence the next. // Basically, anything that changes the appearance of a widget causes a paint. fn paint(&mut self, ctx: &mut PaintCtx, data: &AppData, env: &Env) { // Clear the whole widget with the color of your choice // (ctx.size() returns the size of the layout rect we're painting in) // Note: ctx also has a `clear` method, but that clears the whole context, // and we only want to clear this widget's area. let size = ctx.size(); let rect = size.to_rect(); ctx.fill(rect, &Color::WHITE); let timex = self.t * 100.0; let line_delta = size.height / 7.0; let mut line_y = line_delta; // Kinda hack, should be neck margin for _i in 0..6 { ctx.stroke( Line::new((0.0, line_y), (size.width, line_y)), &Self::STRING_COLOR, 4.0, ); line_y += line_delta; } // Rectangles: the path for practical people let nut_rect = Rect::new(0.0, 0.0, line_delta / 5.0, size.height); // My nuts are black let fill_color = Color::rgb8(0x00, 0x00, 0x00); ctx.fill(nut_rect, &fill_color); // Text is easy; in real use TextLayout should either be stored in the // widget and reused, or a label child widget to manage it all. // This is one way of doing it, you can also use a builder-style way. let mut layout = new_text_layout("Whoops no data"); layout.rebuild_if_needed(ctx.text(), env); for bar in data.bars.iter().enumerate() { let x = bar.0 as f64; layout.draw(ctx, (80.0 + (x * 10.0), 40.0 + (x * 15.0))); } // Let's rotate our text slightly. First we save our current (default) context: ctx.with_save(|ctx| { // Now we can rotate the context (or set a clip path, for instance): // This makes it so that anything drawn after this (in the closure) is // transformed. // The transformation is in radians, but be aware it transforms the canvas, // not just the part you are drawing. So we draw at (80.0, 40.0) on the rotated // canvas, this is NOT the same position as (80.0, 40.0) on the original canvas. ctx.transform(Affine::rotate(std::f64::consts::FRAC_PI_4)); layout.draw(ctx, (80.0, 40.0)); }); // When we exit with_save, the original context's rotation is restored // This is the builder-style way of drawing text. let text = ctx.text(); let layout = text .new_text_layout("Still no data!!") .font(FontFamily::SERIF, 24.0) .text_color(Color::rgb8(128, 0, 0)) .build() .unwrap(); ctx.draw_text(&layout, (100.0 + timex, 25.0)); // Let's burn some CPU to make a (partially transparent) image buffer let image_data = self.get_image_data(256, 256); let image = ctx .make_image(256, 256, image_data, ImageFormat::RgbaSeparate) .unwrap(); // The image is automatically scaled to fit the rect you pass to draw_image ctx.draw_image(&image, size.to_rect(), InterpolationMode::Bilinear); } } pub fn main() { let window = WindowDesc::new(TablatureWidget::new()).title(LocalizedString::new("fret")); AppLauncher::with_window(window) .log_to_console() .launch(AppData::new()) .expect("launch failed"); } fn new_text_layout(data: &str) -> TextLayout<String> { let fill_color = Color::rgb8(0x00, 0x00, 0x00); let mut layout = TextLayout::<String>::from_text(data); layout.set_font(FontDescriptor::new(FontFamily::SERIF).with_size(24.0)); layout.set_text_color(fill_color); layout }
use std::env; extern crate rand; use self::rand::Rng; use yak_client::Client; pub fn open_from_env(env_var: &str, name: &str, test_id: u64) -> Client { let yak_url = env::var(env_var).ok() .expect(&format!("env var {} not found", env_var)); let full_url = format!("{}-{}-{:x}", yak_url, name, test_id); info!("Connecting to:{:?}", full_url); Client::connect(&full_url).unwrap() } pub fn open_client(name: &str) -> (Client, Client) { let test_id = rand::thread_rng().next_u64(); let head = open_from_env("YAK_HEAD", name, test_id); let tail = open_from_env("YAK_TAIL", name, test_id); (head, tail) }
use std::env; use roman::convert_and_print_numerals; const HELP_COPY: &str = "Please specify either one or multiple: a) Roman numerals to be converted to Arabic numerals b) Arabic numerals to be converted to Roman numerals"; fn main() { let args: Vec<String> = env::args().collect(); match args.len() { 0 | 1 => println!("{}", HELP_COPY), _ => convert_and_print_numerals(&args[1..]), } }
use core::cmp::min; use micromath::F32Ext; use crate::pac::{rcc, FLASH, RCC}; use crate::time::Hertz; /// Extension trait that constrains the `RCC` peripheral pub trait RccExt { /// Constrains the `RCC` peripheral so it plays nicely with the other abstractions fn constrain(self) -> Rcc; } impl RccExt for RCC { fn constrain(self) -> Rcc { Rcc { ahb1: AHB1 { _0: () }, ahb2: AHB2 { _0: () }, ahb3: AHB3 { _0: () }, apb1: APB1 { _0: () }, apb2: APB2 { _0: () }, cfgr: CFGR { hse: None, hclk: None, pclk1: None, pclk2: None, sysclk: None, timclk1: None, timclk2: None, }, } } } /// Constrained RCC peripheral pub struct Rcc { /// Advanced High-Performance Bus 1 (AHB1) registers pub ahb1: AHB1, /// Advanced High-Performance Bus 2 (AHB2) registers pub ahb2: AHB2, /// Advanced High-Performance Bus 3 (AHB3) registers pub ahb3: AHB3, /// Advanced Peripheral Bus 1 (APB1) registers pub apb1: APB1, /// Advanced Peripheral Bus 2 (APB2) registers pub apb2: APB2, pub cfgr: CFGR, } /// Advanced Peripheral Bus 1 (APB1) registers pub struct APB1 { _0: (), } impl APB1 { pub(crate) fn enr(&mut self) -> &rcc::APB1ENR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).apb1enr } } pub(crate) fn rstr(&mut self) -> &rcc::APB1RSTR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).apb1rstr } } } /// Advanced Peripheral Bus 2 (APB2) registers pub struct APB2 { _0: (), } impl APB2 { pub(crate) fn enr(&mut self) -> &rcc::APB2ENR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).apb2enr } } pub(crate) fn rstr(&mut self) -> &rcc::APB2RSTR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).apb2rstr } } } /// Advanced High-performance Bus 1 (AHB1) registers pub struct AHB1 { _0: (), } impl AHB1 { pub(crate) fn enr(&mut self) -> &rcc::AHB1ENR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).ahb1enr } } pub(crate) fn rstr(&mut self) -> &rcc::AHB1RSTR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).ahb1rstr } } } /// Advanced High-performance Bus 2 (AHB2) registers pub struct AHB2 { _0: (), } #[allow(dead_code)] impl AHB2 { pub(crate) fn enr(&mut self) -> &rcc::AHB2ENR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).ahb2enr } } pub(crate) fn rstr(&mut self) -> &rcc::AHB2RSTR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).ahb2rstr } } } /// Advanced High-performance Bus 3 (AHB3) registers pub struct AHB3 { _0: (), } #[allow(dead_code)] impl AHB3 { pub(crate) fn enr(&mut self) -> &rcc::AHB3ENR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).ahb3enr } } pub(crate) fn rstr(&mut self) -> &rcc::AHB3RSTR { // NOTE(unsafe) this proxy grants exclusive access to this register unsafe { &(*RCC::ptr()).ahb3rstr } } } /// HSE Clock modes /// * `Oscillator`: Use of an external crystal/ceramic resonator /// * `Bypass`: Use of an external user clock pub enum HSEClockMode { Oscillator, Bypass, } /// HSE Clock pub struct HSEClock { pub freq: u32, pub mode: HSEClockMode, } impl HSEClock { /// Provide HSE frequency. Must be between 4 and 26 MHz pub fn new<F>(freq: F, mode: HSEClockMode) -> Self where F: Into<Hertz>, { let f: u32 = freq.into().0; assert!(4_000_000 <= f && f <= 26_000_000); HSEClock { freq: f, mode } } } const HSI: u32 = 16_000_000; // Hz pub struct CFGR { hse: Option<HSEClock>, hclk: Option<u32>, pclk1: Option<u32>, pclk2: Option<u32>, sysclk: Option<u32>, timclk1: Option<u32>, timclk2: Option<u32>, } impl CFGR { /// Declare an HSE clock if available. pub fn hse(mut self, hse: HSEClock) -> Self { self.hse = Some(hse); self } /// Set HCLK Clock (AHB bus, core, memory and DMA. /// Specified frequency must be <= 216 MHz pub fn hclk<F>(mut self, freq: F) -> Self where F: Into<Hertz>, { let f: u32 = freq.into().0; assert!(f <= 216_000_000); self.hclk = Some(f); self } /// Set PCLK1 Clock (APB1 clock). Must be <= 54 Mhz. By default, max /// frequency is chosen pub fn pclk1<F>(mut self, freq: F) -> Self where F: Into<Hertz>, { let f: u32 = freq.into().0; assert!(12_500_000 <= f && f <= 54_000_000); self.pclk1 = Some(f); self } /// Set PCLK2 Clock (APB2 clock). Must be <= 108 Mhz. By default, max /// frequency is chosen pub fn pclk2<F>(mut self, freq: F) -> Self where F: Into<Hertz>, { let f: u32 = freq.into().0; assert!(12_500_000 <= f && f <= 108_000_000); self.pclk2 = Some(f); self } /// Set SYSCLK Clock. It must be between 12.5 Mhz and 216 Mhz. /// If the ethernet peripheral is on, the user should set a /// frequency higher than 25 Mhz pub fn sysclk<F>(mut self, freq: F) -> Self where F: Into<Hertz>, { let f: u32 = freq.into().0; assert!(12_500_000 <= f && f <= 216_000_000); self.sysclk = Some(f); self } pub fn timclk1<F>(mut self, freq: F) -> Self where F: Into<Hertz>, { self.timclk1 = Some(freq.into().0); self } pub fn timclk2<F>(mut self, freq: F) -> Self where F: Into<Hertz>, { self.timclk2 = Some(freq.into().0); self } /// Configure the "mandatory" clocks (`sysclk`, `hclk`, `pclk1` and `pclk2') /// and return them via the `Clocks` struct. /// /// The user shouldn't call freeze more than once as the clocks parameters /// cannot be changed after the clocks have started. /// /// The implementation makes the following choice: HSI is always chosen over /// HSE except when HSE is provided. When HSE is provided, HSE is used /// wherever it is possible. pub fn freeze(self) -> Clocks { let flash = unsafe { &(*FLASH::ptr()) }; let rcc = unsafe { &(*RCC::ptr()) }; // Switch to fail-safe clock settings. // This is useful when booting from a bootloader that alters clock tree configuration. // Turn on HSI rcc.cr.modify(|_, w| w.hsion().set_bit()); while rcc.cr.read().hsirdy().bit_is_clear() {} // Switch to HSI rcc.cfgr.modify(|_, w| w.sw().hsi()); let base_clk = match self.hse.as_ref() { Some(hse) => hse.freq, None => HSI, }; // SYSCLK, must be <= 216 Mhz. By default, HSI/HSE frequency is chosen let mut sysclk = self.sysclk.unwrap_or(base_clk); // Configure HSE if provided if self.hse.is_some() { // Configure the HSE mode match self.hse.as_ref().unwrap().mode { HSEClockMode::Bypass => rcc.cr.modify(|_, w| w.hsebyp().bypassed()), HSEClockMode::Oscillator => rcc.cr.modify(|_, w| w.hsebyp().not_bypassed()), } // Start HSE rcc.cr.modify(|_, w| w.hseon().on()); while rcc.cr.read().hserdy().is_not_ready() {} } let mut use_pll = false; if sysclk != base_clk { // A PLL is needed to multiply / divide the frequency // Input divisor from HSI/HSE clock, must result in less than 2MHz, and // must be between 2 and 63. In this case, the condition is always // respected. We set it at 2MHz as recommended by the user manual. let pllm = ((base_clk as f32) / (2_000_000 as f32)).ceil() as u8; let vco_clkin_mhz = (base_clk as f32 / pllm as f32) / 1_000_000.0; let mut sysclk_mhz: f32 = sysclk as f32 / 1_000_000.0; // PLLN, main scaler, must result in VCO frequency >=100MHz and <=432MHz, // PLLN min 50, max 432, this constraint is always respected when // vco_clkin <= 2 MHz let mut plln: f32 = 100.0; let allowed_pllp: [u8; 4] = [2, 4, 6, 8]; let pllp_val = *allowed_pllp .iter() .min_by_key(|&pllp| { plln = ((sysclk_mhz * (*pllp as f32)) / vco_clkin_mhz).floor(); let error = sysclk_mhz - ((plln / (*pllp as f32)) * vco_clkin_mhz); if error < 0.0 || plln * vco_clkin_mhz < 100.0 || plln * vco_clkin_mhz > 432.0 || plln < 50.0 || plln > 432.0 { core::u32::MAX } else { (error * 1_000.0) as u32 } }) .unwrap(); // PLLN corresponding to the best pllp_val plln = ((sysclk_mhz * (pllp_val as f32)) / vco_clkin_mhz).floor(); // Pllp bits to be written in the register let pllp = match pllp_val { 2 => 0b00, 4 => 0b01, 6 => 0b10, 8 => 0b11, _ => unreachable!(), }; // Update the real sysclk value sysclk_mhz = (vco_clkin_mhz * plln) / (pllp_val as f32); sysclk = (sysclk_mhz * 1_000_000.0) as u32; // Turn PLL off rcc.cr.modify(|_, w| w.pllon().off()); // Wait till PLL is disabled while !rcc.cr.read().pllrdy().is_not_ready() {} if self.hse.is_some() { // If HSE is provided // Configure PLL from HSE rcc.pllcfgr.write(|w| unsafe { w.pllsrc() .hse() .pllm() .bits(pllm as u8) .plln() .bits(plln as u16) .pllp() .bits(pllp) .pllq() .bits(9) }); } else { // If HSE is not provided // configure PLL from HSI rcc.pllcfgr.modify(|_, w| unsafe { w.pllsrc() .hsi() .pllm() .bits(pllm as u8) .plln() .bits(plln as u16) .pllp() .bits(pllp) }); } // Enable PLL rcc.cr.modify(|_, w| w.pllon().on()); // // Wait for PLL to stabilise while rcc.cr.read().pllrdy().is_not_ready() {} use_pll = true; } // HCLK. By default, SYSCLK frequency is chosen. Because of the method // of clock multiplication and division, even if `sysclk` is set to be // the same as `hclk`, it can be slightly inferior to `sysclk` after // pllm, pllp... calculations let mut hclk: u32 = sysclk; // min(sysclk, self.hclk.unwrap_or(sysclk)); // Configure HPRE. let hpre_val: f32 = (sysclk as f32 / hclk as f32).ceil(); // The real value of hpre is computed to be as near as possible to the // desired value, this leads to a quantization error let (hpre_val, hpre): (f32, u8) = match hpre_val as u32 { 0 => unreachable!(), 1 => (1.0, 0b000), 2 => (2.0, 0b1000), 3..=5 => (4.0, 0b1001), 6..=11 => (8.0, 0b1010), 12..=39 => (16.0, 0b1011), 40..=95 => (64.0, 0b1100), 96..=191 => (128.0, 0b1101), 192..=383 => (256.0, 0b1110), _ => (512.0, 0b1111), }; // update hclk with the real value hclk = (sysclk as f32 / hpre_val).floor() as u32; // PCLK1 (APB1). Must be <= 54 Mhz. By default, min(hclk, 54Mhz) is // chosen let mut pclk1: u32 = min(54_000_000, self.pclk1.unwrap_or(hclk)); // PCLK2 (APB2). Must be <= 108 Mhz. By default, min(hclk, 108Mhz) is // chosen let mut pclk2: u32 = min(108_000_000, self.pclk2.unwrap_or(hclk)); // Configure PPRE1 let mut ppre1_val: u32 = (hclk as f32 / pclk1 as f32).ceil() as u32; let ppre1: u32 = match ppre1_val { 0 => unreachable!(), 1 => { ppre1_val = 1; 0b000 } 2 => { ppre1_val = 2; 0b100 } 3..=6 => { ppre1_val = 4; 0b101 } 7..=12 => { ppre1_val = 8; 0b110 } _ => { ppre1_val = 16; 0b111 } }; // update pclk1 with the real value pclk1 = hclk / ppre1_val; // Configure PPRE2 let mut ppre2_val: u32 = (hclk as f32 / pclk2 as f32).ceil() as u32; let ppre2: u32 = match ppre2_val { 0 => unreachable!(), 1 => { ppre2_val = 1; 0b000 } 2 => { ppre2_val = 2; 0b100 } 3..=6 => { ppre2_val = 4; 0b101 } 7..=12 => { ppre2_val = 8; 0b110 } _ => { ppre2_val = 16; 0b111 } }; // update pclk2 with the real value pclk2 = hclk / ppre2_val; // Assumes TIMPRE bit of RCC_DCKCFGR1 is reset (0) let timclk1 = if ppre1_val == 1 { pclk1 } else { 2 * pclk1 }; let timclk2 = if ppre2_val == 1 { pclk2 } else { 2 * pclk2 }; // Adjust flash wait states flash.acr.write(|w| { w.latency().bits(if sysclk <= 30_000_000 { 0b0000 } else if sysclk <= 60_000_000 { 0b0001 } else if sysclk <= 90_000_000 { 0b0010 } else if sysclk <= 120_000_000 { 0b0011 } else if sysclk <= 150_000_000 { 0b0100 } else if sysclk <= 180_000_000 { 0b0101 } else if sysclk <= 210_000_000 { 0b0110 } else { 0b0111 }) }); // Select SYSCLK source if use_pll { rcc.cfgr.modify(|_, w| w.sw().pll()); while !rcc.cfgr.read().sws().is_pll() {} } else if self.hse.is_some() { rcc.cfgr.modify(|_, w| w.sw().hse()); while !rcc.cfgr.read().sws().is_hse() {} } else { rcc.cfgr.modify(|_, w| w.sw().hsi()); while !rcc.cfgr.read().sws().is_hsi() {} } // Configure HCLK, PCLK1, PCLK2 rcc.cfgr.modify(|_, w| unsafe { w.ppre1() .bits(ppre1 as u8) .ppre2() .bits(ppre2 as u8) .hpre() .bits(hpre as u8) }); // As requested by user manual we need to wait 16 ticks before the right // predivision is applied cortex_m::asm::delay(16); Clocks { hclk: Hertz(hclk), pclk1: Hertz(pclk1), pclk2: Hertz(pclk2), sysclk: Hertz(sysclk), timclk1: Hertz(timclk1), timclk2: Hertz(timclk2), } } } /// Frozen clock frequencies /// /// The existence of this value indicates that the clock configuration can no longer be changed #[derive(Clone, Copy)] pub struct Clocks { hclk: Hertz, pclk1: Hertz, pclk2: Hertz, sysclk: Hertz, timclk1: Hertz, timclk2: Hertz, } impl Clocks { /// Returns the frequency of the AHB1 pub fn hclk(&self) -> Hertz { self.hclk } /// Returns the frequency of the APB1 pub fn pclk1(&self) -> Hertz { self.pclk1 } /// Returns the frequency of the APB2 pub fn pclk2(&self) -> Hertz { self.pclk2 } /// Returns the system (core) frequency pub fn sysclk(&self) -> Hertz { self.sysclk } /// Returns the frequency for timers on APB1 pub fn timclk1(&self) -> Hertz { self.timclk1 } /// Returns the frequency for timers on APB1 pub fn timclk2(&self) -> Hertz { self.timclk2 } } pub trait GetBusFreq { fn get_frequency(clocks: &Clocks) -> Hertz; fn get_timer_frequency(clocks: &Clocks) -> Hertz { Self::get_frequency(clocks) } } impl GetBusFreq for AHB1 { fn get_frequency(clocks: &Clocks) -> Hertz { clocks.hclk } } impl GetBusFreq for AHB2 { fn get_frequency(clocks: &Clocks) -> Hertz { clocks.hclk } } impl GetBusFreq for AHB3 { fn get_frequency(clocks: &Clocks) -> Hertz { clocks.hclk } } impl GetBusFreq for APB1 { fn get_frequency(clocks: &Clocks) -> Hertz { clocks.pclk1 } fn get_timer_frequency(clocks: &Clocks) -> Hertz { clocks.timclk1() } } impl GetBusFreq for APB2 { fn get_frequency(clocks: &Clocks) -> Hertz { clocks.pclk2 } fn get_timer_frequency(clocks: &Clocks) -> Hertz { clocks.timclk2() } } pub(crate) mod sealed { /// Bus associated to peripheral pub trait RccBus { /// Bus type; type Bus; } } use sealed::RccBus; /// Enable/disable peripheral pub trait Enable: RccBus { fn enable(apb: &mut Self::Bus); fn disable(apb: &mut Self::Bus); } /// Reset peripheral pub trait Reset: RccBus { fn reset(apb: &mut Self::Bus); } macro_rules! bus { ($($PER:ident => ($apbX:ty, $peren:ident, $perrst:ident),)+) => { $( impl RccBus for crate::pac::$PER { type Bus = $apbX; } impl Enable for crate::pac::$PER { #[inline(always)] fn enable(apb: &mut Self::Bus) { apb.enr().modify(|_, w| w.$peren().set_bit()); } #[inline(always)] fn disable(apb: &mut Self::Bus) { apb.enr().modify(|_, w| w.$peren().clear_bit()); } } impl Reset for crate::pac::$PER { #[inline(always)] fn reset(apb: &mut Self::Bus) { apb.rstr().modify(|_, w| w.$perrst().set_bit()); apb.rstr().modify(|_, w| w.$perrst().clear_bit()); } } )+ } } // Peripherals respective buses // TODO: check which processor has which peripheral and add them bus! { I2C1 => (APB1, i2c1en, i2c1rst), I2C2 => (APB1, i2c2en, i2c2rst), I2C3 => (APB1, i2c3en, i2c3rst), SPI1 => (APB2, spi1en, spi1rst), SPI2 => (APB1, spi2en, spi2rst), SPI3 => (APB1, spi3en, spi3rst), USART1 => (APB2, usart1en, usart1rst), USART2 => (APB1, usart2en, uart2rst), USART3 => (APB1, usart3en, uart3rst), UART4 => (APB1, uart4en, uart4rst), UART5 => (APB1, uart5en, uart5rst), USART6 => (APB2, usart6en, usart6rst), UART7 => (APB1, uart7en, uart7rst), UART8 => (APB1, uart8en, uart8rst), WWDG => (APB1, wwdgen, wwdgrst), DMA1 => (AHB1, dma1en, dma1rst), DMA2 => (AHB1, dma2en, dma2rst), GPIOA => (AHB1, gpioaen, gpioarst), GPIOB => (AHB1, gpioben, gpiobrst), GPIOC => (AHB1, gpiocen, gpiocrst), GPIOD => (AHB1, gpioden, gpiodrst), GPIOE => (AHB1, gpioeen, gpioerst), GPIOF => (AHB1, gpiofen, gpiofrst), GPIOG => (AHB1, gpiogen, gpiogrst), GPIOH => (AHB1, gpiohen, gpiohrst), GPIOI => (AHB1, gpioien, gpioirst), TIM1 => (APB2, tim1en, tim1rst), TIM2 => (APB1, tim2en, tim2rst), TIM3 => (APB1, tim3en, tim3rst), TIM4 => (APB1, tim4en, tim4rst), TIM5 => (APB1, tim5en, tim5rst), TIM6 => (APB1, tim6en, tim6rst), TIM7 => (APB1, tim7en, tim7rst), TIM8 => (APB2, tim8en, tim8rst), TIM9 => (APB2, tim9en, tim9rst), TIM10 => (APB2, tim10en, tim10rst), TIM11 => (APB2, tim11en, tim11rst), TIM12 => (APB1, tim12en, tim12rst), TIM13 => (APB1, tim13en, tim13rst), TIM14 => (APB1, tim14en, tim14rst), } #[cfg(not(any( feature = "stm32f722", feature = "stm32f723", feature = "stm32f730", feature = "stm32f732", feature = "stm32f733" )))] bus! { I2C4 => (APB1, i2c4en, i2c4rst), GPIOJ => (AHB1, gpiojen, gpiojrst), GPIOK => (AHB1, gpioken, gpiokrst), DMA2D => (AHB1, dma2den, dma2drst), }
use core::cmp::PartialEq; use core::hash::Hash; use im::HashSet; use itertools::Itertools; use rustc_errors::MultiSpan; use rustc_span::Span; use serde::{ser::SerializeSeq, Serialize, Serializer}; use std::fmt; #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Copy)] pub struct RustspecSpan(pub Span); impl Serialize for RustspecSpan { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(format!("{:?}", self.0).as_str()) } } pub type Spanned<T> = (T, RustspecSpan); impl From<RustspecSpan> for MultiSpan { fn from(x: RustspecSpan) -> MultiSpan { x.0.into() } } impl From<Span> for RustspecSpan { fn from(x: Span) -> RustspecSpan { RustspecSpan(x) } } #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize)] pub struct LocalIdent { pub id: usize, pub name: String, pub mutable: bool, } impl fmt::Display for LocalIdent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}_{}", self.name, self.id) } } impl fmt::Debug for LocalIdent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Debug)] pub enum TopLevelIdentKind { Type, Function, Constant, Crate, EnumConstructor, } #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize)] pub struct TopLevelIdent { pub string: String, pub kind: TopLevelIdentKind, } impl fmt::Display for TopLevelIdent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.string) } } impl fmt::Debug for TopLevelIdent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize)] pub enum Ident { Unresolved(String), Local(LocalIdent), TopLevel(TopLevelIdent), } impl fmt::Display for Ident { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { Ident::Unresolved(n) => n.clone(), Ident::Local(n) => format!("{}", n), Ident::TopLevel(n) => format!("{}", n), } ) } } impl fmt::Debug for Ident { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } #[derive(Clone, Hash, PartialEq, Eq, Debug)] pub struct VarSet(pub HashSet<LocalIdent>); impl Serialize for VarSet { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(Some(self.0.len()))?; for e in &self.0 { seq.serialize_element(e)?; } seq.end() } } #[derive(Clone, Hash, PartialEq, Eq, Serialize)] pub enum Borrowing { Borrowed, Consumed, } impl fmt::Display for Borrowing { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { Borrowing::Consumed => "", Borrowing::Borrowed => "&", }, ) } } impl fmt::Debug for Borrowing { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } #[derive(Clone, Hash, PartialEq, Eq, Debug, Serialize)] pub enum ArraySize { Integer(usize), Ident(TopLevelIdent), } #[derive(Clone, Hash, PartialEq, Eq, Debug, Serialize)] pub enum Secrecy { Secret, Public, } #[derive(Clone, Hash, PartialEq, Eq, Serialize)] pub struct TypVar(pub usize); impl fmt::Display for TypVar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "T[{}]", self.0) } } impl fmt::Debug for TypVar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } #[derive(Clone, Hash, PartialEq, Eq, Serialize, Debug)] pub enum BaseTyp { Bool, UInt128, Int128, UInt64, Int64, UInt32, Int32, UInt16, Int16, UInt8, Int8, Usize, Isize, Str, Seq(Box<Spanned<BaseTyp>>), Array(Spanned<ArraySize>, Box<Spanned<BaseTyp>>), Named(Spanned<TopLevelIdent>, Option<Vec<Spanned<BaseTyp>>>), Variable(TypVar), Tuple(Vec<Spanned<BaseTyp>>), Enum( Vec<(Spanned<TopLevelIdent>, Option<Spanned<BaseTyp>>)>, Vec<TypVar>, ), // Cases, type variables NaturalInteger(Secrecy, Spanned<String>, Spanned<usize>), // secrecy, modulo value, encoding bits Placeholder, } pub const UnitTyp: BaseTyp = BaseTyp::Tuple(vec![]); impl fmt::Display for BaseTyp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { BaseTyp::Bool => write!(f, "bool"), BaseTyp::UInt128 => write!(f, "u128"), BaseTyp::Int128 => write!(f, "i128"), BaseTyp::UInt64 => write!(f, "u64"), BaseTyp::Int64 => write!(f, "i64"), BaseTyp::UInt32 => write!(f, "u32"), BaseTyp::Int32 => write!(f, "i32"), BaseTyp::UInt16 => write!(f, "u16"), BaseTyp::Int16 => write!(f, "i16"), BaseTyp::UInt8 => write!(f, "u8"), BaseTyp::Int8 => write!(f, "i8"), BaseTyp::Usize => write!(f, "usize"), BaseTyp::Isize => write!(f, "isize"), BaseTyp::Str => write!(f, "string"), BaseTyp::Array(size, mu) => { let mu = &mu.0; write!(f, "Array<{:?}, {}>", size.0, mu) } BaseTyp::Seq(mu) => { let mu = &mu.0; write!(f, "Seq<{}>", mu) } BaseTyp::Named(ident, args) => write!( f, "{}{}", ident.0, match args { None => String::new(), Some(args) => format!("<{}>", args.iter().map(|(x, _)| x).format(", ")), } ), BaseTyp::Tuple(args) => write!( f, "({})", args.iter().map(|(arg, _)| format!("{}", arg)).format(", ") ), BaseTyp::Enum(args, _) => write!( f, "[{}]", args.iter() .map(|((case, _), payload)| match payload { Some((payload, _)) => format!("{}: {}", case, payload), None => format!("{}", case), }) .format(" | ") ), BaseTyp::Variable(id) => write!(f, "T[{}]", id.0), BaseTyp::NaturalInteger(sec, modulo, bits) => { write!(f, "nat[{:?}][modulo {}][bits {}]", sec, modulo.0, bits.0) } BaseTyp::Placeholder => write!(f, "_"), } } } // impl fmt::Debug for BaseTyp { // fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // write!(f, "{}", self) // } // } pub type Typ = (Spanned<Borrowing>, Spanned<BaseTyp>); #[derive(Clone, Serialize, Debug)] pub enum Literal { Unit, Bool(bool), Int128(i128), UInt128(u128), Int64(i64), UInt64(u64), Int32(i32), UInt32(u32), Int16(i16), UInt16(u16), Int8(i8), UInt8(u8), Usize(usize), Isize(isize), UnspecifiedInt(u128), Str(String), } #[derive(Clone, Serialize, Debug)] pub enum UnOpKind { Not, Neg, } #[derive(Clone, Copy, Debug, Serialize)] pub enum BinOpKind { Add, Sub, Mul, Div, Rem, And, Or, BitXor, BitAnd, BitOr, Shl, Shr, Eq, Lt, Le, Ne, Ge, Gt, } /// Enumeration of the types allowed as question marks's monad /// representation. Named after the [Carrier][std::ops::Carrier] /// trait. #[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub enum CarrierTyp { Result(Spanned<BaseTyp>, Spanned<BaseTyp>), Option(Spanned<BaseTyp>), } /// Extracts the payload type of a carrier type, i.e., `A` is the /// payload type of `Either<A, B>`. pub fn carrier_payload(carrier: CarrierTyp) -> Spanned<BaseTyp> { match carrier { CarrierTyp::Result(ok, ..) | CarrierTyp::Option(ok, ..) => ok, } } pub fn carrier_kind(carrier: CarrierTyp) -> EarlyReturnType { match carrier { CarrierTyp::Result(..) => EarlyReturnType::Result, CarrierTyp::Option(..) => EarlyReturnType::Option, } } #[derive(Clone, Serialize, Debug, Copy)] /// Rust has three styles of structs: (a) unit structs, (b) classic, /// named structs (c) tuple structs. A field is thus either a numeric /// index or a name. However, Hacspec allows only for (a) or (c), /// hence the constructor `Named` being commented out below. pub enum Field { // Named(String), TupleIndex(isize), } #[derive(Clone, Serialize, Debug)] pub enum Expression { Unary(UnOpKind, Box<Spanned<Expression>>, Option<Typ>), Binary( Spanned<BinOpKind>, Box<Spanned<Expression>>, Box<Spanned<Expression>>, Option<Typ>, ), InlineConditional( Box<Spanned<Expression>>, Box<Spanned<Expression>>, Box<Spanned<Expression>>, ), QuestionMark( Box<Spanned<Expression>>, Fillable<CarrierTyp>, // Filled by typechecking phase ), /// One or multiple monadic bindings. For instance, `MonadicLet(M, [(x₀, e₀), …, (xₙ, eₙ)], «f x₀ … xₙ», true)` represents: /// ```haskell /// do x₀ <- e₀ /// … /// xₙ <- eₙ /// return $ f x₀ … xₙ /// ``` /// Note the boolean flag indicates whether we shall insert a `pure` monadic operation or not (that is, above, shall we have `return $ f x₀ … xₙ` or simply `f x₀ … xₙ`). /// This node appears only after the [question marks elimination][desugar::eliminate_question_marks_in_expressions] phase. MonadicLet( CarrierTyp, // Are we dealing with `Result` or `Option`? Vec<(Ident, Box<Spanned<Expression>>)>, // List of "monadic" bindings Box<Spanned<Expression>>, // body bool, // should we insert a `pure` node? (`pure` being e.g. `Ok`) ), Named(Ident), // FuncCall(prefix, name, args, arg_types) FuncCall( Option<Spanned<BaseTyp>>, Spanned<TopLevelIdent>, Vec<(Spanned<Expression>, Spanned<Borrowing>)>, Fillable<Vec<BaseTyp>>, ), MethodCall( Box<(Spanned<Expression>, Spanned<Borrowing>)>, Option<Typ>, // Type of self, to be filled by the typechecker Spanned<TopLevelIdent>, Vec<(Spanned<Expression>, Spanned<Borrowing>)>, Fillable<Vec<BaseTyp>>, ), EnumInject( BaseTyp, // Type of enum Spanned<TopLevelIdent>, // Name of case Option<Spanned<Box<Expression>>>, // Payload of case ), MatchWith( Box<Spanned<Expression>>, // Expression to match Vec<( Spanned<Pattern>, // Payload of case Spanned<Expression>, // Match arm expression )>, ), FieldAccessor(Box<Spanned<Expression>>, Box<Spanned<Field>>), Lit(Literal), ArrayIndex( Spanned<Ident>, // Array variable Box<Spanned<Expression>>, // Index Fillable<Typ>, // Type of the array ), NewArray( Option<Spanned<TopLevelIdent>>, // Name of array type, None if Seq Option<BaseTyp>, // Type of cells Vec<Spanned<Expression>>, // Contents ), Tuple(Vec<Spanned<Expression>>), IntegerCasting( Box<Spanned<Expression>>, //expression to cast Spanned<BaseTyp>, // destination type Option<BaseTyp>, // origin type ), } #[derive(Clone, Serialize, Debug)] pub enum Pattern { IdentPat(Ident, bool), WildCard, LiteralPat(Literal), Tuple(Vec<Spanned<Pattern>>), EnumCase( BaseTyp, Spanned<TopLevelIdent>, Option<Box<Spanned<Pattern>>>, ), } #[derive(Clone, Serialize, Debug, PartialEq, Eq)] pub enum EarlyReturnType { Option, Result, } #[derive(Clone, Serialize, Debug)] pub struct MutatedInfo { pub early_return_type: Fillable<CarrierTyp>, pub vars: VarSet, pub stmt: Statement, } pub type Fillable<T> = Option<T>; pub type QuestionMarkInfo = Option<(ScopeMutableVars, FunctionDependencies)>; #[derive(Clone, Serialize, Debug)] pub enum Statement { LetBinding( Spanned<Pattern>, // Let-binded pattern Option<Spanned<Typ>>, // Typ of the binded expr Spanned<Expression>, // Binded expr Fillable<CarrierTyp>, // Presence of a question mark at the end QuestionMarkInfo, ), Reassignment( Spanned<Ident>, // Variable reassigned Fillable<Spanned<Typ>>, // Type of variable reassigned Spanned<Expression>, // New value Fillable<CarrierTyp>, // Presence of a question mark at the end QuestionMarkInfo, ), Conditional( Spanned<Expression>, // Condition Spanned<Block>, // Then block Option<Spanned<Block>>, // Else block Fillable<Box<MutatedInfo>>, // Variables mutated in either branch ), ForLoop( Option<Spanned<Ident>>, // Loop variable Spanned<Expression>, // Lower bound Spanned<Expression>, // Upper bound Spanned<Block>, // Loop body ), ArrayUpdate( Spanned<Ident>, // Array variable Spanned<Expression>, // Index value Spanned<Expression>, // Cell value Fillable<CarrierTyp>,// Presence of a question mark at the end of the cell value expression QuestionMarkInfo, Fillable<Typ>, // Type of the array ), ReturnExp(Expression, Fillable<Typ>), } pub type MutableVar = (Ident, Fillable<Typ>); #[derive(Clone, Debug)] pub struct ScopeMutableVars { pub external_vars: HashSet<MutableVar>, pub local_vars: HashSet<MutableVar>, } impl Serialize for ScopeMutableVars { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // TODO: Serialize local vars let mut seq = serializer.serialize_seq(Some(self.external_vars.len()))?; for e in &self.external_vars { seq.serialize_element(e)?; } seq.end() } } impl ScopeMutableVars { pub fn new() -> Self { ScopeMutableVars { external_vars: HashSet::new(), local_vars: HashSet::new(), } } pub fn push(&mut self, value: MutableVar) { self.local_vars.insert(value); } pub fn push_external(&mut self, value: MutableVar) { self.external_vars.insert(value); } pub fn extend(&mut self, other: ScopeMutableVars) { for i in other.external_vars { self.external_vars.insert(i.clone()); self.local_vars.insert(i); } for i in other.local_vars { self.local_vars.insert(i); } } } pub type FunctionDependency = TopLevelIdent; #[derive(Clone, Debug)] pub struct FunctionDependencies(pub HashSet<FunctionDependency>); impl Serialize for FunctionDependencies { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(Some(self.0.len()))?; for e in &self.0 { seq.serialize_element(e)?; } seq.end() } } #[derive(Clone, Debug, Serialize)] pub struct Block { pub stmts: Vec<Spanned<Statement>>, pub mutated: Fillable<Box<MutatedInfo>>, pub return_typ: Fillable<Typ>, pub contains_question_mark: Fillable<bool>, pub mutable_vars: ScopeMutableVars, pub function_dependencies: FunctionDependencies, } #[derive(Clone, Debug, Serialize)] pub enum Quantified<I, T> { Unquantified(T), Forall(Vec<I>, Box<Quantified<I, T>>), Exists(Vec<I>, Box<Quantified<I, T>>), Implication(Box<Quantified<I, T>>, Box<Quantified<I, T>>), Eq(Box<Quantified<I, T>>, Box<Quantified<I, T>>), Not(Box<Quantified<I, T>>), } #[derive(Clone, Debug, Serialize)] pub struct FuncSig { pub args: Vec<(Spanned<Ident>, Spanned<Typ>)>, pub ret: Spanned<BaseTyp>, pub mutable_vars: ScopeMutableVars, pub function_dependencies: FunctionDependencies, pub ensures: Vec<Quantified<(Ident, Spanned<BaseTyp>), Spanned<Expression>>>, pub requires: Vec<Quantified<(Ident, Spanned<BaseTyp>), Spanned<Expression>>>, } #[derive(Clone, Debug, Serialize)] pub struct ExternalFuncSig { pub args: Vec<Typ>, pub ret: BaseTyp, } #[derive(Clone, Serialize, Debug)] pub enum Item { FnDecl(Spanned<TopLevelIdent>, FuncSig, Spanned<Block>), EnumDecl( Spanned<TopLevelIdent>, Vec<(Spanned<TopLevelIdent>, Option<Spanned<BaseTyp>>)>, ), ArrayDecl( Spanned<TopLevelIdent>, // Name of the array type Spanned<Expression>, // Length Spanned<BaseTyp>, // Cell type Option<Spanned<TopLevelIdent>>, // Optional type alias for indexes ), AliasDecl(Spanned<TopLevelIdent>, Spanned<BaseTyp>), ImportedCrate(Spanned<TopLevelIdent>), ConstDecl( Spanned<TopLevelIdent>, Spanned<BaseTyp>, Spanned<Expression>, ), NaturalIntegerDecl( Spanned<TopLevelIdent>, // Element type name Secrecy, // Public or secret Spanned<Expression>, // Canvas size Option<(Spanned<TopLevelIdent>, Spanned<String>)>, // Canvas array type name and modulo value ), } pub type ItemTag = String; #[derive(Clone, Hash, PartialEq, Eq, Debug)] pub struct ItemTagSet(pub HashSet<ItemTag>); impl Serialize for ItemTagSet { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(Some(self.0.len()))?; for e in &self.0 { seq.serialize_element(e)?; } seq.end() } } #[derive(Clone, Serialize, Debug)] pub struct DecoratedItem { pub item: Item, pub tags: ItemTagSet, } #[derive(Clone, Serialize, Debug)] pub struct Program { pub items: Vec<Spanned<DecoratedItem>>, } // Helpers #[allow(non_snake_case)] pub fn U8_TYP() -> TopLevelIdent { TopLevelIdent { string: "U8".into(), kind: TopLevelIdentKind::Type, } }
#[macro_export] macro_rules! bitflags { ( $vis:vis enum $name:ident: $type:ty { $( $vname:ident = $value:expr, )+ } ) => { #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Hash, PartialOrd)] $vis struct $name { bits: $type, } impl $name { $( pub const $vname: Self = Self{ bits: $value }; )+ #[inline] pub fn none() -> Self { Self { bits: 0, } } #[inline] pub fn all() -> Self { Self { bits: $($value)|+, } } #[inline] pub fn as_raw(&self) -> $type { self.bits } #[inline] pub fn contains(&self, other: Self) -> bool { (self.bits & other.bits) == other.bits } #[inline] pub fn insert(&mut self, other: Self) { self.bits |= other.bits; } #[inline] pub fn toggle(&mut self, other: Self) { self.bits ^= other.bits; } #[inline] pub fn remove(&mut self, other: Self) { self.bits &= !other.bits; } #[inline] pub fn is_empty(&self) -> bool { self.bits == 0 } } impl Default for $name { fn default() -> $name { $name { bits: 0 } } } impl core::convert::TryFrom<$type> for $name { type Error = (); #[inline] fn try_from(bits: $type) -> Result<Self, ()> { if (bits & Self::all().bits) != bits { Err(()) } else { Ok(Self { bits }) } } } impl core::fmt::Debug for $name { #[allow(unused_assignments)] fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { let mut first = true; f.write_str(stringify!($name))?; f.write_str("(")?; $( if self.contains(Self::$vname) { if !first { f.write_str(" | ")?; } f.write_str(stringify!($vname))?; first = false; } )+ f.write_str(")")?; Ok(()) } } impl core::ops::BitOr for $name { type Output = Self; #[inline] fn bitor(mut self, other: Self) -> Self { self.insert(other); return self; } } impl core::ops::BitOrAssign for $name { #[inline] fn bitor_assign(&mut self, other: Self) { self.insert(other); } } impl core::ops::Sub for $name { type Output = Self; #[inline] fn sub(mut self, other: Self) -> Self { self.remove(other); return self; } } impl core::ops::SubAssign for $name { #[inline] fn sub_assign(&mut self, other: Self) { self.remove(other); } } impl core::ops::BitAnd for $name { type Output = Self; #[inline] fn bitand(mut self, other: Self) -> Self { self.bits &= other.bits; return self; } } impl core::ops::BitAndAssign for $name { #[inline] fn bitand_assign(&mut self, other: Self) { self.bits &= other.bits; } } impl core::ops::BitXor for $name { type Output = Self; #[inline] fn bitxor(mut self, other: Self) -> Self { self.toggle(other); return self; } } impl core::ops::BitXorAssign for $name { #[inline] fn bitxor_assign(&mut self, other: Self) { self.toggle(other); } } } } #[cfg(test)] mod tests { use core::convert::TryInto; bitflags! { enum MyFlags: u32 { A = 1, B = 2, C = 4, } } #[test] fn try_from() { assert_eq!(0u32.try_into(), Ok(MyFlags::none())); assert_eq!(1u32.try_into(), Ok(MyFlags::A)); assert_eq!(2u32.try_into(), Ok(MyFlags::B)); assert_eq!(5u32.try_into(), Ok(MyFlags::A | MyFlags::C)); assert_eq!(7u32.try_into(), Ok(MyFlags::all())); assert_eq!(8u32.try_into(), Result::<MyFlags, ()>::Err(())); } #[test] fn bitflags() { assert_eq!(MyFlags::none().as_raw(), 0); assert_eq!(MyFlags::all().as_raw(), 7); assert!(MyFlags::all().contains(MyFlags::A)); assert!(MyFlags::all().contains(MyFlags::B)); assert!(MyFlags::all().contains(MyFlags::C)); assert!(!MyFlags::none().contains(MyFlags::A)); assert!(!MyFlags::none().contains(MyFlags::B)); assert!(!MyFlags::none().contains(MyFlags::C)); assert!(MyFlags::A.contains(MyFlags::A)); assert!(!MyFlags::A.contains(MyFlags::B)); assert!(!MyFlags::B.contains(MyFlags::A)); assert!(MyFlags::B.contains(MyFlags::B)); assert!(!MyFlags::A.is_empty()); assert!(MyFlags::none().is_empty()); } #[test] fn remove() { let mut x = MyFlags::all(); assert!(x.contains(MyFlags::A)); assert!(x.contains(MyFlags::B)); assert!(x.contains(MyFlags::C)); x.remove(MyFlags::B); assert!(x.contains(MyFlags::A)); assert!(!x.contains(MyFlags::B)); assert!(x.contains(MyFlags::C)); x.remove(MyFlags::A); assert!(!x.contains(MyFlags::A)); assert!(!x.contains(MyFlags::B)); assert!(x.contains(MyFlags::C)); x.remove(MyFlags::all()); assert!(!x.contains(MyFlags::A)); assert!(!x.contains(MyFlags::B)); assert!(!x.contains(MyFlags::C)); assert_eq!(x, MyFlags::none()); } #[test] fn insert() { let mut x = MyFlags::A; assert!(x.contains(MyFlags::A)); assert!(!x.contains(MyFlags::B)); assert!(!x.contains(MyFlags::C)); x.insert(MyFlags::B); assert!(x.contains(MyFlags::A)); assert!(x.contains(MyFlags::B)); assert!(!x.contains(MyFlags::C)); } #[test] fn toggle() { let mut x = MyFlags::A; assert!(x.contains(MyFlags::A)); assert!(!x.contains(MyFlags::B)); assert!(!x.contains(MyFlags::C)); x.toggle(MyFlags::B); assert!(x.contains(MyFlags::A)); assert!(x.contains(MyFlags::B)); assert!(!x.contains(MyFlags::C)); x.toggle(MyFlags::A); assert!(!x.contains(MyFlags::A)); assert!(x.contains(MyFlags::B)); assert!(!x.contains(MyFlags::C)); } }
#![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 Aggregations { #[serde(flatten)] pub resource: Resource, #[serde(flatten)] pub aggregations_kind: AggregationsKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AggregationsKind { pub kind: aggregations_kind::Kind, } pub mod aggregations_kind { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { CasesAggregation, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MlBehaviorAnalyticsAlertRule { #[serde(flatten)] pub alert_rule: AlertRule, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MlBehaviorAnalyticsAlertRuleProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MlBehaviorAnalyticsAlertRuleProperties { #[serde(rename = "alertRuleTemplateName")] pub alert_rule_template_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, pub enabled: bool, #[serde(rename = "lastModifiedUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<AlertSeverity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MlBehaviorAnalyticsAlertRuleTemplate { #[serde(flatten)] pub alert_rule_template: AlertRuleTemplate, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ml_behavior_analytics_alert_rule_template::Properties>, } pub mod ml_behavior_analytics_alert_rule_template { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(flatten)] pub alert_rule_template_properties_base: AlertRuleTemplatePropertiesBase, pub severity: AlertSeverity, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AadDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AadDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AadDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(flatten)] pub data_connector_with_alerts_properties: DataConnectorWithAlertsProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AatpDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AatpDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AatpDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(flatten)] pub data_connector_with_alerts_properties: DataConnectorWithAlertsProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MstiDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MstiDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MstiDataConnectorDataTypes { #[serde(rename = "bingSafetyPhishingURL")] pub bing_safety_phishing_url: msti_data_connector_data_types::BingSafetyPhishingUrl, #[serde(rename = "microsoftEmergingThreatFeed")] pub microsoft_emerging_threat_feed: msti_data_connector_data_types::MicrosoftEmergingThreatFeed, } pub mod msti_data_connector_data_types { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BingSafetyPhishingUrl { #[serde(flatten)] pub data_connector_data_type_common: DataConnectorDataTypeCommon, #[serde(rename = "lookbackPeriod")] pub lookback_period: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MicrosoftEmergingThreatFeed { #[serde(flatten)] pub data_connector_data_type_common: DataConnectorDataTypeCommon, #[serde(rename = "lookbackPeriod")] pub lookback_period: String, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MstiDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(rename = "dataTypes")] pub data_types: MstiDataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MtpDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MtpDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MtpDataConnectorDataTypes { pub incidents: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MtpDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(rename = "dataTypes")] pub data_types: MtpDataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AscDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AscDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AscDataConnectorProperties { #[serde(flatten)] pub data_connector_with_alerts_properties: DataConnectorWithAlertsProperties, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AccountEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "aadTenantId", default, skip_serializing_if = "Option::is_none")] pub aad_tenant_id: Option<String>, #[serde(rename = "aadUserId", default, skip_serializing_if = "Option::is_none")] pub aad_user_id: Option<String>, #[serde(rename = "accountName", default, skip_serializing_if = "Option::is_none")] pub account_name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "hostEntityId", default, skip_serializing_if = "Option::is_none")] pub host_entity_id: Option<String>, #[serde(rename = "isDomainJoined", default, skip_serializing_if = "Option::is_none")] pub is_domain_joined: Option<bool>, #[serde(rename = "ntDomain", default, skip_serializing_if = "Option::is_none")] pub nt_domain: Option<String>, #[serde(rename = "objectGuid", default, skip_serializing_if = "Option::is_none")] pub object_guid: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub puid: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sid: Option<String>, #[serde(rename = "upnSuffix", default, skip_serializing_if = "Option::is_none")] pub upn_suffix: Option<String>, #[serde(rename = "dnsDomain", default, skip_serializing_if = "Option::is_none")] pub dns_domain: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionRequest { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ActionRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionPropertiesBase { #[serde(rename = "logicAppResourceId")] pub logic_app_resource_id: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionRequestProperties { #[serde(flatten)] pub action_properties_base: ActionPropertiesBase, #[serde(rename = "triggerUri")] pub trigger_uri: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionResponse { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ActionResponseProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionResponseProperties { #[serde(flatten)] pub action_properties_base: ActionPropertiesBase, #[serde(rename = "workflowId", default, skip_serializing_if = "Option::is_none")] pub workflow_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionsList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<ActionResponse>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRule { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(flatten)] pub alert_rule_kind: AlertRuleKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRuleKind { pub kind: alert_rule_kind::Kind, } pub mod alert_rule_kind { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Scheduled, MicrosoftSecurityIncidentCreation, Fusion, #[serde(rename = "MLBehaviorAnalytics")] MlBehaviorAnalytics, ThreatIntelligence, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRuleTemplate { #[serde(flatten)] pub resource: Resource, #[serde(flatten)] pub alert_rule_kind: AlertRuleKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRuleTemplateDataSource { #[serde(rename = "connectorId", default, skip_serializing_if = "Option::is_none")] pub connector_id: Option<String>, #[serde(rename = "dataTypes", default, skip_serializing_if = "Vec::is_empty")] pub data_types: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRuleTemplatePropertiesBase { #[serde(rename = "alertRulesCreatedByTemplateCount", default, skip_serializing_if = "Option::is_none")] pub alert_rules_created_by_template_count: Option<i64>, #[serde(rename = "lastUpdatedDateUTC", default, skip_serializing_if = "Option::is_none")] pub last_updated_date_utc: Option<String>, #[serde(rename = "createdDateUTC", default, skip_serializing_if = "Option::is_none")] pub created_date_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "requiredDataConnectors", default, skip_serializing_if = "Vec::is_empty")] pub required_data_connectors: Vec<AlertRuleTemplateDataSource>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<alert_rule_template_properties_base::Status>, } pub mod alert_rule_template_properties_base { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Installed, Available, NotAvailable, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRuleTemplatesList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<AlertRuleTemplate>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AlertRuleTriggerOperator { GreaterThan, LessThan, Equal, NotEqual, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertRulesList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<AlertRule>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AlertSeverity { High, Medium, Low, Informational, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AlertsDataTypeOfDataConnector { pub alerts: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AttackTactic { InitialAccess, Execution, Persistence, PrivilegeEscalation, DefenseEvasion, CredentialAccess, Discovery, LateralMovement, Collection, Exfiltration, CommandAndControl, Impact, PreAttack, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsCloudTrailDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AwsCloudTrailDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsCloudTrailDataConnectorDataTypes { pub logs: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsCloudTrailDataConnectorProperties { #[serde(rename = "awsRoleArn", default, skip_serializing_if = "Option::is_none")] pub aws_role_arn: Option<String>, #[serde(rename = "dataTypes")] pub data_types: AwsCloudTrailDataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureResourceEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AzureResourceEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureResourceEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CasesAggregation { #[serde(flatten)] pub aggregations: Aggregations, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CasesAggregationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CasesAggregationBySeverityProperties { #[serde(rename = "totalCriticalSeverity", default, skip_serializing_if = "Option::is_none")] pub total_critical_severity: Option<i64>, #[serde(rename = "totalHighSeverity", default, skip_serializing_if = "Option::is_none")] pub total_high_severity: Option<i64>, #[serde(rename = "totalInformationalSeverity", default, skip_serializing_if = "Option::is_none")] pub total_informational_severity: Option<i64>, #[serde(rename = "totalLowSeverity", default, skip_serializing_if = "Option::is_none")] pub total_low_severity: Option<i64>, #[serde(rename = "totalMediumSeverity", default, skip_serializing_if = "Option::is_none")] pub total_medium_severity: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CasesAggregationByStatusProperties { #[serde(rename = "totalDismissedStatus", default, skip_serializing_if = "Option::is_none")] pub total_dismissed_status: Option<i64>, #[serde(rename = "totalInProgressStatus", default, skip_serializing_if = "Option::is_none")] pub total_in_progress_status: Option<i64>, #[serde(rename = "totalNewStatus", default, skip_serializing_if = "Option::is_none")] pub total_new_status: Option<i64>, #[serde(rename = "totalResolvedStatus", default, skip_serializing_if = "Option::is_none")] pub total_resolved_status: Option<i64>, #[serde(rename = "totalFalsePositiveStatus", default, skip_serializing_if = "Option::is_none")] pub total_false_positive_status: Option<i32>, #[serde(rename = "totalTruePositiveStatus", default, skip_serializing_if = "Option::is_none")] pub total_true_positive_status: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CasesAggregationProperties { #[serde(rename = "aggregationBySeverity", default, skip_serializing_if = "Option::is_none")] pub aggregation_by_severity: Option<CasesAggregationBySeverityProperties>, #[serde(rename = "aggregationByStatus", default, skip_serializing_if = "Option::is_none")] pub aggregation_by_status: Option<CasesAggregationByStatusProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClientInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub email: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")] pub object_id: Option<String>, #[serde(rename = "userPrincipalName", default, skip_serializing_if = "Option::is_none")] pub user_principal_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudApplicationEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CloudApplicationEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudApplicationEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "appId", default, skip_serializing_if = "Option::is_none")] pub app_id: Option<i64>, #[serde(rename = "appName", default, skip_serializing_if = "Option::is_none")] pub app_name: Option<String>, #[serde(rename = "instanceName", default, skip_serializing_if = "Option::is_none")] pub instance_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudErrorBody { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnector { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(flatten)] pub data_connector_kind: DataConnectorKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorDataTypeCommon { pub state: data_connector_data_type_common::State, } pub mod data_connector_data_type_common { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorKind { pub kind: data_connector_kind::Kind, } pub mod data_connector_kind { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { AzureActiveDirectory, AzureSecurityCenter, MicrosoftCloudAppSecurity, ThreatIntelligence, ThreatIntelligenceTaxii, Office365, #[serde(rename = "OfficeATP")] OfficeAtp, AmazonWebServicesCloudTrail, AzureAdvancedThreatProtection, MicrosoftDefenderAdvancedThreatProtection, Dynamics365, MicrosoftThreatProtection, MicrosoftThreatIntelligence, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<DataConnector>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorTenantId { #[serde(rename = "tenantId")] pub tenant_id: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorWithAlertsProperties { #[serde(rename = "dataTypes", default, skip_serializing_if = "Option::is_none")] pub data_types: Option<AlertsDataTypeOfDataConnector>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DnsEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<DnsEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DnsEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "dnsServerIpEntityId", default, skip_serializing_if = "Option::is_none")] pub dns_server_ip_entity_id: Option<String>, #[serde(rename = "domainName", default, skip_serializing_if = "Option::is_none")] pub domain_name: Option<String>, #[serde(rename = "hostIpAddressEntityId", default, skip_serializing_if = "Option::is_none")] pub host_ip_address_entity_id: Option<String>, #[serde(rename = "ipAddressEntityIds", default, skip_serializing_if = "Vec::is_empty")] pub ip_address_entity_ids: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dynamics365DataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<Dynamics365DataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dynamics365DataConnectorDataTypes { #[serde(rename = "dynamics365CdsActivities")] pub dynamics365_cds_activities: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dynamics365DataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(rename = "dataTypes")] pub data_types: Dynamics365DataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Entity { #[serde(flatten)] pub resource: Resource, #[serde(flatten)] pub entity_kind: EntityKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityCommonProperties { #[serde(rename = "additionalData", default, skip_serializing_if = "Option::is_none")] pub additional_data: Option<serde_json::Value>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EntityInnerKind { Account, Host, File, AzureResource, CloudApplication, DnsResolution, FileHash, Ip, Malware, Process, RegistryKey, RegistryValue, SecurityGroup, Url, IoTDevice, SecurityAlert, Bookmark, Mailbox, MailCluster, MailMessage, SubmissionMail, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EntityInnerType { Account, Host, File, AzureResource, CloudApplication, #[serde(rename = "DNS")] Dns, FileHash, #[serde(rename = "IP")] Ip, Malware, Process, RegistryKey, RegistryValue, SecurityGroup, #[serde(rename = "URL")] Url, IoTDevice, SecurityAlert, HuntingBookmark, MailCluster, MailMessage, Mailbox, SubmissionMail, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityKind { pub kind: EntityInnerKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityQueryKind { pub kind: entity_query_kind::Kind, } pub mod entity_query_kind { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Expansion, Insight, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityQuery { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(flatten)] pub entity_query_kind: EntityQueryKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExpansionEntityQuery { #[serde(flatten)] pub entity_query: EntityQuery, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ExpansionEntityQueriesProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityQueryList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<EntityQuery>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExpansionResultAggregation { #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, pub count: i64, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "entityKind")] pub entity_kind: EntityInnerKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExpansionResultsMetadata { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub aggregations: Vec<ExpansionResultAggregation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExpansionEntityQueriesProperties { #[serde(rename = "dataSources", default, skip_serializing_if = "Vec::is_empty")] pub data_sources: Vec<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "inputEntityType", default, skip_serializing_if = "Option::is_none")] pub input_entity_type: Option<EntityInnerType>, #[serde(rename = "inputFields", default, skip_serializing_if = "Vec::is_empty")] pub input_fields: Vec<String>, #[serde(rename = "outputEntityTypes", default, skip_serializing_if = "Vec::is_empty")] pub output_entity_types: Vec<EntityInnerType>, #[serde(rename = "queryTemplate", default, skip_serializing_if = "Option::is_none")] pub query_template: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedEntity { #[serde(rename = "targetEntityId", default, skip_serializing_if = "Option::is_none")] pub target_entity_id: Option<String>, #[serde(rename = "additionalData", default, skip_serializing_if = "Option::is_none")] pub additional_data: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<FileEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub directory: Option<String>, #[serde(rename = "fileHashEntityIds", default, skip_serializing_if = "Vec::is_empty")] pub file_hash_entity_ids: Vec<String>, #[serde(rename = "fileName", default, skip_serializing_if = "Option::is_none")] pub file_name: Option<String>, #[serde(rename = "hostEntityId", default, skip_serializing_if = "Option::is_none")] pub host_entity_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileHashEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<FileHashEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileHashEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub algorithm: Option<file_hash_entity_properties::Algorithm>, #[serde(rename = "hashValue", default, skip_serializing_if = "Option::is_none")] pub hash_value: Option<String>, } pub mod file_hash_entity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Algorithm { Unknown, #[serde(rename = "MD5")] Md5, #[serde(rename = "SHA1")] Sha1, #[serde(rename = "SHA256")] Sha256, #[serde(rename = "SHA256AC")] Sha256ac, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FusionAlertRule { #[serde(flatten)] pub alert_rule: AlertRule, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<FusionAlertRuleProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FusionAlertRuleProperties { #[serde(rename = "alertRuleTemplateName")] pub alert_rule_template_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, pub enabled: bool, #[serde(rename = "lastModifiedUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<AlertSeverity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FusionAlertRuleTemplate { #[serde(flatten)] pub alert_rule_template: AlertRuleTemplate, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<fusion_alert_rule_template::Properties>, } pub mod fusion_alert_rule_template { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(flatten)] pub alert_rule_template_properties_base: AlertRuleTemplatePropertiesBase, pub severity: AlertSeverity, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceAlertRule { #[serde(flatten)] pub alert_rule: AlertRule, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ThreatIntelligenceAlertRuleProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceAlertRuleProperties { #[serde(rename = "alertRuleTemplateName")] pub alert_rule_template_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, pub enabled: bool, #[serde(rename = "lastModifiedUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<AlertSeverity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceAlertRuleTemplate { #[serde(flatten)] pub alert_rule_template: AlertRuleTemplate, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<threat_intelligence_alert_rule_template::Properties>, } pub mod threat_intelligence_alert_rule_template { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(flatten)] pub alert_rule_template_properties_base: AlertRuleTemplatePropertiesBase, pub severity: AlertSeverity, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GeoLocation { #[serde(default, skip_serializing_if = "Option::is_none")] pub asn: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub city: Option<String>, #[serde(rename = "countryCode", default, skip_serializing_if = "Option::is_none")] pub country_code: Option<String>, #[serde(rename = "countryName", default, skip_serializing_if = "Option::is_none")] pub country_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub latitude: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub longitude: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<HostEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "azureID", default, skip_serializing_if = "Option::is_none")] pub azure_id: Option<String>, #[serde(rename = "dnsDomain", default, skip_serializing_if = "Option::is_none")] pub dns_domain: Option<String>, #[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")] pub host_name: Option<String>, #[serde(rename = "isDomainJoined", default, skip_serializing_if = "Option::is_none")] pub is_domain_joined: Option<bool>, #[serde(rename = "netBiosName", default, skip_serializing_if = "Option::is_none")] pub net_bios_name: Option<String>, #[serde(rename = "ntDomain", default, skip_serializing_if = "Option::is_none")] pub nt_domain: Option<String>, #[serde(rename = "omsAgentID", default, skip_serializing_if = "Option::is_none")] pub oms_agent_id: Option<String>, #[serde(rename = "osFamily", default, skip_serializing_if = "Option::is_none")] pub os_family: Option<host_entity_properties::OsFamily>, #[serde(rename = "osVersion", default, skip_serializing_if = "Option::is_none")] pub os_version: Option<String>, } pub mod host_entity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OsFamily { Linux, Windows, Android, #[serde(rename = "IOS")] Ios, Unknown, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Incident { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IncidentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HuntingBookmark { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<HuntingBookmarkProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HuntingBookmarkProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<UserInfo>, #[serde(rename = "displayName")] pub display_name: String, #[serde(rename = "eventTime", default, skip_serializing_if = "Option::is_none")] pub event_time: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<Label>, #[serde(default, skip_serializing_if = "Option::is_none")] pub notes: Option<String>, pub query: String, #[serde(rename = "queryResult", default, skip_serializing_if = "Option::is_none")] pub query_result: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(rename = "updatedBy", default, skip_serializing_if = "Option::is_none")] pub updated_by: Option<UserInfo>, #[serde(rename = "incidentInfo", default, skip_serializing_if = "Option::is_none")] pub incident_info: Option<IncidentInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentAdditionalData { #[serde(rename = "alertsCount", default, skip_serializing_if = "Option::is_none")] pub alerts_count: Option<i64>, #[serde(rename = "bookmarksCount", default, skip_serializing_if = "Option::is_none")] pub bookmarks_count: Option<i64>, #[serde(rename = "commentsCount", default, skip_serializing_if = "Option::is_none")] pub comments_count: Option<i64>, #[serde(rename = "alertProductNames", default, skip_serializing_if = "Vec::is_empty")] pub alert_product_names: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentAlertList { pub value: Vec<SecurityAlert>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentBookmarkList { pub value: Vec<HuntingBookmark>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentComment { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IncidentCommentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentCommentList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<IncidentComment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentCommentProperties { #[serde(rename = "createdTimeUtc", default, skip_serializing_if = "Option::is_none")] pub created_time_utc: Option<String>, #[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_time_utc: Option<String>, pub message: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub author: Option<ClientInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentEntitiesResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entities: Vec<Entity>, #[serde(rename = "metaData", default, skip_serializing_if = "Vec::is_empty")] pub meta_data: Vec<IncidentEntitiesResultsMetadata>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentEntitiesResultsMetadata { pub count: i32, #[serde(rename = "entityKind")] pub entity_kind: EntityInnerKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentLabel { #[serde(rename = "labelName")] pub label_name: String, #[serde(rename = "labelType", default, skip_serializing_if = "Option::is_none")] pub label_type: Option<incident_label::LabelType>, } pub mod incident_label { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LabelType { User, System, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Incident>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentOwnerInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub email: Option<String>, #[serde(rename = "assignedTo", default, skip_serializing_if = "Option::is_none")] pub assigned_to: Option<String>, #[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")] pub object_id: Option<String>, #[serde(rename = "userPrincipalName", default, skip_serializing_if = "Option::is_none")] pub user_principal_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IncidentClassification { Undetermined, TruePositive, BenignPositive, FalsePositive, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IncidentClassificationReason { SuspiciousActivity, SuspiciousButExpected, IncorrectAlertLogic, InaccurateData, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IncidentSeverity { High, Medium, Low, Informational, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IncidentStatus { New, Active, Closed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentProperties { #[serde(rename = "additionalData", default, skip_serializing_if = "Option::is_none")] pub additional_data: Option<IncidentAdditionalData>, #[serde(default, skip_serializing_if = "Option::is_none")] pub classification: Option<IncidentClassification>, #[serde(rename = "classificationComment", default, skip_serializing_if = "Option::is_none")] pub classification_comment: Option<String>, #[serde(rename = "classificationReason", default, skip_serializing_if = "Option::is_none")] pub classification_reason: Option<IncidentClassificationReason>, #[serde(rename = "createdTimeUtc", default, skip_serializing_if = "Option::is_none")] pub created_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "firstActivityTimeUtc", default, skip_serializing_if = "Option::is_none")] pub first_activity_time_utc: Option<String>, #[serde(rename = "incidentUrl", default, skip_serializing_if = "Option::is_none")] pub incident_url: Option<String>, #[serde(rename = "incidentNumber", default, skip_serializing_if = "Option::is_none")] pub incident_number: Option<i64>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<IncidentLabel>, #[serde(rename = "providerName", default, skip_serializing_if = "Option::is_none")] pub provider_name: Option<String>, #[serde(rename = "providerIncidentId", default, skip_serializing_if = "Option::is_none")] pub provider_incident_id: Option<String>, #[serde(rename = "lastActivityTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_activity_time_utc: Option<String>, #[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub owner: Option<IncidentOwnerInfo>, #[serde(rename = "relatedAnalyticRuleIds", default, skip_serializing_if = "Vec::is_empty")] pub related_analytic_rule_ids: Vec<String>, pub severity: IncidentSeverity, pub status: IncidentStatus, pub title: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IpEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub address: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<GeoLocation>, #[serde(rename = "threatIntelligence", default, skip_serializing_if = "Vec::is_empty")] pub threat_intelligence: Vec<ThreatIntelligence>, } pub type Label = String; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MailboxEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MailboxEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MailboxEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "mailboxPrimaryAddress", default, skip_serializing_if = "Option::is_none")] pub mailbox_primary_address: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub upn: Option<String>, #[serde(rename = "externalDirectoryObjectId", default, skip_serializing_if = "Option::is_none")] pub external_directory_object_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MailClusterEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MailClusterEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MailClusterEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "networkMessageIds", default, skip_serializing_if = "Vec::is_empty")] pub network_message_ids: Vec<String>, #[serde(rename = "countByDeliveryStatus", default, skip_serializing_if = "Option::is_none")] pub count_by_delivery_status: Option<serde_json::Value>, #[serde(rename = "countByThreatType", default, skip_serializing_if = "Option::is_none")] pub count_by_threat_type: Option<serde_json::Value>, #[serde(rename = "countByProtectionStatus", default, skip_serializing_if = "Option::is_none")] pub count_by_protection_status: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub threats: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub query: Option<String>, #[serde(rename = "queryTime", default, skip_serializing_if = "Option::is_none")] pub query_time: Option<String>, #[serde(rename = "mailCount", default, skip_serializing_if = "Option::is_none")] pub mail_count: Option<i32>, #[serde(rename = "isVolumeAnomaly", default, skip_serializing_if = "Option::is_none")] pub is_volume_anomaly: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<String>, #[serde(rename = "clusterSourceIdentifier", default, skip_serializing_if = "Option::is_none")] pub cluster_source_identifier: Option<String>, #[serde(rename = "clusterSourceType", default, skip_serializing_if = "Option::is_none")] pub cluster_source_type: Option<String>, #[serde(rename = "clusterQueryStartTime", default, skip_serializing_if = "Option::is_none")] pub cluster_query_start_time: Option<String>, #[serde(rename = "clusterQueryEndTime", default, skip_serializing_if = "Option::is_none")] pub cluster_query_end_time: Option<String>, #[serde(rename = "clusterGroup", default, skip_serializing_if = "Option::is_none")] pub cluster_group: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MailMessageEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MailMessageEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MailMessageEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "fileEntityIds", default, skip_serializing_if = "Vec::is_empty")] pub file_entity_ids: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub recipient: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub urls: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub threats: Vec<String>, #[serde(rename = "p1Sender", default, skip_serializing_if = "Option::is_none")] pub p1_sender: Option<String>, #[serde(rename = "p1SenderDisplayName", default, skip_serializing_if = "Option::is_none")] pub p1_sender_display_name: Option<String>, #[serde(rename = "p1SenderDomain", default, skip_serializing_if = "Option::is_none")] pub p1_sender_domain: Option<String>, #[serde(rename = "senderIP", default, skip_serializing_if = "Option::is_none")] pub sender_ip: Option<String>, #[serde(rename = "p2Sender", default, skip_serializing_if = "Option::is_none")] pub p2_sender: Option<String>, #[serde(rename = "p2SenderDisplayName", default, skip_serializing_if = "Option::is_none")] pub p2_sender_display_name: Option<String>, #[serde(rename = "p2SenderDomain", default, skip_serializing_if = "Option::is_none")] pub p2_sender_domain: Option<String>, #[serde(rename = "receiveDate", default, skip_serializing_if = "Option::is_none")] pub receive_date: Option<String>, #[serde(rename = "networkMessageId", default, skip_serializing_if = "Option::is_none")] pub network_message_id: Option<String>, #[serde(rename = "internetMessageId", default, skip_serializing_if = "Option::is_none")] pub internet_message_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subject: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option<String>, #[serde(rename = "threatDetectionMethods", default, skip_serializing_if = "Vec::is_empty")] pub threat_detection_methods: Vec<String>, #[serde(rename = "bodyFingerprintBin1", default, skip_serializing_if = "Option::is_none")] pub body_fingerprint_bin1: Option<i32>, #[serde(rename = "bodyFingerprintBin2", default, skip_serializing_if = "Option::is_none")] pub body_fingerprint_bin2: Option<i32>, #[serde(rename = "bodyFingerprintBin3", default, skip_serializing_if = "Option::is_none")] pub body_fingerprint_bin3: Option<i32>, #[serde(rename = "bodyFingerprintBin4", default, skip_serializing_if = "Option::is_none")] pub body_fingerprint_bin4: Option<i32>, #[serde(rename = "bodyFingerprintBin5", default, skip_serializing_if = "Option::is_none")] pub body_fingerprint_bin5: Option<i32>, #[serde(rename = "antispamDirection", default, skip_serializing_if = "Option::is_none")] pub antispam_direction: Option<mail_message_entity_properties::AntispamDirection>, #[serde(rename = "deliveryAction", default, skip_serializing_if = "Option::is_none")] pub delivery_action: Option<mail_message_entity_properties::DeliveryAction>, #[serde(rename = "deliveryLocation", default, skip_serializing_if = "Option::is_none")] pub delivery_location: Option<mail_message_entity_properties::DeliveryLocation>, } pub mod mail_message_entity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AntispamDirection { Unknown, Inbound, Outbound, Intraorg, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DeliveryAction { Unknown, DeliveredAsSpam, Delivered, Blocked, Replaced, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DeliveryLocation { Unknown, Inbox, JunkFolder, DeletedFolder, Quarantine, External, Failed, Dropped, Forwarded, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubmissionMailEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SubmissionMailEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubmissionMailEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "networkMessageId", default, skip_serializing_if = "Option::is_none")] pub network_message_id: Option<String>, #[serde(rename = "submissionId", default, skip_serializing_if = "Option::is_none")] pub submission_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub submitter: Option<String>, #[serde(rename = "submissionDate", default, skip_serializing_if = "Option::is_none")] pub submission_date: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub recipient: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sender: Option<String>, #[serde(rename = "senderIp", default, skip_serializing_if = "Option::is_none")] pub sender_ip: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subject: Option<String>, #[serde(rename = "reportType", default, skip_serializing_if = "Option::is_none")] pub report_type: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct McasDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<McasDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct McasDataConnectorDataTypes { #[serde(flatten)] pub alerts_data_type_of_data_connector: AlertsDataTypeOfDataConnector, #[serde(rename = "discoveryLogs", default, skip_serializing_if = "Option::is_none")] pub discovery_logs: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct McasDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(rename = "dataTypes")] pub data_types: McasDataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MdatpDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MdatpDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MdatpDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(flatten)] pub data_connector_with_alerts_properties: DataConnectorWithAlertsProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MalwareEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MalwareEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MalwareEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(rename = "fileEntityIds", default, skip_serializing_if = "Vec::is_empty")] pub file_entity_ids: Vec<String>, #[serde(rename = "malwareName", default, skip_serializing_if = "Option::is_none")] pub malware_name: Option<String>, #[serde(rename = "processEntityIds", default, skip_serializing_if = "Vec::is_empty")] pub process_entity_ids: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MicrosoftSecurityIncidentCreationAlertRule { #[serde(flatten)] pub alert_rule: AlertRule, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MicrosoftSecurityIncidentCreationAlertRuleProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MicrosoftSecurityIncidentCreationAlertRuleCommonProperties { #[serde(rename = "displayNamesFilter", default, skip_serializing_if = "Vec::is_empty")] pub display_names_filter: Vec<String>, #[serde(rename = "displayNamesExcludeFilter", default, skip_serializing_if = "Vec::is_empty")] pub display_names_exclude_filter: Vec<String>, #[serde(rename = "productFilter")] pub product_filter: microsoft_security_incident_creation_alert_rule_common_properties::ProductFilter, #[serde(rename = "severitiesFilter", default, skip_serializing_if = "Vec::is_empty")] pub severities_filter: Vec<AlertSeverity>, } pub mod microsoft_security_incident_creation_alert_rule_common_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProductFilter { #[serde(rename = "Microsoft Cloud App Security")] MicrosoftCloudAppSecurity, #[serde(rename = "Azure Security Center")] AzureSecurityCenter, #[serde(rename = "Azure Advanced Threat Protection")] AzureAdvancedThreatProtection, #[serde(rename = "Azure Active Directory Identity Protection")] AzureActiveDirectoryIdentityProtection, #[serde(rename = "Azure Security Center for IoT")] AzureSecurityCenterForIoT, #[serde(rename = "Office 365 Advanced Threat Protection")] Office365AdvancedThreatProtection, #[serde(rename = "Microsoft Defender Advanced Threat Protection")] MicrosoftDefenderAdvancedThreatProtection, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MicrosoftSecurityIncidentCreationAlertRuleProperties { #[serde(flatten)] pub microsoft_security_incident_creation_alert_rule_common_properties: MicrosoftSecurityIncidentCreationAlertRuleCommonProperties, #[serde(rename = "alertRuleTemplateName", default, skip_serializing_if = "Option::is_none")] pub alert_rule_template_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName")] pub display_name: String, pub enabled: bool, #[serde(rename = "lastModifiedUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_utc: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MicrosoftSecurityIncidentCreationAlertRuleTemplate { #[serde(flatten)] pub alert_rule_template: AlertRuleTemplate, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeAtpDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OfficeAtpDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeAtpDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(flatten)] pub data_connector_with_alerts_properties: DataConnectorWithAlertsProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OfficeDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeDataConnectorDataTypes { pub exchange: serde_json::Value, #[serde(rename = "sharePoint")] pub share_point: serde_json::Value, pub teams: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(rename = "dataTypes")] pub data_types: OfficeDataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationsList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Operation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ProcessEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "accountEntityId", default, skip_serializing_if = "Option::is_none")] pub account_entity_id: Option<String>, #[serde(rename = "commandLine", default, skip_serializing_if = "Option::is_none")] pub command_line: Option<String>, #[serde(rename = "creationTimeUtc", default, skip_serializing_if = "Option::is_none")] pub creation_time_utc: Option<String>, #[serde(rename = "elevationToken", default, skip_serializing_if = "Option::is_none")] pub elevation_token: Option<process_entity_properties::ElevationToken>, #[serde(rename = "hostEntityId", default, skip_serializing_if = "Option::is_none")] pub host_entity_id: Option<String>, #[serde(rename = "hostLogonSessionEntityId", default, skip_serializing_if = "Option::is_none")] pub host_logon_session_entity_id: Option<String>, #[serde(rename = "imageFileEntityId", default, skip_serializing_if = "Option::is_none")] pub image_file_entity_id: Option<String>, #[serde(rename = "parentProcessEntityId", default, skip_serializing_if = "Option::is_none")] pub parent_process_entity_id: Option<String>, #[serde(rename = "processId", default, skip_serializing_if = "Option::is_none")] pub process_id: Option<String>, } pub mod process_entity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ElevationToken { Default, Full, Limited, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryKeyEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistryKeyEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryKeyEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub hive: Option<registry_key_entity_properties::Hive>, #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<String>, } pub mod registry_key_entity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Hive { #[serde(rename = "HKEY_LOCAL_MACHINE")] HkeyLocalMachine, #[serde(rename = "HKEY_CLASSES_ROOT")] HkeyClassesRoot, #[serde(rename = "HKEY_CURRENT_CONFIG")] HkeyCurrentConfig, #[serde(rename = "HKEY_USERS")] HkeyUsers, #[serde(rename = "HKEY_CURRENT_USER_LOCAL_SETTINGS")] HkeyCurrentUserLocalSettings, #[serde(rename = "HKEY_PERFORMANCE_DATA")] HkeyPerformanceData, #[serde(rename = "HKEY_PERFORMANCE_NLSTEXT")] HkeyPerformanceNlstext, #[serde(rename = "HKEY_PERFORMANCE_TEXT")] HkeyPerformanceText, #[serde(rename = "HKEY_A")] HkeyA, #[serde(rename = "HKEY_CURRENT_USER")] HkeyCurrentUser, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryValueEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistryValueEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryValueEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "keyEntityId", default, skip_serializing_if = "Option::is_none")] pub key_entity_id: Option<String>, #[serde(rename = "valueData", default, skip_serializing_if = "Option::is_none")] pub value_data: Option<String>, #[serde(rename = "valueName", default, skip_serializing_if = "Option::is_none")] pub value_name: Option<String>, #[serde(rename = "valueType", default, skip_serializing_if = "Option::is_none")] pub value_type: Option<registry_value_entity_properties::ValueType>, } pub mod registry_value_entity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ValueType { None, Unknown, String, ExpandString, Binary, DWord, MultiString, QWord, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelationList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Relation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Relation { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RelationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelationProperties { #[serde(rename = "relatedResourceId")] pub related_resource_id: String, #[serde(rename = "relatedResourceName", default, skip_serializing_if = "Option::is_none")] pub related_resource_name: Option<String>, #[serde(rename = "relatedResourceType", default, skip_serializing_if = "Option::is_none")] pub related_resource_type: Option<String>, #[serde(rename = "relatedResourceKind", default, skip_serializing_if = "Option::is_none")] pub related_resource_kind: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceWithEtag { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: 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 etag: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScheduledAlertRule { #[serde(flatten)] pub alert_rule: AlertRule, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ScheduledAlertRuleProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScheduledAlertRuleCommonProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub query: Option<String>, #[serde(rename = "queryFrequency", default, skip_serializing_if = "Option::is_none")] pub query_frequency: Option<String>, #[serde(rename = "queryPeriod", default, skip_serializing_if = "Option::is_none")] pub query_period: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<AlertSeverity>, #[serde(rename = "triggerOperator", default, skip_serializing_if = "Option::is_none")] pub trigger_operator: Option<AlertRuleTriggerOperator>, #[serde(rename = "triggerThreshold", default, skip_serializing_if = "Option::is_none")] pub trigger_threshold: Option<i64>, #[serde(rename = "eventGroupingSettings", default, skip_serializing_if = "Option::is_none")] pub event_grouping_settings: Option<EventGroupingSettings>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventGroupingSettings { #[serde(rename = "aggregationKind", default, skip_serializing_if = "Option::is_none")] pub aggregation_kind: Option<EventGroupingAggregationKind>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EventGroupingAggregationKind { SingleAlert, AlertPerResult, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScheduledAlertRuleProperties { #[serde(flatten)] pub scheduled_alert_rule_common_properties: ScheduledAlertRuleCommonProperties, #[serde(rename = "alertRuleTemplateName", default, skip_serializing_if = "Option::is_none")] pub alert_rule_template_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName")] pub display_name: String, pub enabled: bool, #[serde(rename = "lastModifiedUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_utc: Option<String>, #[serde(rename = "suppressionDuration")] pub suppression_duration: String, #[serde(rename = "suppressionEnabled")] pub suppression_enabled: bool, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, #[serde(rename = "incidentConfiguration", default, skip_serializing_if = "Option::is_none")] pub incident_configuration: Option<IncidentConfiguration>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScheduledAlertRuleTemplate { #[serde(flatten)] pub alert_rule_template: AlertRuleTemplate, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<scheduled_alert_rule_template::Properties>, } pub mod scheduled_alert_rule_template { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(flatten)] pub alert_rule_template_properties_base: AlertRuleTemplatePropertiesBase, #[serde(flatten)] pub scheduled_alert_rule_common_properties: ScheduledAlertRuleCommonProperties, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentConfiguration { #[serde(rename = "createIncident")] pub create_incident: bool, #[serde(rename = "groupingConfiguration", default, skip_serializing_if = "Option::is_none")] pub grouping_configuration: Option<GroupingConfiguration>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GroupingConfiguration { pub enabled: bool, #[serde(rename = "reopenClosedIncident")] pub reopen_closed_incident: bool, #[serde(rename = "lookbackDuration")] pub lookback_duration: String, #[serde(rename = "entitiesMatchingMethod")] pub entities_matching_method: grouping_configuration::EntitiesMatchingMethod, #[serde(rename = "groupByEntities", default, skip_serializing_if = "Vec::is_empty")] pub group_by_entities: Vec<String>, } pub mod grouping_configuration { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EntitiesMatchingMethod { All, None, Custom, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecurityAlert { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SecurityAlertProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecurityAlertProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "alertDisplayName", default, skip_serializing_if = "Option::is_none")] pub alert_display_name: Option<String>, #[serde(rename = "alertType", default, skip_serializing_if = "Option::is_none")] pub alert_type: Option<String>, #[serde(rename = "compromisedEntity", default, skip_serializing_if = "Option::is_none")] pub compromised_entity: Option<String>, #[serde(rename = "confidenceLevel", default, skip_serializing_if = "Option::is_none")] pub confidence_level: Option<security_alert_properties::ConfidenceLevel>, #[serde(rename = "confidenceReasons", default, skip_serializing_if = "Vec::is_empty")] pub confidence_reasons: Vec<serde_json::Value>, #[serde(rename = "confidenceScore", default, skip_serializing_if = "Option::is_none")] pub confidence_score: Option<f64>, #[serde(rename = "confidenceScoreStatus", default, skip_serializing_if = "Option::is_none")] pub confidence_score_status: Option<security_alert_properties::ConfidenceScoreStatus>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "endTimeUtc", default, skip_serializing_if = "Option::is_none")] pub end_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub intent: Option<security_alert_properties::Intent>, #[serde(rename = "providerAlertId", default, skip_serializing_if = "Option::is_none")] pub provider_alert_id: Option<String>, #[serde(rename = "processingEndTime", default, skip_serializing_if = "Option::is_none")] pub processing_end_time: Option<String>, #[serde(rename = "productComponentName", default, skip_serializing_if = "Option::is_none")] pub product_component_name: Option<String>, #[serde(rename = "productName", default, skip_serializing_if = "Option::is_none")] pub product_name: Option<String>, #[serde(rename = "productVersion", default, skip_serializing_if = "Option::is_none")] pub product_version: Option<String>, #[serde(rename = "remediationSteps", default, skip_serializing_if = "Vec::is_empty")] pub remediation_steps: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<AlertSeverity>, #[serde(rename = "startTimeUtc", default, skip_serializing_if = "Option::is_none")] pub start_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<security_alert_properties::Status>, #[serde(rename = "systemAlertId", default, skip_serializing_if = "Option::is_none")] pub system_alert_id: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, #[serde(rename = "timeGenerated", default, skip_serializing_if = "Option::is_none")] pub time_generated: Option<String>, #[serde(rename = "vendorName", default, skip_serializing_if = "Option::is_none")] pub vendor_name: Option<String>, #[serde(rename = "alertLink", default, skip_serializing_if = "Option::is_none")] pub alert_link: Option<String>, #[serde(rename = "resourceIdentifiers", default, skip_serializing_if = "Vec::is_empty")] pub resource_identifiers: Vec<serde_json::Value>, } pub mod security_alert_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConfidenceLevel { Unknown, Low, High, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConfidenceScoreStatus { NotApplicable, InProcess, NotFinal, Final, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Intent { Unknown, Probing, Exploitation, Persistence, PrivilegeEscalation, DefenseEvasion, CredentialAccess, Discovery, LateralMovement, Execution, Collection, Exfiltration, CommandAndControl, Impact, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Unknown, New, Resolved, Dismissed, InProgress, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecurityGroupEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SecurityGroupEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecurityGroupEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "distinguishedName", default, skip_serializing_if = "Option::is_none")] pub distinguished_name: Option<String>, #[serde(rename = "objectGuid", default, skip_serializing_if = "Option::is_none")] pub object_guid: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sid: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SettingList { pub value: Vec<Settings>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Settings { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(flatten)] pub settings_kind: SettingsKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SettingsKind { pub kind: settings_kind::Kind, } pub mod settings_kind { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Anomalies, EyesOn, EntityAnalytics, Ueba, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TiDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiDataConnectorDataTypes { pub indicators: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiDataConnectorProperties { #[serde(rename = "tenantId")] pub tenant_id: String, #[serde(rename = "tipLookbackPeriod", default, skip_serializing_if = "Option::is_none")] pub tip_lookback_period: Option<String>, #[serde(rename = "dataTypes")] pub data_types: TiDataConnectorDataTypes, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiTaxiiDataConnector { #[serde(flatten)] pub data_connector: DataConnector, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TiTaxiiDataConnectorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiTaxiiDataConnectorDataTypes { #[serde(rename = "taxiiClient")] pub taxii_client: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiTaxiiDataConnectorProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, #[serde(rename = "workspaceId", default, skip_serializing_if = "Option::is_none")] pub workspace_id: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "taxiiServer", default, skip_serializing_if = "Option::is_none")] pub taxii_server: Option<String>, #[serde(rename = "collectionId", default, skip_serializing_if = "Option::is_none")] pub collection_id: Option<String>, #[serde(rename = "userName", default, skip_serializing_if = "Option::is_none")] pub user_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, #[serde(rename = "taxiiLookbackPeriod", default, skip_serializing_if = "Option::is_none")] pub taxii_lookback_period: Option<String>, #[serde(rename = "pollingFrequency")] pub polling_frequency: ti_taxii_data_connector_properties::PollingFrequency, #[serde(rename = "dataTypes")] pub data_types: TiTaxiiDataConnectorDataTypes, } pub mod ti_taxii_data_connector_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PollingFrequency { OnceAMinute, OnceAnHour, OnceADay, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligence { #[serde(default, skip_serializing_if = "Option::is_none")] pub confidence: Option<f64>, #[serde(rename = "providerName", default, skip_serializing_if = "Option::is_none")] pub provider_name: Option<String>, #[serde(rename = "reportLink", default, skip_serializing_if = "Option::is_none")] pub report_link: Option<String>, #[serde(rename = "threatDescription", default, skip_serializing_if = "Option::is_none")] pub threat_description: Option<String>, #[serde(rename = "threatName", default, skip_serializing_if = "Option::is_none")] pub threat_name: Option<String>, #[serde(rename = "threatType", default, skip_serializing_if = "Option::is_none")] pub threat_type: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub email: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")] pub object_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Anomalies { #[serde(flatten)] pub settings: Settings, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AnomaliesProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AnomaliesProperties { #[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")] pub is_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpSyncer { #[serde(flatten)] pub settings: Settings, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IpSyncerSettingsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpSyncerSettingsProperties { #[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")] pub is_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EyesOn { #[serde(flatten)] pub settings: Settings, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<EyesOnSettingsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EyesOnSettingsProperties { #[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")] pub is_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityAnalytics { #[serde(flatten)] pub settings: Settings, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<EntityAnalyticsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityAnalyticsProperties { #[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")] pub is_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Ueba { #[serde(flatten)] pub settings: Settings, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<UebaProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UebaProperties { #[serde(rename = "dataSources", default, skip_serializing_if = "Vec::is_empty")] pub data_sources: Vec<UebaDataSources>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UebaDataSources { AuditLogs, AzureActivity, SecurityEvent, SigninLogs, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UrlEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<UrlEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UrlEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTDeviceEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IoTDeviceEntityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTDeviceEntityProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "deviceId", default, skip_serializing_if = "Option::is_none")] pub device_id: Option<String>, #[serde(rename = "deviceName", default, skip_serializing_if = "Option::is_none")] pub device_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<String>, #[serde(rename = "iotSecurityAgentId", default, skip_serializing_if = "Option::is_none")] pub iot_security_agent_id: Option<String>, #[serde(rename = "deviceType", default, skip_serializing_if = "Option::is_none")] pub device_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub vendor: Option<String>, #[serde(rename = "edgeId", default, skip_serializing_if = "Option::is_none")] pub edge_id: Option<String>, #[serde(rename = "macAddress", default, skip_serializing_if = "Option::is_none")] pub mac_address: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option<String>, #[serde(rename = "serialNumber", default, skip_serializing_if = "Option::is_none")] pub serial_number: Option<String>, #[serde(rename = "firmwareVersion", default, skip_serializing_if = "Option::is_none")] pub firmware_version: Option<String>, #[serde(rename = "operatingSystem", default, skip_serializing_if = "Option::is_none")] pub operating_system: Option<String>, #[serde(rename = "iotHubEntityId", default, skip_serializing_if = "Option::is_none")] pub iot_hub_entity_id: Option<String>, #[serde(rename = "hostEntityId", default, skip_serializing_if = "Option::is_none")] pub host_entity_id: Option<String>, #[serde(rename = "ipAddressEntityId", default, skip_serializing_if = "Option::is_none")] pub ip_address_entity_id: Option<String>, #[serde(rename = "threatIntelligence", default, skip_serializing_if = "Vec::is_empty")] pub threat_intelligence: Vec<ThreatIntelligence>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub protocols: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IncidentInfo { #[serde(rename = "incidentId", default, skip_serializing_if = "Option::is_none")] pub incident_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<IncidentSeverity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(rename = "relationName", default, skip_serializing_if = "Option::is_none")] pub relation_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WatchlistList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Watchlist>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Watchlist { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WatchlistProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WatchlistProperties { #[serde(rename = "watchlistId", default, skip_serializing_if = "Option::is_none")] pub watchlist_id: Option<String>, #[serde(rename = "displayName")] pub display_name: String, pub provider: String, pub source: watchlist_properties::Source, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<UserInfo>, #[serde(rename = "updatedBy", default, skip_serializing_if = "Option::is_none")] pub updated_by: Option<UserInfo>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "watchlistType", default, skip_serializing_if = "Option::is_none")] pub watchlist_type: Option<String>, #[serde(rename = "watchlistAlias", default, skip_serializing_if = "Option::is_none")] pub watchlist_alias: Option<String>, #[serde(rename = "isDeleted", default, skip_serializing_if = "Option::is_none")] pub is_deleted: Option<bool>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<Label>, #[serde(rename = "defaultDuration", default, skip_serializing_if = "Option::is_none")] pub default_duration: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "numberOfLinesToSkip", default, skip_serializing_if = "Option::is_none")] pub number_of_lines_to_skip: Option<i32>, #[serde(rename = "rawContent", default, skip_serializing_if = "Option::is_none")] pub raw_content: Option<String>, #[serde(rename = "contentType", default, skip_serializing_if = "Option::is_none")] pub content_type: Option<String>, #[serde(rename = "uploadStatus", default, skip_serializing_if = "Option::is_none")] pub upload_status: Option<String>, #[serde(rename = "watchlistItemsCount", default, skip_serializing_if = "Option::is_none")] pub watchlist_items_count: Option<i32>, } pub mod watchlist_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Source { #[serde(rename = "Local file")] LocalFile, #[serde(rename = "Remote storage")] RemoteStorage, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WatchlistItemList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<WatchlistItem>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WatchlistItem { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WatchlistItemProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WatchlistItemProperties { #[serde(rename = "watchlistItemType", default, skip_serializing_if = "Option::is_none")] pub watchlist_item_type: Option<String>, #[serde(rename = "watchlistItemId", default, skip_serializing_if = "Option::is_none")] pub watchlist_item_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "isDeleted", default, skip_serializing_if = "Option::is_none")] pub is_deleted: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<UserInfo>, #[serde(rename = "updatedBy", default, skip_serializing_if = "Option::is_none")] pub updated_by: Option<UserInfo>, #[serde(rename = "itemsKeyValue")] pub items_key_value: serde_json::Value, #[serde(rename = "entityMapping", default, skip_serializing_if = "Option::is_none")] pub entity_mapping: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRule { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AutomationRuleProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRuleAction { pub order: i32, #[serde(rename = "actionType")] pub action_type: automation_rule_action::ActionType, } pub mod automation_rule_action { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ActionType { ModifyProperties, RunPlaybook, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRuleCondition { #[serde(rename = "conditionType")] pub condition_type: automation_rule_condition::ConditionType, } pub mod automation_rule_condition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConditionType { Property, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRuleProperties { #[serde(rename = "displayName")] pub display_name: String, pub order: i32, #[serde(rename = "triggeringLogic")] pub triggering_logic: AutomationRuleTriggeringLogic, pub actions: Vec<AutomationRuleAction>, #[serde(rename = "createdTimeUtc", default, skip_serializing_if = "Option::is_none")] pub created_time_utc: Option<String>, #[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_time_utc: Option<String>, #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<ClientInfo>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<ClientInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRulesList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<AutomationRule>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRuleRunPlaybookAction { #[serde(flatten)] pub automation_rule_action: AutomationRuleAction, #[serde(rename = "actionConfiguration")] pub action_configuration: automation_rule_run_playbook_action::ActionConfiguration, } pub mod automation_rule_run_playbook_action { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionConfiguration { #[serde(rename = "logicAppResourceId", default, skip_serializing_if = "Option::is_none")] pub logic_app_resource_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRuleModifyPropertiesAction { #[serde(flatten)] pub automation_rule_action: AutomationRuleAction, #[serde(rename = "actionConfiguration")] pub action_configuration: automation_rule_modify_properties_action::ActionConfiguration, } pub mod automation_rule_modify_properties_action { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionConfiguration { #[serde(default, skip_serializing_if = "Option::is_none")] pub classification: Option<IncidentClassification>, #[serde(rename = "classificationComment", default, skip_serializing_if = "Option::is_none")] pub classification_comment: Option<String>, #[serde(rename = "classificationReason", default, skip_serializing_if = "Option::is_none")] pub classification_reason: Option<IncidentClassificationReason>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<IncidentLabel>, #[serde(default, skip_serializing_if = "Option::is_none")] pub owner: Option<IncidentOwnerInfo>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<IncidentSeverity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<IncidentStatus>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AutomationRulePropertyConditionSupportedProperty { IncidentTitle, IncidentDescription, IncidentSeverity, IncidentStatus, IncidentTactics, IncidentRelatedAnalyticRuleIds, IncidentProviderName, AccountAadTenantId, AccountAadUserId, AccountName, #[serde(rename = "AccountNTDomain")] AccountNtDomain, #[serde(rename = "AccountPUID")] AccountPuid, AccountSid, AccountObjectGuid, #[serde(rename = "AccountUPNSuffix")] AccountUpnSuffix, AzureResourceResourceId, AzureResourceSubscriptionId, CloudApplicationAppId, CloudApplicationAppName, #[serde(rename = "DNSDomainName")] DnsDomainName, FileDirectory, FileName, FileHashValue, #[serde(rename = "HostAzureID")] HostAzureId, HostName, HostNetBiosName, #[serde(rename = "HostNTDomain")] HostNtDomain, #[serde(rename = "HostOSVersion")] HostOsVersion, IoTDeviceId, IoTDeviceName, IoTDeviceType, IoTDeviceVendor, IoTDeviceModel, IoTDeviceOperatingSystem, #[serde(rename = "IPAddress")] IpAddress, MailboxDisplayName, MailboxPrimaryAddress, #[serde(rename = "MailboxUPN")] MailboxUpn, MailMessageDeliveryAction, MailMessageDeliveryLocation, MailMessageRecipient, #[serde(rename = "MailMessageSenderIP")] MailMessageSenderIp, MailMessageSubject, MailMessageP1Sender, MailMessageP2Sender, MalwareCategory, MalwareName, ProcessCommandLine, ProcessId, RegistryKey, RegistryValueData, Url, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRulePropertyValuesCondition { #[serde(flatten)] pub automation_rule_condition: AutomationRuleCondition, #[serde(rename = "conditionProperties")] pub condition_properties: automation_rule_property_values_condition::ConditionProperties, } pub mod automation_rule_property_values_condition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConditionProperties { #[serde(rename = "propertyName", default, skip_serializing_if = "Option::is_none")] pub property_name: Option<AutomationRulePropertyConditionSupportedProperty>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operator: Option<condition_properties::Operator>, #[serde(rename = "propertyValues", default, skip_serializing_if = "Vec::is_empty")] pub property_values: Vec<String>, } pub mod condition_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Operator { Equals, NotEquals, Contains, NotContains, StartsWith, NotStartsWith, EndsWith, NotEndsWith, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutomationRuleTriggeringLogic { #[serde(rename = "isEnabled")] pub is_enabled: bool, #[serde(rename = "expirationTimeUtc", default, skip_serializing_if = "Option::is_none")] pub expiration_time_utc: Option<String>, #[serde(rename = "triggersOn")] pub triggers_on: automation_rule_triggering_logic::TriggersOn, #[serde(rename = "triggersWhen")] pub triggers_when: automation_rule_triggering_logic::TriggersWhen, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub conditions: Vec<AutomationRuleCondition>, } pub mod automation_rule_triggering_logic { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TriggersOn { Incidents, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TriggersWhen { Created, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Bookmark { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<BookmarkProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BookmarkExpandResponse { #[serde(rename = "metaData", default, skip_serializing_if = "Option::is_none")] pub meta_data: Option<ExpansionResultsMetadata>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<bookmark_expand_response::Value>, } pub mod bookmark_expand_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Value { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entities: Vec<Entity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub edges: Vec<ConnectedEntity>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BookmarkExpandParameters { #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "expansionId", default, skip_serializing_if = "Option::is_none")] pub expansion_id: Option<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BookmarkList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Bookmark>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BookmarkProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<UserInfo>, #[serde(rename = "displayName")] pub display_name: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<Label>, #[serde(default, skip_serializing_if = "Option::is_none")] pub notes: Option<String>, pub query: String, #[serde(rename = "queryResult", default, skip_serializing_if = "Option::is_none")] pub query_result: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(rename = "updatedBy", default, skip_serializing_if = "Option::is_none")] pub updated_by: Option<UserInfo>, #[serde(rename = "eventTime", default, skip_serializing_if = "Option::is_none")] pub event_time: Option<String>, #[serde(rename = "queryStartTime", default, skip_serializing_if = "Option::is_none")] pub query_start_time: Option<String>, #[serde(rename = "queryEndTime", default, skip_serializing_if = "Option::is_none")] pub query_end_time: Option<String>, #[serde(rename = "incidentInfo", default, skip_serializing_if = "Option::is_none")] pub incident_info: Option<IncidentInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Case { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CaseProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseComment { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CaseCommentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseCommentList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<CaseComment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseCommentProperties { #[serde(rename = "createdTimeUtc", default, skip_serializing_if = "Option::is_none")] pub created_time_utc: Option<String>, pub message: String, #[serde(rename = "userInfo", default, skip_serializing_if = "Option::is_none")] pub user_info: Option<UserInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Case>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseProperties { #[serde(rename = "caseNumber", default, skip_serializing_if = "Option::is_none")] pub case_number: Option<i64>, #[serde(rename = "closeReason", default, skip_serializing_if = "Option::is_none")] pub close_reason: Option<case_properties::CloseReason>, #[serde(rename = "closedReasonText", default, skip_serializing_if = "Option::is_none")] pub closed_reason_text: Option<String>, #[serde(rename = "createdTimeUtc", default, skip_serializing_if = "Option::is_none")] pub created_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "endTimeUtc", default, skip_serializing_if = "Option::is_none")] pub end_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<Label>, #[serde(rename = "lastComment", default, skip_serializing_if = "Option::is_none")] pub last_comment: Option<String>, #[serde(rename = "lastUpdatedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_updated_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub metrics: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub owner: Option<UserInfo>, #[serde(rename = "relatedAlertIds", default, skip_serializing_if = "Vec::is_empty")] pub related_alert_ids: Vec<String>, #[serde(rename = "relatedAlertProductNames", default, skip_serializing_if = "Vec::is_empty")] pub related_alert_product_names: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tactics: Vec<AttackTactic>, pub severity: case_properties::Severity, #[serde(rename = "startTimeUtc", default, skip_serializing_if = "Option::is_none")] pub start_time_utc: Option<String>, pub status: case_properties::Status, pub title: String, #[serde(rename = "totalComments", default, skip_serializing_if = "Option::is_none")] pub total_comments: Option<i64>, } pub mod case_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CloseReason { Resolved, Dismissed, TruePositive, FalsePositive, Other, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Severity { Critical, High, Medium, Low, Informational, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Draft, New, InProgress, Closed, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseRelationList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<CaseRelation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseRelation { #[serde(flatten)] pub relation_base: RelationBase, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CaseRelationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CaseRelationProperties { #[serde(rename = "relationName")] pub relation_name: String, #[serde(rename = "bookmarkId")] pub bookmark_id: String, #[serde(rename = "caseIdentifier")] pub case_identifier: String, #[serde(rename = "bookmarkName", default, skip_serializing_if = "Option::is_none")] pub bookmark_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelationsModelInput { #[serde(flatten)] pub relation_base: RelationBase, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RelationsModelInputProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelationsModelInputProperties { #[serde(rename = "relationName", default, skip_serializing_if = "Option::is_none")] pub relation_name: Option<String>, #[serde(rename = "sourceRelationNode", default, skip_serializing_if = "Option::is_none")] pub source_relation_node: Option<RelationNode>, #[serde(rename = "targetRelationNode", default, skip_serializing_if = "Option::is_none")] pub target_relation_node: Option<RelationNode>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelationBase { #[serde(flatten)] pub resource: Resource, #[serde(flatten)] pub serde_json_value: serde_json::Value, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelationNode { #[serde(rename = "relationNodeId", default, skip_serializing_if = "Option::is_none")] pub relation_node_id: Option<String>, #[serde(rename = "relationNodeKind", default, skip_serializing_if = "Option::is_none")] pub relation_node_kind: Option<relation_node::RelationNodeKind>, #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<String>, #[serde(rename = "relationAdditionalProperties", default, skip_serializing_if = "Option::is_none")] pub relation_additional_properties: Option<serde_json::Value>, } pub mod relation_node { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RelationNodeKind { Case, Bookmark, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AadCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AadCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AadCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AatpCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AatpCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AatpCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AscCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AscCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AscCheckRequirementsProperties { #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsCloudTrailCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorsCheckRequirements { pub kind: DataConnectorKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DataConnectorAuthorizationState { Valid, Invalid, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DataConnectorLicenseState { Valid, Invalid, Unknown, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataConnectorRequirementsState { #[serde(rename = "authorizationState", default, skip_serializing_if = "Option::is_none")] pub authorization_state: Option<DataConnectorAuthorizationState>, #[serde(rename = "licenseState", default, skip_serializing_if = "Option::is_none")] pub license_state: Option<DataConnectorLicenseState>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dynamics365CheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<Dynamics365CheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dynamics365CheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct McasCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<McasCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct McasCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MdatpCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MdatpCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MdatpCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MstiCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MstiCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MstiCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MtpCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MtpCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MtpCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeAtpCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OfficeAtpCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeAtpCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TiCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiTaxiiCheckRequirements { #[serde(flatten)] pub data_connectors_check_requirements: DataConnectorsCheckRequirements, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TiTaxiiCheckRequirementsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TiTaxiiCheckRequirementsProperties { #[serde(flatten)] pub data_connector_tenant_id: DataConnectorTenantId, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentDomainWhois { #[serde(default, skip_serializing_if = "Option::is_none")] pub domain: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub server: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expires: Option<String>, #[serde(rename = "parsedWhois", default, skip_serializing_if = "Option::is_none")] pub parsed_whois: Option<EnrichmentDomainWhoisDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentDomainWhoisDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub registrar: Option<EnrichmentDomainWhoisRegistrarDetails>, #[serde(default, skip_serializing_if = "Option::is_none")] pub contacts: Option<EnrichmentDomainWhoisContacts>, #[serde(rename = "nameServers", default, skip_serializing_if = "Vec::is_empty")] pub name_servers: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub statuses: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentDomainWhoisRegistrarDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "abuseContactEmail", default, skip_serializing_if = "Option::is_none")] pub abuse_contact_email: Option<String>, #[serde(rename = "abuseContactPhone", default, skip_serializing_if = "Option::is_none")] pub abuse_contact_phone: Option<String>, #[serde(rename = "ianaId", default, skip_serializing_if = "Option::is_none")] pub iana_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(rename = "whoisServer", default, skip_serializing_if = "Option::is_none")] pub whois_server: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentDomainWhoisContacts { #[serde(default, skip_serializing_if = "Option::is_none")] pub admin: Option<EnrichmentDomainWhoisContact>, #[serde(default, skip_serializing_if = "Option::is_none")] pub billing: Option<EnrichmentDomainWhoisContact>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registrant: Option<EnrichmentDomainWhoisContact>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tech: Option<EnrichmentDomainWhoisContact>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentDomainWhoisContact { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub org: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub street: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub city: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub postal: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub country: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub phone: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub fax: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub email: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentIpGeodata { #[serde(default, skip_serializing_if = "Option::is_none")] pub asn: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub carrier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub city: Option<String>, #[serde(rename = "cityCf", default, skip_serializing_if = "Option::is_none")] pub city_cf: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub continent: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub country: Option<String>, #[serde(rename = "countryCf", default, skip_serializing_if = "Option::is_none")] pub country_cf: Option<i32>, #[serde(rename = "ipAddr", default, skip_serializing_if = "Option::is_none")] pub ip_addr: Option<String>, #[serde(rename = "ipRoutingType", default, skip_serializing_if = "Option::is_none")] pub ip_routing_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub latitude: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub longitude: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub organization: Option<String>, #[serde(rename = "organizationType", default, skip_serializing_if = "Option::is_none")] pub organization_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub region: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(rename = "stateCf", default, skip_serializing_if = "Option::is_none")] pub state_cf: Option<i32>, #[serde(rename = "stateCode", default, skip_serializing_if = "Option::is_none")] pub state_code: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActivityTimelineItem { #[serde(flatten)] pub entity_timeline_item: EntityTimelineItem, #[serde(rename = "queryId")] pub query_id: String, #[serde(rename = "bucketStartTimeUTC")] pub bucket_start_time_utc: String, #[serde(rename = "bucketEndTimeUTC")] pub bucket_end_time_utc: String, #[serde(rename = "firstActivityTimeUTC")] pub first_activity_time_utc: String, #[serde(rename = "lastActivityTimeUTC")] pub last_activity_time_utc: String, pub content: String, pub title: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BookmarkTimelineItem { #[serde(flatten)] pub entity_timeline_item: EntityTimelineItem, #[serde(rename = "azureResourceId")] pub azure_resource_id: String, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub notes: Option<String>, #[serde(rename = "endTimeUtc", default, skip_serializing_if = "Option::is_none")] pub end_time_utc: Option<String>, #[serde(rename = "startTimeUtc", default, skip_serializing_if = "Option::is_none")] pub start_time_utc: Option<String>, #[serde(rename = "eventTime", default, skip_serializing_if = "Option::is_none")] pub event_time: Option<String>, #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<UserInfo>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<Label>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityGetInsightsParameters { #[serde(rename = "startTime")] pub start_time: String, #[serde(rename = "endTime")] pub end_time: String, #[serde(rename = "addDefaultExtendedTimeRange", default, skip_serializing_if = "Option::is_none")] pub add_default_extended_time_range: Option<bool>, #[serde(rename = "insightQueryIds", default, skip_serializing_if = "Vec::is_empty")] pub insight_query_ids: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityGetInsightsResponse { #[serde(rename = "metaData", default, skip_serializing_if = "Option::is_none")] pub meta_data: Option<GetInsightsResultsMetadata>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EntityInsightItem>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityEdges { #[serde(rename = "targetEntityId", default, skip_serializing_if = "Option::is_none")] pub target_entity_id: Option<String>, #[serde(rename = "additionalData", default, skip_serializing_if = "Option::is_none")] pub additional_data: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityExpandParameters { #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "expansionId", default, skip_serializing_if = "Option::is_none")] pub expansion_id: Option<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityExpandResponse { #[serde(rename = "metaData", default, skip_serializing_if = "Option::is_none")] pub meta_data: Option<ExpansionResultsMetadata>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<entity_expand_response::Value>, } pub mod entity_expand_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Value { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entities: Vec<Entity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub edges: Vec<EntityEdges>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityInsightItem { #[serde(rename = "queryId", default, skip_serializing_if = "Option::is_none")] pub query_id: Option<String>, #[serde(rename = "queryTimeInterval", default, skip_serializing_if = "Option::is_none")] pub query_time_interval: Option<entity_insight_item::QueryTimeInterval>, #[serde(rename = "tableQueryResults", default, skip_serializing_if = "Option::is_none")] pub table_query_results: Option<InsightsTableResult>, #[serde(rename = "chartQueryResults", default, skip_serializing_if = "Vec::is_empty")] pub chart_query_results: Vec<InsightsTableResult>, } pub mod entity_insight_item { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryTimeInterval { #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<Entity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityTimelineItem { pub kind: EntityTimelineKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityTimelineResponse { #[serde(rename = "metaData", default, skip_serializing_if = "Option::is_none")] pub meta_data: Option<TimelineResultsMetadata>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EntityTimelineItem>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EntityTimelineKind { Activity, Bookmark, SecurityAlert, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityTimelineParameters { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub kinds: Vec<EntityTimelineKind>, #[serde(rename = "startTime")] pub start_time: String, #[serde(rename = "endTime")] pub end_time: String, #[serde(rename = "numberOfBucket", default, skip_serializing_if = "Option::is_none")] pub number_of_bucket: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityQueryItem { #[serde(flatten)] pub entity_query_kind: EntityQueryKind, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EntityQueryItemProperties { #[serde(rename = "dataTypes", default, skip_serializing_if = "Vec::is_empty")] pub data_types: Vec<serde_json::Value>, #[serde(rename = "inputEntityType", default, skip_serializing_if = "Option::is_none")] pub input_entity_type: Option<EntityInnerType>, #[serde(rename = "requiredInputFieldsSets", default, skip_serializing_if = "Vec::is_empty")] pub required_input_fields_sets: Vec<Vec<String>>, #[serde(rename = "entitiesFilter", default, skip_serializing_if = "Option::is_none")] pub entities_filter: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InsightsTableResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub columns: Vec<serde_json::Value>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub rows: Vec<Vec<String>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InsightQueryItem { #[serde(flatten)] pub entity_query_item: EntityQueryItem, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<InsightQueryItemProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InsightQueryItemProperties { #[serde(flatten)] pub entity_query_item_properties: EntityQueryItemProperties, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "baseQuery", default, skip_serializing_if = "Option::is_none")] pub base_query: Option<String>, #[serde(rename = "tableQuery", default, skip_serializing_if = "Option::is_none")] pub table_query: Option<insight_query_item_properties::TableQuery>, #[serde(rename = "chartQuery", default, skip_serializing_if = "Option::is_none")] pub chart_query: Option<serde_json::Value>, #[serde(rename = "additionalQuery", default, skip_serializing_if = "Option::is_none")] pub additional_query: Option<insight_query_item_properties::AdditionalQuery>, #[serde(rename = "defaultTimeRange", default, skip_serializing_if = "Option::is_none")] pub default_time_range: Option<insight_query_item_properties::DefaultTimeRange>, #[serde(rename = "referenceTimeRange", default, skip_serializing_if = "Option::is_none")] pub reference_time_range: Option<insight_query_item_properties::ReferenceTimeRange>, } pub mod insight_query_item_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TableQuery { #[serde(rename = "columnsDefinitions", default, skip_serializing_if = "Vec::is_empty")] pub columns_definitions: Vec<serde_json::Value>, #[serde(rename = "queriesDefinitions", default, skip_serializing_if = "Vec::is_empty")] pub queries_definitions: Vec<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AdditionalQuery { #[serde(default, skip_serializing_if = "Option::is_none")] pub query: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub text: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultTimeRange { #[serde(rename = "beforeRange", default, skip_serializing_if = "Option::is_none")] pub before_range: Option<String>, #[serde(rename = "afterRange", default, skip_serializing_if = "Option::is_none")] pub after_range: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceTimeRange { #[serde(rename = "beforeRange", default, skip_serializing_if = "Option::is_none")] pub before_range: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GetInsightsResultsMetadata { #[serde(rename = "totalCount")] pub total_count: i32, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub errors: Vec<GetInsightsError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GetInsightsError { pub kind: get_insights_error::Kind, #[serde(rename = "queryId", default, skip_serializing_if = "Option::is_none")] pub query_id: Option<String>, #[serde(rename = "errorMessage")] pub error_message: String, } pub mod get_insights_error { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Insight, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GetQueriesResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EntityQueryItem>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecurityAlertTimelineItem { #[serde(flatten)] pub entity_timeline_item: EntityTimelineItem, #[serde(rename = "azureResourceId")] pub azure_resource_id: String, #[serde(rename = "productName", default, skip_serializing_if = "Option::is_none")] pub product_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName")] pub display_name: String, pub severity: AlertSeverity, #[serde(rename = "endTimeUtc")] pub end_time_utc: String, #[serde(rename = "startTimeUtc")] pub start_time_utc: String, #[serde(rename = "timeGenerated")] pub time_generated: String, #[serde(rename = "alertType")] pub alert_type: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimelineError { pub kind: EntityTimelineKind, #[serde(rename = "queryId", default, skip_serializing_if = "Option::is_none")] pub query_id: Option<String>, #[serde(rename = "errorMessage")] pub error_message: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimelineResultsMetadata { #[serde(rename = "totalCount")] pub total_count: i32, pub aggregations: Vec<TimelineAggregation>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub errors: Vec<TimelineError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimelineAggregation { pub count: i32, pub kind: EntityTimelineKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeConsent { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OfficeConsentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeConsentList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<OfficeConsent>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfficeConsentProperties { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "consentId", default, skip_serializing_if = "Option::is_none")] pub consent_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceInformationList { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, pub value: Vec<ThreatIntelligenceInformation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceInformation { #[serde(flatten)] pub resource_with_etag: ResourceWithEtag, #[serde(flatten)] pub threat_intelligence_resource_kind: ThreatIntelligenceResourceKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceIndicatorModel { #[serde(flatten)] pub threat_intelligence_information: ThreatIntelligenceInformation, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ThreatIntelligenceIndicatorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceIndicatorModelForRequestBody { #[serde(flatten)] pub threat_intelligence_resource_kind: ThreatIntelligenceResourceKind, #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ThreatIntelligenceIndicatorProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceResourceKind { pub kind: ThreatIntelligenceResourceInnerKind, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ThreatIntelligenceResourceInnerKind { #[serde(rename = "indicator")] Indicator, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceIndicatorProperties { #[serde(flatten)] pub entity_common_properties: EntityCommonProperties, #[serde(rename = "threatIntelligenceTags", default, skip_serializing_if = "Vec::is_empty")] pub threat_intelligence_tags: Vec<String>, #[serde(rename = "lastUpdatedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_updated_time_utc: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "indicatorTypes", default, skip_serializing_if = "Vec::is_empty")] pub indicator_types: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub pattern: Option<String>, #[serde(rename = "patternType", default, skip_serializing_if = "Option::is_none")] pub pattern_type: Option<String>, #[serde(rename = "patternVersion", default, skip_serializing_if = "Option::is_none")] pub pattern_version: Option<String>, #[serde(rename = "killChainPhases", default, skip_serializing_if = "Vec::is_empty")] pub kill_chain_phases: Vec<ThreatIntelligenceKillChainPhase>, #[serde(rename = "parsedPattern", default, skip_serializing_if = "Vec::is_empty")] pub parsed_pattern: Vec<ThreatIntelligenceParsedPattern>, #[serde(rename = "externalId", default, skip_serializing_if = "Option::is_none")] pub external_id: Option<String>, #[serde(rename = "createdByRef", default, skip_serializing_if = "Option::is_none")] pub created_by_ref: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub defanged: Option<bool>, #[serde(rename = "externalLastUpdatedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub external_last_updated_time_utc: Option<String>, #[serde(rename = "externalReferences", default, skip_serializing_if = "Vec::is_empty")] pub external_references: Vec<ThreatIntelligenceExternalReference>, #[serde(rename = "granularMarkings", default, skip_serializing_if = "Vec::is_empty")] pub granular_markings: Vec<ThreatIntelligenceGranularMarkingModel>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub revoked: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub confidence: Option<i32>, #[serde(rename = "objectMarkingRefs", default, skip_serializing_if = "Vec::is_empty")] pub object_marking_refs: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option<String>, #[serde(rename = "threatTypes", default, skip_serializing_if = "Vec::is_empty")] pub threat_types: Vec<String>, #[serde(rename = "validFrom", default, skip_serializing_if = "Option::is_none")] pub valid_from: Option<String>, #[serde(rename = "validUntil", default, skip_serializing_if = "Option::is_none")] pub valid_until: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub modified: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub extensions: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceKillChainPhase { #[serde(rename = "killChainName", default, skip_serializing_if = "Option::is_none")] pub kill_chain_name: Option<String>, #[serde(rename = "phaseName", default, skip_serializing_if = "Option::is_none")] pub phase_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceParsedPattern { #[serde(rename = "patternTypeKey", default, skip_serializing_if = "Option::is_none")] pub pattern_type_key: Option<String>, #[serde(rename = "patternTypeValues", default, skip_serializing_if = "Vec::is_empty")] pub pattern_type_values: Vec<ThreatIntelligenceParsedPatternTypeValue>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceParsedPatternTypeValue { #[serde(rename = "valueType", default, skip_serializing_if = "Option::is_none")] pub value_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceGranularMarkingModel { #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option<String>, #[serde(rename = "markingRef", default, skip_serializing_if = "Option::is_none")] pub marking_ref: Option<i32>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub selectors: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceExternalReference { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "externalId", default, skip_serializing_if = "Option::is_none")] pub external_id: Option<String>, #[serde(rename = "sourceName", default, skip_serializing_if = "Option::is_none")] pub source_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub hashes: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceFilteringCriteria { #[serde(rename = "pageSize", default, skip_serializing_if = "Option::is_none")] pub page_size: Option<i32>, #[serde(rename = "minConfidence", default, skip_serializing_if = "Option::is_none")] pub min_confidence: Option<i32>, #[serde(rename = "maxConfidence", default, skip_serializing_if = "Option::is_none")] pub max_confidence: Option<i32>, #[serde(rename = "minValidUntil", default, skip_serializing_if = "Option::is_none")] pub min_valid_until: Option<String>, #[serde(rename = "maxValidUntil", default, skip_serializing_if = "Option::is_none")] pub max_valid_until: Option<String>, #[serde(rename = "includeDisabled", default, skip_serializing_if = "Option::is_none")] pub include_disabled: Option<bool>, #[serde(rename = "sortBy", default, skip_serializing_if = "Vec::is_empty")] pub sort_by: Vec<ThreatIntelligenceSortingCriteria>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sources: Vec<String>, #[serde(rename = "patternTypes", default, skip_serializing_if = "Vec::is_empty")] pub pattern_types: Vec<String>, #[serde(rename = "threatTypes", default, skip_serializing_if = "Vec::is_empty")] pub threat_types: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ids: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub keywords: Vec<String>, #[serde(rename = "skipToken", default, skip_serializing_if = "Option::is_none")] pub skip_token: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceSortingCriteria { #[serde(rename = "itemKey", default, skip_serializing_if = "Option::is_none")] pub item_key: Option<String>, #[serde(rename = "sortOrder", default, skip_serializing_if = "Option::is_none")] pub sort_order: Option<ThreatIntelligenceSortingOrder>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ThreatIntelligenceSortingOrder { #[serde(rename = "unsorted")] Unsorted, #[serde(rename = "ascending")] Ascending, #[serde(rename = "descending")] Descending, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceAppendTags { #[serde(rename = "threatIntelligenceTags", default, skip_serializing_if = "Vec::is_empty")] pub threat_intelligence_tags: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceMetricsList { pub value: Vec<ThreatIntelligenceMetrics>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceMetrics { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ThreatIntelligenceMetric>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceMetric { #[serde(rename = "lastUpdatedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_updated_time_utc: Option<String>, #[serde(rename = "threatTypeMetrics", default, skip_serializing_if = "Vec::is_empty")] pub threat_type_metrics: Vec<ThreatIntelligenceMetricEntity>, #[serde(rename = "patternTypeMetrics", default, skip_serializing_if = "Vec::is_empty")] pub pattern_type_metrics: Vec<ThreatIntelligenceMetricEntity>, #[serde(rename = "sourceMetrics", default, skip_serializing_if = "Vec::is_empty")] pub source_metrics: Vec<ThreatIntelligenceMetricEntity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreatIntelligenceMetricEntity { #[serde(rename = "metricName", default, skip_serializing_if = "Option::is_none")] pub metric_name: Option<String>, #[serde(rename = "metricValue", default, skip_serializing_if = "Option::is_none")] pub metric_value: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } }
use crate::models::MultiLanguageString; use crate::{Result, VGMError}; use select::node::Node; use select::predicate::Attr; fn parse_month(input: &str) -> Result<u8> { // Months // Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec // January, February, March, April, May, June, July, August, September, October, November, December Ok(match input { "January" | "Jan" => 1, "February" | "Feb" => 2, "March" | "Mar" => 3, "April" | "Apr" => 4, "May" => 5, "June" | "Jun" => 6, "July" | "Jul" => 7, "August" | "Aug" => 8, "September" | "Sep" => 9, "October" | "Oct" => 10, "November" | "Nov" => 11, "December" | "Dec" => 12, _ => return Err(VGMError::InvalidDate), }) } pub(crate) fn parse_date(input: &str) -> Result<String> { let input = input.trim().replace(",", ""); let parts = input.split(" ").collect::<Vec<&str>>(); // there are three types of time return if parts.len() >= 3 { // 1. Month date, Year -> Month date Year // 0 1 2 Ok(format!( "{}-{:02}-{}", parts[2], parse_month(parts[0])?, parts[1] )) } else if parts.len() == 2 { // 2. Month Year Ok(format!("{}-{:02}", parts[1], parse_month(parts[0])?)) } else if parts.len() == 1 { // 3. Year Ok(parts[0].to_string()) } else { unreachable!() }; } pub(crate) fn parse_multi_language(node: &Node) -> MultiLanguageString { let mut title = MultiLanguageString::default(); for node in node.find(Attr("class", "albumtitle")) { let language = node.attr("lang").unwrap(); let mut text = String::new(); recur(&node, &mut text); fn recur(node: &Node, string: &mut String) { if let Some(text) = node.as_text() { string.push_str(text); } else if let Some("em") = node.name() { return; } for child in node.children() { recur(&child, string) } } title.insert(language.to_string(), text); } title } #[cfg(test)] mod test { #[test] fn normal_dates() { assert_eq!(super::parse_date("Aug 13, 2006").unwrap(), "2006-08-13"); assert_eq!(super::parse_date("Sep 29, 2021").unwrap(), "2021-09-29"); assert_eq!(super::parse_date("Jul 12, 2016").unwrap(), "2016-07-12"); assert_eq!(super::parse_date("Jul 2017").unwrap(), "2017-07"); assert_eq!(super::parse_date("2014").unwrap(), "2014"); } }
use std::convert::{AsMut, AsRef, From, Into}; use std::mem; use std::ptr; use crate::base::allocator::Allocator; use crate::base::dimension::{U1, U2, U3, U4}; use crate::base::storage::{ContiguousStorage, ContiguousStorageMut, Storage, StorageMut}; use crate::base::{DefaultAllocator, Matrix, OMatrix, Scalar}; macro_rules! impl_from_into_mint_1D( ($($NRows: ident => $VT:ident [$SZ: expr]);* $(;)*) => {$( impl<T> From<mint::$VT<T>> for OMatrix<T, $NRows, U1> where T: Scalar, DefaultAllocator: Allocator<T, $NRows, U1> { #[inline] fn from(v: mint::$VT<T>) -> Self { unsafe { let mut res = Self::new_uninitialized(); ptr::copy_nonoverlapping(&v.x, (*res.as_mut_ptr()).data.ptr_mut(), $SZ); res.assume_init() } } } impl<T, S> Into<mint::$VT<T>> for Matrix<T, $NRows, U1, S> where T: Scalar, S: ContiguousStorage<T, $NRows, U1> { #[inline] fn into(self) -> mint::$VT<T> { unsafe { let mut res: mint::$VT<T> = mem::MaybeUninit::uninit().assume_init(); ptr::copy_nonoverlapping(self.data.ptr(), &mut res.x, $SZ); res } } } impl<T, S> AsRef<mint::$VT<T>> for Matrix<T, $NRows, U1, S> where T: Scalar, S: ContiguousStorage<T, $NRows, U1> { #[inline] fn as_ref(&self) -> &mint::$VT<T> { unsafe { mem::transmute(self.data.ptr()) } } } impl<T, S> AsMut<mint::$VT<T>> for Matrix<T, $NRows, U1, S> where T: Scalar, S: ContiguousStorageMut<T, $NRows, U1> { #[inline] fn as_mut(&mut self) -> &mut mint::$VT<T> { unsafe { mem::transmute(self.data.ptr_mut()) } } } )*} ); // Implement for vectors of dimension 2 .. 4. impl_from_into_mint_1D!( U2 => Vector2[2]; U3 => Vector3[3]; U4 => Vector4[4]; ); macro_rules! impl_from_into_mint_2D( ($(($NRows: ty, $NCols: ty) => $MV:ident{ $($component:ident),* }[$SZRows: expr]);* $(;)*) => {$( impl<T> From<mint::$MV<T>> for OMatrix<T, $NRows, $NCols> where T: Scalar, DefaultAllocator: Allocator<T, $NRows, $NCols> { #[inline] fn from(m: mint::$MV<T>) -> Self { unsafe { let mut res = Self::new_uninitialized(); let mut ptr = (*res.as_mut_ptr()).data.ptr_mut(); $( ptr::copy_nonoverlapping(&m.$component.x, ptr, $SZRows); ptr = ptr.offset($SZRows); )* let _ = ptr; res.assume_init() } } } impl<T> Into<mint::$MV<T>> for OMatrix<T, $NRows, $NCols> where T: Scalar, DefaultAllocator: Allocator<T, $NRows, $NCols> { #[inline] fn into(self) -> mint::$MV<T> { unsafe { let mut res: mint::$MV<T> = mem::MaybeUninit::uninit().assume_init(); let mut ptr = self.data.ptr(); $( ptr::copy_nonoverlapping(ptr, &mut res.$component.x, $SZRows); ptr = ptr.offset($SZRows); )* let _ = ptr; res } } } )*} ); // Implement for matrices with shape 2x2 .. 4x4. impl_from_into_mint_2D!( (U2, U2) => ColumnMatrix2{x, y}[2]; (U2, U3) => ColumnMatrix2x3{x, y, z}[2]; (U3, U3) => ColumnMatrix3{x, y, z}[3]; (U3, U4) => ColumnMatrix3x4{x, y, z, w}[3]; (U4, U4) => ColumnMatrix4{x, y, z, w}[4]; );
$NetBSD: patch-vendor_target-lexicon_src_targets.rs,v 1.10 2023/07/10 12:01:24 he Exp $ Add aarch64_eb, mipsel and riscv64gc for NetBSD. --- vendor/target-lexicon/src/targets.rs.orig 2021-05-03 21:35:46.000000000 +0000 +++ vendor/target-lexicon/src/targets.rs @@ -1357,6 +1357,7 @@ mod tests { "aarch64-unknown-linux-gnu_ilp32", "aarch64-unknown-linux-musl", "aarch64-unknown-netbsd", + "aarch64_be-unknown-netbsd", "aarch64-unknown-none", "aarch64-unknown-none-softfloat", "aarch64-unknown-openbsd", @@ -1441,6 +1442,7 @@ mod tests { "mipsel-unknown-linux-gnu", "mipsel-unknown-linux-musl", "mipsel-unknown-linux-uclibc", + "mipsel-unknown-netbsd", "mipsel-unknown-none", "mipsisa32r6el-unknown-linux-gnu", "mipsisa32r6-unknown-linux-gnu", @@ -1478,6 +1480,7 @@ mod tests { "riscv64gc-unknown-freebsd", "riscv64gc-unknown-linux-gnu", "riscv64gc-unknown-linux-musl", + "riscv64gc-unknown-netbsd", "riscv64gc-unknown-none-elf", "riscv64gc-unknown-openbsd", "riscv64imac-unknown-none-elf",
use gltf; use render::Node; use render::math::*; use shader::Shader; pub struct Scene { pub name: Option<String>, pub nodes: Vec<Node>, } impl Scene { pub fn from_gltf(g_scene: gltf::scene::Scene) -> Scene { Scene { // TODO! name: None, //g_scene.name().map(|s| s.into()), nodes: g_scene.nodes().map(Node::from_gltf).collect() } } // TODO!: flatten draw call hierarchy (global Vec<Primitive>?) pub fn draw(&self, shader: &Shader) { let model_matrix = Matrix4::identity(); for node in &self.nodes { node.draw(shader, &model_matrix); } } }
use log::debug; use serde::{Serialize,Deserialize}; use crate::{ParticipantId, ParticipantKey, Participant, rand, total_stakes2, ParticipantIdx}; use std::collections::HashMap; pub type Id = u32; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Slot { pub id:Id, pub leader:ParticipantKey, committee:Vec<ParticipantId> } impl Slot { pub fn get_committee(&self) -> &Vec<ParticipantId> { &self.committee } pub fn new(idx:usize, bypass:&mut HashMap<ParticipantIdx,()>,participants:&mut Vec<Participant>, committee_size:usize, btc_hash:Vec<u8>) -> Self { let committee = random_committee(idx,bypass, participants, committee_size, btc_hash ); Slot { id: idx as u32, leader: participants[idx].key , committee } } } pub fn random_committee(slot_idx:usize, // a flag to bypass participants that had already acted as signers bypass: &mut HashMap<ParticipantIdx, ()>, participants:&mut Vec<Participant>, committee_size:usize, btc_hash:Vec<u8>) -> Vec<ParticipantId> { let mut committee: Vec<ParticipantId> = vec![]; let mut curr_bypass: HashMap<ParticipantIdx, ()> = HashMap::new(); let slot_id = slot_idx as u32; // function to loop over participants as signers let to_iterate = |bypass_idx:&HashMap<ParticipantIdx,()>, pcpants:&Vec<Participant>| { pcpants.iter().enumerate().filter_map(|(idx, p)| { if !bypass_idx.contains_key(&idx) && idx != slot_idx { Some((idx, p.weight)) } else { None } } ).collect() }; let mut pcpants:Vec<(ParticipantIdx, u32)> = to_iterate(bypass,participants); let mut total:u32 = pcpants.iter().map(|(_,y)| *y).sum(); let mut rnd = rand(slot_idx as u8, btc_hash.clone(), total ); while committee.len() < committee_size { // all participants have been signers; refresh the bypass flag if pcpants.is_empty() { bypass.drain(); bypass.extend( curr_bypass.iter()); curr_bypass = HashMap::new(); pcpants = to_iterate(bypass,participants); total = pcpants.iter().map(|(_,y)| *y).sum(); rnd = rand(slot_idx as u8, btc_hash.clone(), total); } pcpants.retain(|(participant_idx, weight)| { if committee.len() == committee_size { false } else if weight >= &rnd { let p = &mut participants[*participant_idx]; // current participant is a signer for current slot. p.add_signer_slot(slot_id); // bypass this index, to give other participants a chance to be signers. curr_bypass.insert(*participant_idx,()); committee.push(p.id); // deduct the current participants's position total -= weight; // recalculate the random number rnd = rand(slot_id as u8, btc_hash.clone(), total); false } else { rnd -= weight; true } }); } // concatenate the new participants to bypass bypass.extend(curr_bypass.iter()); committee }