text
stringlengths
8
4.13M
//! This crate includes the compiled python bytecode of the RustPython standard library. The most //! common way to use this crate is to just add the `"freeze-stdlib"` feature to `rustpython-vm`, //! in order to automatically include the python part of the standard library into the binary. // windows needs to read the symlink out of `Lib` as git turns it into a text file, // so build.rs sets this env var pub const LIB_PATH: &str = match option_env!("win_lib_path") { Some(s) => s, None => concat!(env!("CARGO_MANIFEST_DIR"), "/Lib"), }; #[cfg(feature = "freeze-stdlib")] pub const FROZEN_STDLIB: &rustpython_compiler_core::frozen::FrozenLib = rustpython_derive::py_freeze!(dir = "./Lib", crate_name = "rustpython_compiler_core");
#[macro_export] macro_rules! check_value { ($block: expr, $key: expr) => { check_none!($block, $key); check_off!($block, $key); }; } #[macro_export] macro_rules! check_none { ($block: expr, $key: expr) => { match $block.get($key) { Some(d) => { if d.is_block() { if d.to_block().directives().is_empty() { return Setting::None; } } } None => { return Setting::None; } } }; ($block: expr, $key: expr, $default: expr) => { match $block.get($key) { Some(d) => { if d.is_block() { if d.to_block().directives().is_empty() { return Setting::Value($default); } } } None => { return Setting::Value($default); } } }; } #[macro_export] macro_rules! check_off { ($block: expr, $key: expr) => { if let Some(val) = $block.get($key) { if val.is_off() { return Setting::Off; } } }; } #[derive(Debug, Clone)] pub enum Setting<T> { None, Off, Value(T), } impl<T> Setting<T> { pub fn is_value(&self) -> bool { matches!(self, Setting::Value(_)) } pub fn is_none(&self) -> bool { matches!(self, Setting::None) } pub fn is_off(&self) -> bool { matches!(self, Setting::Off) } pub fn into_value(self) -> T { match self { Setting::Value(val) => val, _ => panic!("into_value"), } } } impl<T> Default for Setting<T> { fn default() -> Self { Setting::None } } impl<T: Default> Setting<T> { pub fn unwrap_or_default(self) -> T { match self { Setting::Value(x) => x, _ => Default::default(), } } }
use crate::entities::Item; use crate::game_event::GameEventType; use crate::room::RoomType; use crate::sound::AudioEvent; pub enum ActionHandled { Handled, NotHandled, } #[derive(Debug, PartialEq, Eq, Hash, Clone, Display)] pub enum Action { // System Actions. Tick(u64), Message(String, GameEventType), Command(String), PlayerFinishedReading, GameOver, // Player Attack, Dodge, PickUp(Item), Enter(RoomType), Leave(RoomType), // Enemy attack EnemyAttack, // Audio things Audio(AudioEvent), //Pickup PickUpKeycard, PickUpCrowbar, // Game logic actions PlayerDied, UseDoor, UseKeycard, UseCrowbar, UseCasket, UseTerminal, // Open Rooms OpenCorridor, OpenCryoControl, ShowEnterText, Rebooted, }
mod pushable; pub use self::pushable::Pushable;
use crate::bindings::*; use crate::core::*; use crate::http::status::*; use std::ptr; use std::os::raw::c_void; #[macro_export] macro_rules! http_request_handler { ( $x: ident, $y: expr ) => { #[no_mangle] extern "C" fn $x(r: *mut ngx_http_request_t) -> ngx_int_t { let status: Status = $y(unsafe { &mut $crate::http::Request::from_ngx_http_request(r) }); status.0 } }; } pub struct Request(*mut ngx_http_request_t); impl Request { pub unsafe fn from_ngx_http_request(r: *mut ngx_http_request_t) -> Request { Request(r) } pub fn is_main(&self) -> bool { self.0 == unsafe { (*self.0).main } } pub fn pool(&self) -> Pool { unsafe { Pool::from_ngx_pool((*self.0).pool) } } pub fn connection(&self) -> *mut ngx_connection_t { unsafe { (*self.0).connection } } pub fn get_module_loc_conf(&self, module: &ngx_module_t) -> *mut c_void { unsafe { *(*self.0).loc_conf.add(module.ctx_index) } } pub fn get_complex_value(&self, cv: &mut ngx_http_complex_value_t) -> Option<NgxStr> { let mut res = ngx_str_t { len: 0, data: ptr::null_mut() }; unsafe { if ngx_http_complex_value(self.0, cv, &mut res) != NGX_OK as ngx_int_t { return None; } Some(NgxStr::from_ngx_str(res)) } } pub fn discard_request_body(&mut self) -> Status { Status(unsafe { ngx_http_discard_request_body(self.0) }) } pub fn user_agent(&self) -> NgxStr { unsafe { NgxStr::from_ngx_str((*(*self.0).headers_in.user_agent).value) } } pub fn set_status(&mut self, status: HTTPStatus) { unsafe { (*self.0).headers_out.status = status.into(); } } pub fn set_content_length_n(&mut self, n: usize) { unsafe { (*self.0).headers_out.content_length_n = n as off_t; } } pub fn send_header(&self) -> Status { Status(unsafe { ngx_http_send_header(self.0) }) } pub fn set_header_only(&self) -> bool { unsafe { (*self.0).header_only() != 0 } } pub fn output_filter(&mut self, body: &mut ngx_chain_t) -> Status { Status(unsafe { ngx_http_output_filter(self.0, body) }) } }
use std::cell::RefCell; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use crate::config::Config; use crate::exts::LockIt; use crate::signals::order::{ dev_mgmt::{SessionManager, CAPS_MANAGER}, server_actions::SendData, }; use crate::tts::{Gender, Tts, TtsData, TtsFactory, VoiceDescr}; use anyhow::Result; use bytes::Bytes; use lily_common::{audio::Audio, communication::*, vars::DEFAULT_SAMPLES_PER_SECOND}; use log::{error, info, warn}; use rmp_serde::{decode, encode}; use rumqttc::{AsyncClient, QoS}; use tokio::sync::mpsc; use unic_langid::LanguageIdentifier; thread_local! { pub static MSG_OUTPUT: RefCell<Option<MqttInterfaceOutput>> = RefCell::new(None); } pub struct MqttInterfaceIn {} impl MqttInterfaceIn { pub fn new() -> Self { Self {} } pub async fn handle_new_sattelite( &mut self, payload: &Bytes, config: &Config, client: &Arc<Mutex<AsyncClient>>, ) -> Result<()> { info!("New satellite incoming"); let input: MsgNewSatellite = decode::from_read(std::io::Cursor::new(payload))?; let uuid2 = &input.uuid; let caps = input.caps; CAPS_MANAGER.with(|c| c.borrow_mut().add_client(uuid2, caps)); let output = encode::to_vec(&MsgWelcome { conf: config.to_client_conf(), satellite: input.uuid, })?; Ok(client .lock_it() .publish("lily/satellite_welcome", QoS::AtMostOnce, false, output) .await?) } pub async fn handle_nlu_process( &mut self, payload: &Bytes, channel_nlu: &mpsc::Sender<MsgRequest>, ) -> Result<()> { let msg_nlu: MsgRequest = decode::from_read(std::io::Cursor::new(payload))?; Ok(channel_nlu.send(msg_nlu).await?) } pub async fn handle_event( &mut self, payload: &Bytes, channel_event: &mpsc::Sender<MsgEvent>, ) -> Result<()> { let msg: MsgEvent = decode::from_read(std::io::Cursor::new(payload))?; Ok(channel_event.send(msg).await?) } pub async fn handle_disconnected(&mut self, payload: &Bytes) -> Result<()> { let msg: MsgGoodbye = decode::from_read(std::io::Cursor::new(payload))?; // This error has nothing to do with connection, shouldn't break it if let Err(e) = CAPS_MANAGER.with(|c| c.borrow_mut().disconnected(&msg.satellite)) { warn!("{}", &e.to_string()) } Ok(()) } pub async fn subscribe(client: &Arc<Mutex<AsyncClient>>) -> Result<()> { let client_raw = client.lock_it(); client_raw .subscribe("lily/new_satellite", QoS::AtMostOnce) .await?; client_raw .subscribe("lily/nlu_process", QoS::AtMostOnce) .await?; client_raw.subscribe("lily/event", QoS::AtMostOnce).await?; client_raw .subscribe("lily/disconnected", QoS::ExactlyOnce) .await?; Ok(()) } } pub struct MqttInterfaceOut { common_out: mpsc::Receiver<(SendData, String)>, } impl MqttInterfaceOut { pub fn new() -> Result<Self> { let (sender, common_out) = mpsc::channel(100); let output = MqttInterfaceOutput::create(sender)?; MSG_OUTPUT.with(|a| a.replace(Some(output))); Ok(Self { common_out }) } pub async fn handle_out( &mut self, curr_langs: &[LanguageIdentifier], conf_tts: &TtsData, def_lang: Option<&LanguageIdentifier>, sessions: Arc<Mutex<SessionManager>>, client: &Arc<Mutex<AsyncClient>>, ) -> Result<()> { let voice_prefs: VoiceDescr = VoiceDescr { gender: if conf_tts.prefer_male { Gender::Male } else { Gender::Female }, }; let mut tts_set = HashMap::new(); for lang in curr_langs { let tts = TtsFactory::load_with_prefs( lang, conf_tts.prefer_online, conf_tts.ibm.clone(), &voice_prefs, )?; info!("Using tts {}", tts.get_info()); tts_set.insert(lang, tts); } loop { let (msg_data, uuid_str) = self.common_out.recv().await.expect("Out channel broken"); Self::process_out( msg_data, uuid_str, &mut tts_set, &def_lang, &sessions, client, ) .await?; } } async fn process_out( msg_data: SendData, uuid_str: String, tts_set: &mut HashMap<&LanguageIdentifier, Box<dyn Tts>>, def_lang: &Option<&LanguageIdentifier>, sessions: &Arc<Mutex<SessionManager>>, client: &Arc<Mutex<AsyncClient>>, ) -> Result<()> { let audio_data = match msg_data { SendData::Audio(audio) => audio, SendData::String((str, lang)) => { async fn synth_text(tts: &mut Box<dyn Tts>, input: &str) -> Audio { match tts.synth_text(input).await { Ok(a) => a, Err(e) => { error!("Error while synthing voice: {}", e); Audio::new_empty(DEFAULT_SAMPLES_PER_SECOND) } } } match tts_set.get_mut(&lang) { Some(tts) => synth_text(tts, &str).await, None => { warn!("Received answer for language {:?} not in the config or that has no TTS, using default", lang); let def = def_lang .expect("There's no language assigned, need one at least"); match tts_set.get_mut(def) { Some(tts) => synth_text(tts, &str).await, None => { warn!("Default has no tts either, sending empty audio"); Audio::new_empty(DEFAULT_SAMPLES_PER_SECOND) } } } } } }; if let Err(e) = sessions.lock().expect("POISON_MSG").end_session(&uuid_str) { warn!("{}", e); } let msg_pack = encode::to_vec(&MsgAnswer { audio: Some(audio_data.into_encoded()?), text: None, })?; client .lock_it() .publish( &format!("lily/{}/say_msg", uuid_str), QoS::AtMostOnce, false, msg_pack, ) .await?; Ok(()) } } pub struct MqttInterfaceOutput { client: mpsc::Sender<(SendData, String)>, } impl MqttInterfaceOutput { fn create(client: mpsc::Sender<(SendData, String)>) -> Result<Self> { Ok(Self { client }) } pub fn answer(&mut self, input: String, lang: &LanguageIdentifier, to: String) -> Result<()> { self.client .try_send((SendData::String((input, lang.to_owned())), to)) .unwrap(); Ok(()) } pub fn send_audio(&mut self, audio: Audio, to: String) -> Result<()> { self.client.try_send((SendData::Audio(audio), to)).unwrap(); Ok(()) } }
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fuchsia_async as fasync, fuchsia_cobalt::{CobaltConnector, CobaltSender, ConnectionType}, time_metrics_registry::{ RealTimeClockEventsMetricDimensionEventType as RtcEventType, TimekeeperLifecycleEventsMetricDimensionEventType as LifecycleEventType, REAL_TIME_CLOCK_EVENTS_METRIC_ID, TIMEKEEPER_LIFECYCLE_EVENTS_METRIC_ID, }, }; /// A collection of convenience functions for logging time metrics to Cobalt. pub trait CobaltDiagnostics { /// Records a Timekeeper lifecycle event. fn log_lifecycle_event(&mut self, event_type: LifecycleEventType); /// Records an RTC interaction event. fn log_rtc_event(&mut self, event_type: RtcEventType); } /// A connection to the real Cobalt service. pub struct CobaltDiagnosticsImpl { /// The wrapped CobaltSender used to log metrics. sender: CobaltSender, // TODO(57677): Move back to an owned fasync::Task instead of detaching the spawned Task // once the lifecycle of timekeeper ensures CobaltDiagnostics objects will last long enough // to finish their logging. } impl CobaltDiagnosticsImpl { /// Contructs a new CobaltDiagnostics instance. pub fn new() -> Self { let (sender, fut) = CobaltConnector::default() .serve(ConnectionType::project_id(time_metrics_registry::PROJECT_ID)); fasync::Task::spawn(fut).detach(); Self { sender } } } impl CobaltDiagnostics for CobaltDiagnosticsImpl { fn log_lifecycle_event(&mut self, event_type: LifecycleEventType) { self.sender.log_event(TIMEKEEPER_LIFECYCLE_EVENTS_METRIC_ID, event_type); } fn log_rtc_event(&mut self, event_type: RtcEventType) { self.sender.log_event(REAL_TIME_CLOCK_EVENTS_METRIC_ID, event_type); } } #[cfg(test)] mod test { use { super::*, fidl_fuchsia_cobalt::{CobaltEvent, Event, EventPayload}, futures::StreamExt, }; #[fasync::run_until_stalled(test)] async fn log_events() { let (mpsc_sender, mut mpsc_receiver) = futures::channel::mpsc::channel(1); let sender = CobaltSender::new(mpsc_sender); let mut diagnostics = CobaltDiagnosticsImpl { sender }; diagnostics.log_lifecycle_event(LifecycleEventType::InitializedBeforeUtcStart); assert_eq!( mpsc_receiver.next().await, Some(CobaltEvent { metric_id: time_metrics_registry::TIMEKEEPER_LIFECYCLE_EVENTS_METRIC_ID, event_codes: vec![LifecycleEventType::InitializedBeforeUtcStart as u32], component: None, payload: EventPayload::Event(Event), }) ); diagnostics.log_rtc_event(RtcEventType::ReadFailed); assert_eq!( mpsc_receiver.next().await, Some(CobaltEvent { metric_id: time_metrics_registry::REAL_TIME_CLOCK_EVENTS_METRIC_ID, event_codes: vec![RtcEventType::ReadFailed as u32], component: None, payload: EventPayload::Event(Event), }) ); } } /// Defines a fake implementation of `CobaltDiagnostics` and a monitor to verify interactions. #[cfg(test)] pub mod fake { use { super::*, std::sync::{Arc, Mutex}, }; /// The data shared between a `FakeCobaltDiagnostics` and the associated `FakeCobaltMonitor`. struct Data { /// An ordered list of the lifecycle events received since the last reset. lifecycle_events: Vec<LifecycleEventType>, /// An ordered list of the RTC events received since the last reset. rtc_events: Vec<RtcEventType>, } /// A fake implementation of `CobaltDiagnostics` that allows for easy unit testing via an /// associated `FakeCobaltMonitor`. /// /// Note: This uses std::sync::Mutex to synchronize access between the diagnostics and monitor /// from synchronous methods. If used in combination with asynchronous code on a multithreaded /// executor this could potentially deadlock. If this becomes a problems we could switch to an /// mpsc communication model similar to the real implementation. pub struct FakeCobaltDiagnostics { data: Arc<Mutex<Data>>, } impl FakeCobaltDiagnostics { /// Constructs a new `FakeCobaltDiagnostics`/`FakeCobaltMonitor` pair. pub fn new() -> (Self, FakeCobaltMonitor) { let data = Arc::new(Mutex::new(Data { lifecycle_events: vec![], rtc_events: vec![] })); (FakeCobaltDiagnostics { data: Arc::clone(&data) }, FakeCobaltMonitor { data }) } } impl CobaltDiagnostics for FakeCobaltDiagnostics { fn log_lifecycle_event(&mut self, event_type: LifecycleEventType) { let mut data = self.data.lock().expect("Error aquiring mutex"); data.lifecycle_events.push(event_type); } fn log_rtc_event(&mut self, event_type: RtcEventType) { let mut data = self.data.lock().expect("Error aquiring mutex"); data.rtc_events.push(event_type); } } /// A monitor to verify interactions with an associated `FakeCobaltDiagnostics`. pub struct FakeCobaltMonitor { data: Arc<Mutex<Data>>, } impl FakeCobaltMonitor { /// Clears all recorded interactions. pub fn reset(&mut self) { let mut data = self.data.lock().expect("Error aquiring mutex"); data.lifecycle_events.clear(); data.rtc_events.clear(); } /// Panics if the supplied slice does not match the received lifecycle events. pub fn assert_lifecycle_events(&self, expected: &[LifecycleEventType]) { assert_eq!(self.data.lock().expect("Error aquiring mutex").lifecycle_events, expected); } /// Panics if the supplied slice does not match the received RTC events. pub fn assert_rtc_events(&self, expected: &[RtcEventType]) { assert_eq!(self.data.lock().expect("Error aquiring mutex").rtc_events, expected); } } #[cfg(test)] mod test { use super::*; #[test] fn log_and_reset_lifecycle_events() { let (mut diagnostics, mut monitor) = FakeCobaltDiagnostics::new(); monitor.assert_lifecycle_events(&[]); diagnostics.log_lifecycle_event(LifecycleEventType::ReadFromStash); monitor.assert_lifecycle_events(&[LifecycleEventType::ReadFromStash]); diagnostics.log_lifecycle_event(LifecycleEventType::StartedUtcFromTimeSource); monitor.assert_lifecycle_events(&[ LifecycleEventType::ReadFromStash, LifecycleEventType::StartedUtcFromTimeSource, ]); monitor.reset(); monitor.assert_lifecycle_events(&[]); diagnostics.log_lifecycle_event(LifecycleEventType::ReadFromStash); monitor.assert_lifecycle_events(&[LifecycleEventType::ReadFromStash]); } #[test] fn log_and_reset_rtc_events() { let (mut diagnostics, mut monitor) = FakeCobaltDiagnostics::new(); monitor.assert_rtc_events(&[]); diagnostics.log_rtc_event(RtcEventType::ReadFailed); monitor.assert_rtc_events(&[RtcEventType::ReadFailed]); diagnostics.log_rtc_event(RtcEventType::ReadSucceeded); monitor.assert_rtc_events(&[RtcEventType::ReadFailed, RtcEventType::ReadSucceeded]); monitor.reset(); monitor.assert_rtc_events(&[]); diagnostics.log_rtc_event(RtcEventType::ReadFailed); monitor.assert_rtc_events(&[RtcEventType::ReadFailed]); } } }
/* * Copyright 2020 Fluence Labs Limited * * 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. */ #![recursion_limit = "512"] #![warn(rust_2018_idioms)] #![deny( dead_code, nonstandard_style, unused_imports, unused_mut, unused_variables, unused_unsafe, unreachable_patterns )] use async_std::task; use ctrlc_adapter::block_until_ctrlc; use faas_api::{relay, service, FunctionCall}; use fluence_client::{Client, ClientCommand, ClientEvent}; use futures::{ channel::{mpsc, mpsc::UnboundedReceiver, oneshot}, prelude::*, select, stream::StreamExt, }; use libp2p::PeerId; use parity_multiaddr::Multiaddr; use std::error::Error; use std::time::Duration; fn main() -> Result<(), Box<dyn Error>> { env_logger::builder().format_timestamp_micros().init(); let relay_addr: Multiaddr = std::env::args() .nth(1) .expect("multiaddr of relay peer should be provided by the first argument") .parse() .expect("provided wrong Multiaddr"); let (exit_sender, exit_receiver) = oneshot::channel::<()>(); let client_task = task::spawn(async move { run_client(exit_receiver, relay_addr) .await .expect("Error running client"); // TODO: handle errors }); block_until_ctrlc(); exit_sender .send(()) .expect("send exit signal to client task"); task::block_on(client_task); Ok(()) } async fn run_client( exit_receiver: oneshot::Receiver<()>, relay: Multiaddr, ) -> Result<(), Box<dyn Error>> { let client = Client::connect(relay); let (mut client, client_task) = client.await?; let stdin_cmds = read_cmds_from_stdin(); let mut stdin_cmds = stdin_cmds.into_stream().fuse(); let mut stop = exit_receiver.into_stream().fuse(); loop { select!( cmd = stdin_cmds.select_next_some() => { match cmd { Ok(cmd) => { client.send(cmd); print!("\n"); }, Err(e) => println!("incorrect string provided: {:?}", e) } }, incoming = client.receive_one() => { match incoming { Some(ClientEvent::NewConnection{ peer_id, ..}) => { log::info!("Connected to {}", peer_id); print_example(&client.peer_id, peer_id); } Some(msg) => println!("Received\n{}\n", serde_json::to_string_pretty(&msg).unwrap()), None => { println!("Client closed"); break; } } }, _ = stop.next() => { client.stop(); break; } ) } client_task.await; Ok(()) } // TODO: it's not clear how and why this all works, so it is possible // that it would BLOCK ALL THE FUTURES in the executor, so // BE CAREFUL fn read_cmds_from_stdin() -> UnboundedReceiver<serde_json::error::Result<ClientCommand>> { let (cmd_sender, cmd_recv) = mpsc::unbounded(); task::spawn(async move { use serde_json::Deserializer; use std::io; // NOTE: this is synchronous IO loop { let stdin = io::BufReader::new(io::stdin()); let stream = Deserializer::from_reader(stdin).into_iter::<ClientCommand>(); // blocking happens in 'for' below for cmd in stream { cmd_sender.unbounded_send(cmd).expect("send cmd"); task::sleep(Duration::from_nanos(10)).await; // return Poll::Pending from future's fn poll } } }); cmd_recv } fn print_example(peer_id: &PeerId, bootstrap: PeerId) { use serde_json::json; use std::time::SystemTime; fn show(cmd: ClientCommand) { println!("{}", serde_json::to_string_pretty(&cmd).unwrap()); } fn uuid() -> String { uuid::Uuid::new_v4().to_string() } let time = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_millis() .to_string(); let call_multiaddr = ClientCommand::Call { node: bootstrap.clone(), call: FunctionCall { uuid: uuid(), target: Some(service!("IPFS.multiaddr")), reply_to: Some(relay!(bootstrap.clone(), peer_id.clone())), arguments: json!({ "hash": "QmFile", "msg_id": time }), name: Some("call multiaddr".to_string()), }, }; let register_ipfs_get = ClientCommand::Call { node: bootstrap.clone(), call: FunctionCall { uuid: uuid(), target: Some(service!("provide")), reply_to: Some(relay!(bootstrap.clone(), peer_id.clone())), arguments: json!({ "service_id": "IPFS.get_QmFile3", "msg_id": time }), name: Some("register service".to_string()), }, }; let call_ipfs_get = ClientCommand::Call { node: bootstrap.clone(), call: FunctionCall { uuid: uuid(), target: Some(service!("IPFS.get_QmFile3")), reply_to: Some(relay!(bootstrap, peer_id.clone())), arguments: serde_json::Value::Null, name: Some("call ipfs get".to_string()), }, }; println!("Possible messages:"); println!("\n### call IPFS.multiaddr"); show(call_multiaddr); println!("\n### Register IPFS.get service"); show(register_ipfs_get); println!("\n### Call IPFS.get service"); show(call_ipfs_get); println!("\n") }
use rwm::config::Config; use rwm::manager::Manager; use simple_logger; use rwm::displays::xcb_server::XcbDisplayServer; #[tokio::main] async fn main() { simple_logger::init().unwrap(); Manager::<XcbDisplayServer>::new(Config::new()).stream().await; }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCN_NOTIFICATIONS(pub i32); pub const HcnNotificationInvalid: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(0i32); pub const HcnNotificationNetworkPreCreate: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(1i32); pub const HcnNotificationNetworkCreate: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(2i32); pub const HcnNotificationNetworkPreDelete: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(3i32); pub const HcnNotificationNetworkDelete: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(4i32); pub const HcnNotificationNamespaceCreate: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(5i32); pub const HcnNotificationNamespaceDelete: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(6i32); pub const HcnNotificationGuestNetworkServiceCreate: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(7i32); pub const HcnNotificationGuestNetworkServiceDelete: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(8i32); pub const HcnNotificationNetworkEndpointAttached: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(9i32); pub const HcnNotificationNetworkEndpointDetached: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(16i32); pub const HcnNotificationGuestNetworkServiceStateChanged: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(17i32); pub const HcnNotificationGuestNetworkServiceInterfaceStateChanged: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(18i32); pub const HcnNotificationServiceDisconnect: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(16777216i32); pub const HcnNotificationFlagsReserved: HCN_NOTIFICATIONS = HCN_NOTIFICATIONS(-268435456i32); impl ::core::convert::From<i32> for HCN_NOTIFICATIONS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCN_NOTIFICATIONS { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] pub type HCN_NOTIFICATION_CALLBACK = unsafe extern "system" fn(notificationtype: u32, context: *const ::core::ffi::c_void, notificationstatus: ::windows::core::HRESULT, notificationdata: super::super::Foundation::PWSTR); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCN_PORT_ACCESS(pub i32); pub const HCN_PORT_ACCESS_EXCLUSIVE: HCN_PORT_ACCESS = HCN_PORT_ACCESS(1i32); pub const HCN_PORT_ACCESS_SHARED: HCN_PORT_ACCESS = HCN_PORT_ACCESS(2i32); impl ::core::convert::From<i32> for HCN_PORT_ACCESS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCN_PORT_ACCESS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCN_PORT_PROTOCOL(pub i32); pub const HCN_PORT_PROTOCOL_TCP: HCN_PORT_PROTOCOL = HCN_PORT_PROTOCOL(1i32); pub const HCN_PORT_PROTOCOL_UDP: HCN_PORT_PROTOCOL = HCN_PORT_PROTOCOL(2i32); pub const HCN_PORT_PROTOCOL_BOTH: HCN_PORT_PROTOCOL = HCN_PORT_PROTOCOL(3i32); impl ::core::convert::From<i32> for HCN_PORT_PROTOCOL { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCN_PORT_PROTOCOL { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct HCN_PORT_RANGE_ENTRY { pub OwningPartitionId: ::windows::core::GUID, pub TargetPartitionId: ::windows::core::GUID, pub Protocol: HCN_PORT_PROTOCOL, pub Priority: u64, pub ReservationType: u32, pub SharingFlags: u32, pub DeliveryMode: u32, pub StartingPort: u16, pub EndingPort: u16, } impl HCN_PORT_RANGE_ENTRY {} impl ::core::default::Default for HCN_PORT_RANGE_ENTRY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for HCN_PORT_RANGE_ENTRY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HCN_PORT_RANGE_ENTRY") .field("OwningPartitionId", &self.OwningPartitionId) .field("TargetPartitionId", &self.TargetPartitionId) .field("Protocol", &self.Protocol) .field("Priority", &self.Priority) .field("ReservationType", &self.ReservationType) .field("SharingFlags", &self.SharingFlags) .field("DeliveryMode", &self.DeliveryMode) .field("StartingPort", &self.StartingPort) .field("EndingPort", &self.EndingPort) .finish() } } impl ::core::cmp::PartialEq for HCN_PORT_RANGE_ENTRY { fn eq(&self, other: &Self) -> bool { self.OwningPartitionId == other.OwningPartitionId && self.TargetPartitionId == other.TargetPartitionId && self.Protocol == other.Protocol && self.Priority == other.Priority && self.ReservationType == other.ReservationType && self.SharingFlags == other.SharingFlags && self.DeliveryMode == other.DeliveryMode && self.StartingPort == other.StartingPort && self.EndingPort == other.EndingPort } } impl ::core::cmp::Eq for HCN_PORT_RANGE_ENTRY {} unsafe impl ::windows::core::Abi for HCN_PORT_RANGE_ENTRY { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct HCN_PORT_RANGE_RESERVATION { pub startingPort: u16, pub endingPort: u16, } impl HCN_PORT_RANGE_RESERVATION {} impl ::core::default::Default for HCN_PORT_RANGE_RESERVATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for HCN_PORT_RANGE_RESERVATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HCN_PORT_RANGE_RESERVATION").field("startingPort", &self.startingPort).field("endingPort", &self.endingPort).finish() } } impl ::core::cmp::PartialEq for HCN_PORT_RANGE_RESERVATION { fn eq(&self, other: &Self) -> bool { self.startingPort == other.startingPort && self.endingPort == other.endingPort } } impl ::core::cmp::Eq for HCN_PORT_RANGE_RESERVATION {} unsafe impl ::windows::core::Abi for HCN_PORT_RANGE_RESERVATION { type Abi = Self; } #[inline] pub unsafe fn HcnCloseEndpoint(endpoint: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCloseEndpoint(endpoint: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnCloseEndpoint(::core::mem::transmute(endpoint)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnCloseGuestNetworkService(guestnetworkservice: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCloseGuestNetworkService(guestnetworkservice: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnCloseGuestNetworkService(::core::mem::transmute(guestnetworkservice)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnCloseLoadBalancer(loadbalancer: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCloseLoadBalancer(loadbalancer: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnCloseLoadBalancer(::core::mem::transmute(loadbalancer)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnCloseNamespace(namespace: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCloseNamespace(namespace: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnCloseNamespace(::core::mem::transmute(namespace)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnCloseNetwork(network: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCloseNetwork(network: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnCloseNetwork(::core::mem::transmute(network)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnCreateEndpoint<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(network: *const ::core::ffi::c_void, id: *const ::windows::core::GUID, settings: Param2, endpoint: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCreateEndpoint(network: *const ::core::ffi::c_void, id: *const ::windows::core::GUID, settings: super::super::Foundation::PWSTR, endpoint: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnCreateEndpoint(::core::mem::transmute(network), ::core::mem::transmute(id), settings.into_param().abi(), ::core::mem::transmute(endpoint), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnCreateGuestNetworkService<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(id: *const ::windows::core::GUID, settings: Param1, guestnetworkservice: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCreateGuestNetworkService(id: *const ::windows::core::GUID, settings: super::super::Foundation::PWSTR, guestnetworkservice: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnCreateGuestNetworkService(::core::mem::transmute(id), settings.into_param().abi(), ::core::mem::transmute(guestnetworkservice), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnCreateLoadBalancer<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(id: *const ::windows::core::GUID, settings: Param1, loadbalancer: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCreateLoadBalancer(id: *const ::windows::core::GUID, settings: super::super::Foundation::PWSTR, loadbalancer: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnCreateLoadBalancer(::core::mem::transmute(id), settings.into_param().abi(), ::core::mem::transmute(loadbalancer), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnCreateNamespace<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(id: *const ::windows::core::GUID, settings: Param1, namespace: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCreateNamespace(id: *const ::windows::core::GUID, settings: super::super::Foundation::PWSTR, namespace: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnCreateNamespace(::core::mem::transmute(id), settings.into_param().abi(), ::core::mem::transmute(namespace), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnCreateNetwork<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(id: *const ::windows::core::GUID, settings: Param1, network: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnCreateNetwork(id: *const ::windows::core::GUID, settings: super::super::Foundation::PWSTR, network: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnCreateNetwork(::core::mem::transmute(id), settings.into_param().abi(), ::core::mem::transmute(network), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnDeleteEndpoint(id: *const ::windows::core::GUID) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnDeleteEndpoint(id: *const ::windows::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnDeleteEndpoint(::core::mem::transmute(id), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnDeleteGuestNetworkService(id: *const ::windows::core::GUID) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnDeleteGuestNetworkService(id: *const ::windows::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnDeleteGuestNetworkService(::core::mem::transmute(id), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnDeleteLoadBalancer(id: *const ::windows::core::GUID) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnDeleteLoadBalancer(id: *const ::windows::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnDeleteLoadBalancer(::core::mem::transmute(id), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnDeleteNamespace(id: *const ::windows::core::GUID) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnDeleteNamespace(id: *const ::windows::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnDeleteNamespace(::core::mem::transmute(id), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnDeleteNetwork(id: *const ::windows::core::GUID) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnDeleteNetwork(id: *const ::windows::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnDeleteNetwork(::core::mem::transmute(id), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnEnumerateEndpoints<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(query: Param0, endpoints: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnEnumerateEndpoints(query: super::super::Foundation::PWSTR, endpoints: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnEnumerateEndpoints(query.into_param().abi(), ::core::mem::transmute(endpoints), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnEnumerateGuestNetworkPortReservations(returncount: *mut u32, portentries: *mut *mut HCN_PORT_RANGE_ENTRY) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnEnumerateGuestNetworkPortReservations(returncount: *mut u32, portentries: *mut *mut HCN_PORT_RANGE_ENTRY) -> ::windows::core::HRESULT; } HcnEnumerateGuestNetworkPortReservations(::core::mem::transmute(returncount), ::core::mem::transmute(portentries)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnEnumerateLoadBalancers<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(query: Param0, loadbalancer: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnEnumerateLoadBalancers(query: super::super::Foundation::PWSTR, loadbalancer: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnEnumerateLoadBalancers(query.into_param().abi(), ::core::mem::transmute(loadbalancer), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnEnumerateNamespaces<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(query: Param0, namespaces: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnEnumerateNamespaces(query: super::super::Foundation::PWSTR, namespaces: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnEnumerateNamespaces(query.into_param().abi(), ::core::mem::transmute(namespaces), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnEnumerateNetworks<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(query: Param0, networks: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnEnumerateNetworks(query: super::super::Foundation::PWSTR, networks: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnEnumerateNetworks(query.into_param().abi(), ::core::mem::transmute(networks), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnFreeGuestNetworkPortReservations(portentries: *mut HCN_PORT_RANGE_ENTRY) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnFreeGuestNetworkPortReservations(portentries: *mut HCN_PORT_RANGE_ENTRY); } ::core::mem::transmute(HcnFreeGuestNetworkPortReservations(::core::mem::transmute(portentries))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnModifyEndpoint<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(endpoint: *const ::core::ffi::c_void, settings: Param1) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnModifyEndpoint(endpoint: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnModifyEndpoint(::core::mem::transmute(endpoint), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnModifyGuestNetworkService<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(guestnetworkservice: *const ::core::ffi::c_void, settings: Param1) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnModifyGuestNetworkService(guestnetworkservice: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnModifyGuestNetworkService(::core::mem::transmute(guestnetworkservice), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnModifyLoadBalancer<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(loadbalancer: *const ::core::ffi::c_void, settings: Param1) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnModifyLoadBalancer(loadbalancer: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnModifyLoadBalancer(::core::mem::transmute(loadbalancer), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnModifyNamespace<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(namespace: *const ::core::ffi::c_void, settings: Param1) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnModifyNamespace(namespace: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnModifyNamespace(::core::mem::transmute(namespace), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnModifyNetwork<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(network: *const ::core::ffi::c_void, settings: Param1) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnModifyNetwork(network: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnModifyNetwork(::core::mem::transmute(network), settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnOpenEndpoint(id: *const ::windows::core::GUID, endpoint: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnOpenEndpoint(id: *const ::windows::core::GUID, endpoint: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnOpenEndpoint(::core::mem::transmute(id), ::core::mem::transmute(endpoint), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnOpenLoadBalancer(id: *const ::windows::core::GUID, loadbalancer: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnOpenLoadBalancer(id: *const ::windows::core::GUID, loadbalancer: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnOpenLoadBalancer(::core::mem::transmute(id), ::core::mem::transmute(loadbalancer), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnOpenNamespace(id: *const ::windows::core::GUID, namespace: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnOpenNamespace(id: *const ::windows::core::GUID, namespace: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnOpenNamespace(::core::mem::transmute(id), ::core::mem::transmute(namespace), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnOpenNetwork(id: *const ::windows::core::GUID, network: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnOpenNetwork(id: *const ::windows::core::GUID, network: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnOpenNetwork(::core::mem::transmute(id), ::core::mem::transmute(network), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnQueryEndpointProperties<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(endpoint: *const ::core::ffi::c_void, query: Param1, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnQueryEndpointProperties(endpoint: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnQueryEndpointProperties(::core::mem::transmute(endpoint), query.into_param().abi(), ::core::mem::transmute(properties), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnQueryLoadBalancerProperties<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(loadbalancer: *const ::core::ffi::c_void, query: Param1, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnQueryLoadBalancerProperties(loadbalancer: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnQueryLoadBalancerProperties(::core::mem::transmute(loadbalancer), query.into_param().abi(), ::core::mem::transmute(properties), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnQueryNamespaceProperties<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(namespace: *const ::core::ffi::c_void, query: Param1, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnQueryNamespaceProperties(namespace: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnQueryNamespaceProperties(::core::mem::transmute(namespace), query.into_param().abi(), ::core::mem::transmute(properties), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnQueryNetworkProperties<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(network: *const ::core::ffi::c_void, query: Param1, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnQueryNetworkProperties(network: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcnQueryNetworkProperties(::core::mem::transmute(network), query.into_param().abi(), ::core::mem::transmute(properties), ::core::mem::transmute(errorrecord)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnRegisterGuestNetworkServiceCallback(guestnetworkservice: *const ::core::ffi::c_void, callback: ::core::option::Option<HCN_NOTIFICATION_CALLBACK>, context: *const ::core::ffi::c_void, callbackhandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnRegisterGuestNetworkServiceCallback(guestnetworkservice: *const ::core::ffi::c_void, callback: ::windows::core::RawPtr, context: *const ::core::ffi::c_void, callbackhandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnRegisterGuestNetworkServiceCallback(::core::mem::transmute(guestnetworkservice), ::core::mem::transmute(callback), ::core::mem::transmute(context), ::core::mem::transmute(callbackhandle)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnRegisterServiceCallback(callback: ::core::option::Option<HCN_NOTIFICATION_CALLBACK>, context: *const ::core::ffi::c_void, callbackhandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnRegisterServiceCallback(callback: ::windows::core::RawPtr, context: *const ::core::ffi::c_void, callbackhandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnRegisterServiceCallback(::core::mem::transmute(callback), ::core::mem::transmute(context), ::core::mem::transmute(callbackhandle)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnReleaseGuestNetworkServicePortReservationHandle<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(portreservationhandle: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnReleaseGuestNetworkServicePortReservationHandle(portreservationhandle: super::super::Foundation::HANDLE) -> ::windows::core::HRESULT; } HcnReleaseGuestNetworkServicePortReservationHandle(portreservationhandle.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnReserveGuestNetworkServicePort(guestnetworkservice: *const ::core::ffi::c_void, protocol: HCN_PORT_PROTOCOL, access: HCN_PORT_ACCESS, port: u16) -> ::windows::core::Result<super::super::Foundation::HANDLE> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnReserveGuestNetworkServicePort(guestnetworkservice: *const ::core::ffi::c_void, protocol: HCN_PORT_PROTOCOL, access: HCN_PORT_ACCESS, port: u16, portreservationhandle: *mut super::super::Foundation::HANDLE) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcnReserveGuestNetworkServicePort(::core::mem::transmute(guestnetworkservice), ::core::mem::transmute(protocol), ::core::mem::transmute(access), ::core::mem::transmute(port), &mut result__).from_abi::<super::super::Foundation::HANDLE>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcnReserveGuestNetworkServicePortRange(guestnetworkservice: *const ::core::ffi::c_void, portcount: u16, portrangereservation: *mut HCN_PORT_RANGE_RESERVATION, portreservationhandle: *mut super::super::Foundation::HANDLE) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnReserveGuestNetworkServicePortRange(guestnetworkservice: *const ::core::ffi::c_void, portcount: u16, portrangereservation: *mut HCN_PORT_RANGE_RESERVATION, portreservationhandle: *mut super::super::Foundation::HANDLE) -> ::windows::core::HRESULT; } HcnReserveGuestNetworkServicePortRange(::core::mem::transmute(guestnetworkservice), ::core::mem::transmute(portcount), ::core::mem::transmute(portrangereservation), ::core::mem::transmute(portreservationhandle)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnUnregisterGuestNetworkServiceCallback(callbackhandle: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnUnregisterGuestNetworkServiceCallback(callbackhandle: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnUnregisterGuestNetworkServiceCallback(::core::mem::transmute(callbackhandle)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcnUnregisterServiceCallback(callbackhandle: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcnUnregisterServiceCallback(callbackhandle: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcnUnregisterServiceCallback(::core::mem::transmute(callbackhandle)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
use crate::{common::*, functional::Func}; pub use base::*; pub use ops::*; mod base { // maybe def /// A trait analogous to [Option](std::option::Option). pub trait Maybe {} // just def /// A type analogous to `Some`. pub struct Just<T>(T); impl<T> Maybe for Just<T> {} // nothing def /// A type analogous to `None`. pub struct Nothing; impl Maybe for Nothing {} } mod ops { use super::*; typ! { pub fn Unwrap<value>(Just::<value>: Maybe) { value } pub fn UnwrapOr<maybe, default>(maybe: Maybe, default: _) { match maybe { #[generics(value)] Just::<value> => value, Nothing => default, } } pub fn IsJust<maybe>(maybe: Maybe) -> Bit { match maybe { #[generics(value)] Just::<value> => true, Nothing => false, } } pub fn IsNothing<maybe>(maybe: Maybe) -> Bit { match maybe { #[generics(value)] Just::<value> => false, Nothing => true, } } pub fn Map<maybe, func>(maybe: Maybe, func: _) -> Maybe { match maybe { #[generics(value)] Just::<value> => { let new_value = func.Func(value); Just::<new_value> } Nothing => Nothing } } } } // tests #[cfg(test)] mod tests { // use super::*; // use crate::{ // boolean::Boolean, // control::{IfElsePredicate, IfElsePredicateOutput, IfSameOutput}, // functional::{Applicative, FMap}, // numeric::AddOneMap, // }; // use typenum::{consts::*, GrEq, IsGreaterOrEqual, Unsigned}; // // unwrap // type Opt1 = Just<U3>; // type Opt2 = Nothing; // type SameOp<Lhs, Rhs> = IfSameOutput<(), Lhs, Rhs>; // type Assert1 = SameOp<Unwrap<Opt1>, U3>; // type Assert2 = SameOp<UnwrapOr<Opt1, U0>, U3>; // type Assert3 = SameOp<UnwrapOr<Opt2, U0>, U0>; // // map // struct BoxFunc; // impl<Input> Map<Input> for BoxFunc { // type Output = Box<Input>; // } // type Assert4 = IfSameOutput<(), MaybeMap<Just<i8>, BoxFunc>, Just<Box<i8>>>; // type Assert5 = IfSameOutput<(), MaybeMap<Nothing, BoxFunc>, Nothing>; // // filter // struct ThresholdFunc; // impl<Input> Map<Input> for ThresholdFunc // where // Input: Unsigned + IsGreaterOrEqual<U4>, // GrEq<Input, U4>: Boolean, // Just<Input>: IfElsePredicate<GrEq<Input, U4>, Nothing>, // { // type Output = IfElsePredicateOutput<Just<Input>, GrEq<Input, U4>, Nothing>; // } // type Assert6 = IfSameOutput<(), MaybeFilter<Just<U8>, ThresholdFunc>, Just<U8>>; // type Assert7 = IfSameOutput<(), MaybeFilter<Just<U2>, ThresholdFunc>, Nothing>; // type Assert8 = IfSameOutput<(), MaybeFilter<Nothing, ThresholdFunc>, Nothing>; // // FMap // type Assert9 = IfSameOutput<(), FMap<Nothing, AddOneMap>, Nothing>; // type Assert10 = IfSameOutput<(), FMap<Just<U8>, AddOneMap>, Just<U9>>; // // Applicative // type Assert11 = IfSameOutput<(), Applicative<Nothing, Nothing>, Nothing>; // type Assert12 = IfSameOutput<(), Applicative<Just<AddOneMap>, Nothing>, Nothing>; // type Assert13 = IfSameOutput<(), Applicative<Nothing, Just<U7>>, Nothing>; // type Assert14 = IfSameOutput<(), Applicative<Just<AddOneMap>, Just<U7>>, Just<U8>>; #[test] fn maybe_test() {} }
use bevy::{math::*, prelude::*}; use meshie::Meshie; pub mod systems; pub struct MovementDebug; #[derive(Default, Debug)] pub struct EffectsResource { pub mesh_handle: Handle<Mesh>, pub availability: Vec<Availability>, pub vertices: Vec<ds_range::Range>, pub chunk_size: u32, pub max_chunks: u32, } #[derive(Debug, PartialEq)] pub enum Availability { Open, Used, } impl Default for Availability { fn default() -> Self { Self::Open } } pub struct DebugMeshie { pub entity: Entity, pub mesh_handle: Handle<Mesh>, pub momentum: ds_range::Range, pub momentum_pos: Vec<[f32; 3]>, // facing: ds_range::Range, pub last_path: Vec3, pub prior_inertia: Vec3, } pub fn generate_debug_meshie(entity: Entity, meshes: &mut ResMut<Assets<Mesh>>) -> DebugMeshie { let mut meshie = Mesh::from(shape::Quad { size: vec2(10.0, 200.0), flip: false, }); meshie.translate_mesh(ds_range::Range { start: 0, end: 3 }, vec3(0.0, 190.0, 0.0)); meshie.set_uvs(ds_range::Range { start: 0, end: 3 }, vec![[0.5, 0.0], [0.5, 0.0], [0.5, 0.0], [0.5, 0.0]]); let momentum = meshie.add_mesh(&Mesh::from(shape::Quad { size: vec2(10.0, 200.0), flip: false, })); meshie.set_uvs(momentum, vec![[0.0,0.5], [0.0,0.5], [0.0,0.5], [0.0,0.5]]); meshie.translate_mesh(momentum, vec3(0.0, 290.0, 0.0)); let positions = meshie.get_positions(momentum); DebugMeshie { entity, mesh_handle: meshes.add(meshie), momentum, momentum_pos: positions, // facing: ds_range::Range { start: 0, end: 3}, last_path: Vec3::default(), prior_inertia: Vec3::default(), } } pub struct EntityDestination { pub target: Entity, } pub struct EffectsMeshie; #[derive(Default, Debug)] pub struct Effect { pub indices: ds_range::Range, } pub fn generate_effects_meshie( chunk_size: u32, max_chunks: u32, effects: &mut ResMut<EffectsResource>, ) -> Mesh { effects.chunk_size = chunk_size; effects.max_chunks = max_chunks; let mut effects_meshie = Mesh::from(shape::Quad { size: vec2(80.0, 80.0), flip: false, }); effects.vertices.push(ds_range::Range { start: 0, end: 3 }); effects.availability.push(Availability::Used); for _ in 0..(max_chunks - 1) { let mesh = Mesh::from(shape::Quad { size: vec2(80.0, 80.0), flip: false, }); effects.vertices.push(effects_meshie.add_mesh(&mesh)); effects.availability.push(Availability::Open); } effects_meshie }
use polyhedron_ops as p_ops; fn nsi_camera(c: &nsi::Context, name: &str, _camera_xform: &[f64; 16], samples: u32) { // Setup a camera transform. c.create("camera_xform", nsi::NodeType::Transform, &[]); c.connect("camera_xform", "", ".root", "objects", &[]); c.set_attribute( "camera_xform", &[nsi::double_matrix!( "transformationmatrix", &[1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 5., 1.,] )], ); // Setup a camera. c.create("camera", nsi::NodeType::PerspectiveCamera, &[]); c.connect("camera", "", "camera_xform", "objects", &[]); c.set_attribute("camera", &[nsi::float!("fov", 35.)]); // Setup a screen. c.create("screen", nsi::NodeType::Screen, &[]); c.connect("screen", "", "camera", "screens", &[]); c.set_attribute( "screen", &[ nsi::integers!("resolution", &[1024, 1024]).array_len(2), nsi::integer!("oversampling", 1), ], ); c.set_attribute( ".global", &[ nsi::integer!("renderatlowpriority", 1), nsi::string!("bucketorder", "circle"), nsi::integer!("quality.shadingsamples", samples as _), nsi::integer!("maximumraydepth.reflection", 6), ], ); // RGB layer. c.create("beauty", nsi::NodeType::OutputLayer, &[]); c.set_attribute( "beauty", &[ nsi::string!("variablename", "Ci"), nsi::integer!("withalpha", 1), nsi::string!("scalarformat", "float"), //nsi::string!("filter", "box"), nsi::double!("filterwidth", 1.), ], ); c.connect("beauty", "", "screen", "outputlayers", &[]); // Normal layer. c.create("albedo", nsi::NodeType::OutputLayer, &[]); c.set_attribute( "albedo", &[ nsi::string!("variablename", "albedo"), nsi::string!("variablesource", "shader"), nsi::string!("layertype", "color"), nsi::string!("scalarformat", "float"), nsi::string!("filter", "box"), nsi::double!("filterwidth", 1.), ], ); c.connect("albedo", "", "screen", "outputlayers", &[]); // Normal layer. c.create("normal", nsi::NodeType::OutputLayer, &[]); c.set_attribute( "normal", &[ nsi::string!("variablename", "N.world"), nsi::string!("variablesource", "builtin"), nsi::string!("layertype", "vector"), nsi::string!("scalarformat", "float"), nsi::string!("filter", "box"), nsi::double!("filterwidth", 1.), ], ); c.connect("normal", "", "screen", "outputlayers", &[]); // Setup an output driver. c.create("driver", nsi::NodeType::OutputDriver, &[]); c.connect("driver", "", "beauty", "outputdrivers", &[]); c.connect("driver", "", "albedo", "outputdrivers", &[]); c.connect("driver", "", "normal", "outputdrivers", &[]); c.set_attribute( "driver", &[ nsi::string!("drivername", "r-display"), nsi::string!("imagefilename", name), nsi::float!("denoise", 1.), nsi::integer!("associatealpha", 0), ], ); c.create("driver2", nsi::NodeType::OutputDriver, &[]); c.connect("driver2", "", "beauty", "outputdrivers", &[]); c.set_attribute("driver2", &[nsi::string!("drivername", "idisplay")]); } fn nsi_environment(c: &nsi::Context) { // Set up an environment light. c.create("env_xform", nsi::NodeType::Transform, &[]); c.connect("env_xform", "", ".root", "objects", &[]); c.create("environment", nsi::NodeType::Environment, &[]); c.connect("environment", "", "env_xform", "objects", &[]); c.create("env_attrib", nsi::NodeType::Attributes, &[]); c.connect("env_attrib", "", "environment", "geometryattributes", &[]); c.set_attribute("env_attrib", &[nsi::integer!("visibility.camera", 0)]); c.create("env_shader", nsi::NodeType::Shader, &[]); c.connect("env_shader", "", "env_attrib", "surfaceshader", &[]); // Environment light attributes. c.set_attribute( "env_shader", &[ nsi::string!("shaderfilename", "${DELIGHT}/osl/environmentLight"), nsi::float!("intensity", 1.), ], ); c.set_attribute( "env_shader", &[nsi::string!("image", "assets/wooden_lounge_2k.tdl")], ); } fn nsi_reflective_ground(c: &nsi::Context, _name: &str) { // Floor. c.create("ground_xform_0", nsi::NodeType::Transform, &[]); c.connect("ground_xform_0", "", ".root", "objects", &[]); c.set_attribute( "ground_xform_0", &[nsi::double_matrix!( "transformationmatrix", &[1., 0., 0., 0., 0., 0., -1., 0., 0., 1., 0., 0., 0., -1., 0., 1.,] )], ); c.create("ground_0", nsi::NodeType::Plane, &[]); c.connect("ground_0", "", "ground_xform_0", "objects", &[]); /* // Ceiling. c.create("ground_xform_1", nsi::NodeType::Transform, &[]); c.connect("ground_xform_1", "", ".root", "objects", &[]); c.set_attribute( "ground_xform_1", &[nsi::double_matrix!( "transformationmatrix", &[1., 0., 0., 0., 0., 0., -1., 0., 0., 1., 0., 0., 0., 1., 0., 1.,] )], ); c.create("ground_1", nsi::NodeType::Plane, &[]); c.connect("ground_1", "", "ground_xform_1", "objects", &[]);*/ c.create("ground_attrib", nsi::NodeType::Attributes, &[]); c.set_attribute( "ground_attrib", &[nsi::integer!("visibility.camera", false as _)], ); c.connect("ground_attrib", "", "ground_0", "geometryattributes", &[]); // c.connect("ground_attrib", "", "ground_1", "geometryattributes", &[]); // Ground shader. c.create("ground_shader", nsi::NodeType::Shader, &[]); c.connect("ground_shader", "", "ground_attrib", "surfaceshader", &[]); c.set_attribute( "ground_shader", &[ nsi::string!("shaderfilename", "${DELIGHT}/osl/dlPrincipled"), nsi::color!("i_color", &[0.001, 0.001, 0.001]), //nsi::arg!("coating_thickness", &0.1f32), nsi::float!("roughness", 0.2), nsi::float!("specular_level", 1.), nsi::float!("metallic", 1.), nsi::float!("anisotropy", 1.), nsi::color!("anisotropy_direction", &[1., 0., 0.]), nsi::float!("sss_weight", 0.), nsi::color!("sss_color", &[0.5, 0.5, 0.5]), nsi::float!("sss_scale", 0.), nsi::color!("incandescence", &[0., 0., 0.]), nsi::float!("incandescence_intensity", 0.), //nsi::color!("incandescence_multiplier", &[1.0f32, 1.0, 1.0]), ], ); } fn nsi_material(c: &nsi::Context, name: &str) { let attribute_name = format!("{}_attrib", name); c.create(attribute_name.clone(), nsi::NodeType::Attributes, &[]); c.connect(attribute_name.clone(), "", name, "geometryattributes", &[]); // Metal shader. let shader_name = format!("{}_shader", name); c.create(shader_name.clone(), nsi::NodeType::Shader, &[]); c.connect( shader_name.clone(), "", attribute_name, "surfaceshader", &[], ); c.set_attribute( shader_name, &[ nsi::string!("shaderfilename", "${DELIGHT}/osl/dlPrincipled"), nsi::color!("i_color", &[1., 0.6, 0.3]), //nsi::arg!("coating_thickness", 0.1), nsi::float!("roughness", 0.3), nsi::float!("specular_level", 1.0), nsi::float!("metallic", 1.), nsi::float!("anisotropy", 0.), nsi::float!("sss_weight", 0.), nsi::color!("sss_color", &[0.5, 0.5, 0.5]), nsi::float!("sss_scale", 0.), nsi::color!("incandescence", &[0., 0., 0.]), nsi::float!("incandescence_intensity", 0.), //nsi::color!("incandescence_multiplier", &[1., 1., 1.]), ], ); } pub fn nsi_render( polyhedron: &p_ops::Polyhedron, camera_xform: &[f64; 16], name: &str, samples: u32, cloud_render: bool, ) { let ctx = { if cloud_render { nsi::Context::new(&[nsi::integer!("cloud", 1)]) } else { nsi::Context::new(&[nsi::string!("streamfilename", "stdout")]) } } .expect("Could not create NSI rendering context."); nsi_camera(&ctx, name, camera_xform, samples); nsi_environment(&ctx); let name = polyhedron.to_nsi(&ctx, None, None, None, None); nsi_material(&ctx, &name); nsi_reflective_ground(&ctx, &name); // And now, render it! ctx.render_control(&[nsi::string!("action", "start")]); ctx.render_control(&[nsi::string!("action", "wait")]); } fn main() { let mut polyhedron = p_ops::Polyhedron::tetrahedron(); polyhedron.meta(None, None, None, None, true); polyhedron.normalize(); polyhedron.gyro(Some(1. / 3.), Some(0.1), true); polyhedron.normalize(); polyhedron.kis(Some(-0.2), None, Some(true), true); polyhedron.normalize(); //println!("1"); nsi_render(&polyhedron, &[0.0f64; 16], "test_0001samples.exr", 1, false); /*println!("256"); nsi_render( &polyhedron, &[0.0f64; 16], "test_0256samples.exr", 256, true, ); println!("2048");*/ /*nsi_render( &polyhedron, &[0.0f64; 16], "test_2048samples.exr", 2048, true, ); println!("4096"); nsi_render( &polyhedron, &[0.0f64; 16], "test_4096samples.exr", 4096, true, );*/ }
use std::env; use std::fs; use std::process; use tini::prelude::*; fn main() { let mut args = env::args().skip(1); let filename = match args.next() { Some(arg) => arg, None => { eprintln!("Error: too few arguments. Expected one."); println!("Usage: tinii <file>"); process::exit(1); } }; let input = match fs::read_to_string(filename) { Ok(i) => i, Err(e) => { eprintln!("error while reading file {}.", e); process::exit(1) } }; let lexer = Lexer::new(&input); let parser = Parser::new(lexer); let mut interpreter = Interpreter::new(); for expr in parser { let expr = match expr { Ok(expr) => expr, Err(e) => { eprintln!("error while parsing: {}.", e); process::exit(1); } }; match interpreter.eval(expr) { Err(e) => { eprintln!("error while running interpreter: {}.", e); process::exit(1) } _ => {} } } }
///Defines a payoff applied to the underlying spot value. pub trait Payoff { ///Applies the payoff to the spot value of the underlying. fn apply(&self, spot: f64) -> f64; } ///Defines the payoff for a Call Option #[derive(Debug)] pub struct CallPayoff { strike: f64, } impl CallPayoff { pub fn new(strike: f64) -> CallPayoff { CallPayoff { strike } } } impl Payoff for CallPayoff { fn apply(&self, spot: f64) -> f64 { let payoff = spot - self.strike; if payoff > 0.0 { payoff } else { 0.0 } } } #[cfg(test)] mod tests { use super::*; #[test] fn call_payoff_ok() { let etol = 1e-10; let payoff = CallPayoff::new(50.0_f64); let expected = 50.0_f64; let actual = payoff.apply(100.0_f64); assert!( (actual - expected).abs() < etol, "actual: {}, expected: {}", actual, expected ); } }
// #![windows_subsystem = "windows"] // #![warn(bare_trait_objects)] extern crate ggez; // mod imgui_wrapper; // extern crate nalgebra; // use rand::{thread_rng, Rng}; // use nalgebra::{Point2, Vector2}; // use crate::imgui_wrapper::ImGuiWrapper; use ggez::{ conf, event::{self, EventHandler, KeyCode, KeyMods, MouseButton}, graphics, nalgebra::Point2, timer, Context, ContextBuilder, GameResult, }; // /// Create a unit vector representing the // /// given angle (in radians) // fn vec_from_angle(angle: f32) -> Vector2 { // let vx = angle.sin(); // let vy = angle.cos(); // Vector2::new(vx, vy) // } // // Actors: anything in the game world // #[derive(Debug)] // enum ActorType { // Continent // } // #[derive(Debug)] // struct Actor { // tag: ActorType, // pos: Point2, // facing: f32, // velocity: Vector2, // ang_vel: f32, // } // // Constants // const MAX_ROCK_VELOCITY: f32 = 50.0; const ASSETS_DIR_NAME: &str = "assets"; // // Constructors for different game objects // fn create_continent() -> Actor { // Actor { // tag: ActorType::Continent, // pos: Point2::origin(), // facing: 0.0, // velocity: na::zero(), // ang_vel: 0.0, // } // } // Create the continents // fn create_continents(num: i32, ) -> Vec<Actor> { // let new_continent = |_| { // let mut continent = create_continent(); // continent.pos = thread_rng().gen_range(0.0, 500.0); // continent // } // (0..num).map(new_continent).collect(); // } // Creating a gamestate depends on having an SDL context to load resources. // Creating a context depends on loading a config file. // Loading a config file depends on having FS (or we can just fake our way around it // by creating an FS and then throwing it away; the costs are not huge.) fn main() { let window_mode = conf::WindowMode::default().resizable(false).dimensions(750.0, 500.0); let window_conf = conf::WindowSetup::default() .title("Big Foil") .icon("/tile.png"); let (mut ctx, mut event_loop) = ContextBuilder::new("foil", "🔥 Big Foil") .window_mode(window_mode) .window_setup(window_conf) .add_resource_path(ASSETS_DIR_NAME) .build() .expect("aieee, could not create ggez context!"); // Create an instance of your event handler. // Usually, you should provide it with the Context object to // use when setting your game up. let mut game = MainState::new(&mut ctx).unwrap(); // Run! match event::run(&mut ctx, &mut event_loop, &mut game) { Ok(_) => println!("Exited cleanly."), Err(e) => println!("Error occured: {}", e), } } /// Game state here struct MainState { spritebatch: graphics::spritebatch::SpriteBatch, pos_x: f32, // imgui_wrapper: ImGuiWrapper, } impl MainState { fn new(mut ctx: &mut Context) -> GameResult<MainState> { // Load/create resources such as images here. let image = graphics::Image::new(ctx, "/tile.png").unwrap(); let batch = graphics::spritebatch::SpriteBatch::new(image); // let imgui_wrapper = ImGuiWrapper::new(&mut ctx); let state = MainState { spritebatch: batch, pos_x: 0.0, // imgui_wrapper, }; Ok(state) } } impl EventHandler for MainState { fn update(&mut self, ctx: &mut Context) -> GameResult { self.pos_x = self.pos_x % 800.0 + 1.0; if timer::ticks(ctx) % 100 == 0 { println!( "Average FPS: {} | Delta time frame: {:?}", timer::fps(ctx), timer::delta(ctx) ); } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { graphics::clear(ctx, graphics::BLACK); // Render game stuff { let circle = graphics::Mesh::new_circle( ctx, graphics::DrawMode::fill(), Point2::new(self.pos_x, 300.0), 100.0, 0.1, graphics::WHITE, )?; graphics::draw(ctx, &circle, graphics::DrawParam::default())?; for x in 0..2 { for y in (0..100).step_by(10) { let x = x as f32; let y = y as f32; let p = graphics::DrawParam::new().dest(Point2::new(x * 50.0, y * 30.0)); self.spritebatch.add(p); } } graphics::draw(ctx, &self.spritebatch, graphics::DrawParam::default())?; self.spritebatch.clear(); } // Render game UI { // self.imgui_wrapper.render(ctx, self.hidpi_factor); } // Draw code here... graphics::present(ctx)?; Ok(()) } }
#[doc = "Reader of register NWDA2"] pub type R = crate::R<u32, super::NWDA2>; #[doc = "Reader of field `NEWDAT`"] pub type NEWDAT_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - New Data Bits"] #[inline(always)] pub fn newdat(&self) -> NEWDAT_R { NEWDAT_R::new((self.bits & 0xffff) as u16) } }
use std::fmt; use std::marker::PhantomData; use bytes::{Buf, BufMut}; use prost::{DecodeError, Message}; use tower_grpc::client::codec::{Codec, DecodeBuf, EncodeBuf}; /// A protobuf codec. pub struct Protobuf<T, U>(PhantomData<(T, U)>); impl<T, U> Protobuf<T, U> { pub fn new() -> Self { Protobuf(PhantomData) } } impl<T, U> Clone for Protobuf<T, U> { fn clone(&self) -> Self { Protobuf(PhantomData) } } impl<T, U> fmt::Debug for Protobuf<T, U> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Protobuf") } } impl<T: Message, U: Message + Default> Codec for Protobuf<T, U> { const CONTENT_TYPE: &'static str = "application/grpc+proto"; type Encode = T; type Decode = U; // never errors type EncodeError = Void; type DecodeError = DecodeError; fn encode(&mut self, msg: Self::Encode, buf: &mut EncodeBuf) -> Result<(), Self::EncodeError> { let len = msg.encoded_len(); if buf.remaining_mut() < len { buf.reserve(len); } // prost says the only error from `Message::encode` is if there is not // enough space in the buffer. msg.encode(buf).expect("buf space was reserved"); Ok(()) } fn decode(&mut self, buf: &mut DecodeBuf) -> Result<Self::Decode, Self::DecodeError> { trace!("decode; bytes={}", buf.remaining()); match Message::decode(buf) { Ok(msg) => Ok(msg), Err(err) => { debug!("decode error: {:?}", err); Err(err) } } } } /// Can never be instantiated. pub enum Void {}
mod srs; pub use gdal_sys::OGRAxisOrientation; pub use srs::{AxisOrientationType, CoordTransform, SpatialRef}; #[cfg(test)] mod tests;
use std::collections::HashMap; use rust_mal_lib::types::{MalError, MalResult, MalValue}; use rust_mal_lib::{env::Environment, reader, types}; use rust_mal_steps::scaffold::*; #[derive(Clone)] struct FlatEnv { data: HashMap<String, MalValue>, } impl Environment for FlatEnv { fn new(_outer: Option<&Self>) -> Self { FlatEnv { data: HashMap::new(), } } fn new_inner(&self) -> Self { panic!("step2 env: no environment nesting supported"); } fn root(&self) -> Self { self.clone() } fn get_env_value(&self, key: &MalValue) -> MalResult { match **key { types::MalType::Symbol(ref symbol) => match self.data.get(symbol) { Some(value) => Ok(value.clone()), None => types::err_string(format!("env: cannot find {}", symbol)), }, _ => types::err_str("env: cannot get with a non-symbol key"), } } fn set_env_value(&mut self, key: MalValue, val: MalValue) -> &mut Self { match *key { types::MalType::Symbol(ref symbol) => { self.data.insert(symbol.clone(), val); } _ => panic!("step2 env: env: cannot set with a non-symbol key"), } self } } fn read(string: &str) -> MalResult { reader::read_str(string) } fn eval_ast(ast: MalValue, env: &impl Environment) -> MalResult { use types::MalType::*; match *ast { Symbol(ref symbol) => env.get_env_value(&types::new_symbol(symbol.clone())), List(ref seq) | Vector(ref seq) => { let mut ast_ev = vec![]; for value in seq { ast_ev.push(eval(value.clone(), env)?); } Ok(match *ast { List(_) => types::new_list(ast_ev), _ => types::new_vector(ast_ev), }) } _ => Ok(ast.clone()), } } fn eval(ast: MalValue, env: &impl Environment) -> MalResult { use types::MalType::*; match *ast { List(_) => (), _ => return eval_ast(ast, env), } // ast is a list : apply the first item to the other let list_ev = eval_ast(ast, env)?; let items = match *list_ev { List(ref seq) => seq, _ => return types::err_str("can only apply on a List"), }; if items.is_empty() { return Ok(list_ev.clone()); } let f = &items[0]; f.apply(items[1..].to_vec()) } fn print(expr: MalValue) -> String { expr.pr_str(true) } fn int_op<F>(f: F, args: Vec<MalValue>) -> MalResult where F: FnOnce(i32, i32) -> i32, { if args.len() != 2 { return types::err_string(format!( "wrong arity ({}) for operation between 2 integers", args.len() )); } match *args[0] { types::MalType::Integer(left) => match *args[1] { types::MalType::Integer(right) => Ok(types::new_integer(f(left, right))), _ => types::err_str("right argument must be an integer"), }, _ => types::err_str("left argument must be an integer"), } } fn add(args: Vec<MalValue>) -> MalResult { int_op(|a, b| a + b, args) } fn sub(args: Vec<MalValue>) -> MalResult { int_op(|a, b| a - b, args) } fn mul(args: Vec<MalValue>) -> MalResult { int_op(|a, b| a * b, args) } fn div(args: Vec<MalValue>) -> MalResult { if args.len() != 2 { return types::err_string(format!( "wrong arity ({}) for operation between 2 integers", args.len() )); } match *args[0] { types::MalType::Integer(left) => match *args[1] { types::MalType::Integer(right) => { if right == 0 { types::err_str("cannot divide by 0") } else { Ok(types::new_integer(left / right)) } } _ => types::err_str("right argument must be an integer"), }, _ => types::err_str("left argument must be an integer"), } } struct Step2Eval; impl InterpreterScaffold<FlatEnv> for Step2Eval { const STEP_NAME: &'static str = "step2_eval"; fn create_env() -> Result<FlatEnv, MalError> { let mut env = FlatEnv::new(None); env.set_env_value( types::new_symbol("+".into()), types::new_function(add, Some(2), "+"), ) .set_env_value( types::new_symbol("-".into()), types::new_function(sub, Some(2), "-"), ) .set_env_value( types::new_symbol("*".into()), types::new_function(mul, Some(2), "*"), ) .set_env_value( types::new_symbol("/".into()), types::new_function(div, Some(2), "/"), ); Ok(env) } fn rep(input: &str, env: &FlatEnv) -> Result<String, MalError> { let ast = read(input)?; let expr = eval(ast, env)?; Ok(print(expr)) } } fn main() -> Result<(), String> { cli_loop::<FlatEnv, Step2Eval>() } #[cfg(test)] mod tests { use super::*; #[test] fn test_step2_spec() { assert_eq!( validate_against_spec::<FlatEnv, Step2Eval>("step2_eval.mal"), Ok(()) ); } }
#[macro_use] pub mod counter; mod metrics; pub use crate::metrics::flush; pub use crate::metrics::query; pub use crate::metrics::set_panic_hook; pub use crate::metrics::submit; pub use influx_db_client as influxdb;
#[doc = "Reader of register MMCTXRIS"] pub type R = crate::R<u32, super::MMCTXRIS>; #[doc = "Reader of field `GBF`"] pub type GBF_R = crate::R<bool, bool>; #[doc = "Reader of field `SCOLLGF`"] pub type SCOLLGF_R = crate::R<bool, bool>; #[doc = "Reader of field `MCOLLGF`"] pub type MCOLLGF_R = crate::R<bool, bool>; #[doc = "Reader of field `OCTCNT`"] pub type OCTCNT_R = crate::R<bool, bool>; impl R { #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Status"] #[inline(always)] pub fn gbf(&self) -> GBF_R { GBF_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Status"] #[inline(always)] pub fn scollgf(&self) -> SCOLLGF_R { SCOLLGF_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Status"] #[inline(always)] pub fn mcollgf(&self) -> MCOLLGF_R { MCOLLGF_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 20 - Octet Counter Interrupt Status"] #[inline(always)] pub fn octcnt(&self) -> OCTCNT_R { OCTCNT_R::new(((self.bits >> 20) & 0x01) != 0) } }
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert('(', ')'); map.insert('[', ']'); map.insert('{', '}'); println!("{:?}", map.get(&'[') == Some(&']')); let mut stack = Vec::new(); stack.push(']'); let x = '['; match (stack.pop().as_ref(), map.get(&x)) { (Some(a), Some(b)) => println!("a, b: {:?}", a == b), (Some(_a), None) => println!("a"), (None, Some(_b)) => println!("b"), (None, None) => println!("none"), } // println!("{:?}", map.get(&'[') == stack.pop().as_ref()); }
/* Copyright (c) 2015, 2016 Saurav Sachidanand 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. */ //! Interpolation of intermediate values of functions /** Interpolates an intermediate value of a function from three of it's given values # Returns * `interpol_val`: Intermediate value of the function # Arguments * `y1`: Value 1 of the function * `y2`: Value 2 of the function * `y3`: Value 3 of the function * `n` : Interpolating factor, measured from the central value `y2`, positively towards `y3` **/ #[inline] pub fn three_values(y1: f64, y2: f64, y3: f64, n: f64) -> f64 { let a = y2 - y1; let b = y3 - y2; let c = b - a; y2 + n*(a + b + n*c)/2.0 } /** Interpolates an intermediate value of a function from five of it's given values # Returns * `interpol_val`: Intermediate value of the function # Arguments * `y1`: Value 1 of the function * `y2`: Value 2 of the function * `y3`: Value 3 of the function * `y4`: Value 4 of the function * `y5`: Value 5 of the function * `n` : Interpolating factor, measured from the central value `y3`, positively towards `y4` **/ pub fn five_values(y1: f64, y2: f64, y3: f64, y4: f64, y5: f64, n: f64) -> f64 { let a = y2 - y1; let b = y3 - y2; let c = y4 - y3; let d = y5 - y4; let e = b - a; let f = c - b; let g = d - c; let h = f - e; let j = g - f; let k = (j - h) / 12.0; let h_j_12 = (h + j) / 6.0; y3 + Horner_eval!( n, 0.0, b + c - h_j_12, f - k, h_j_12, k ) / 2.0 }
use crate::fs_helper::AppContext; use std::collections::HashMap; use uuid::Uuid; const VAL_STRING2: &str = "asd"; const VAL_DEFAULT: &str = "default"; const VAL_LOCAL_DATE: &str = "2021-01-01"; const VAL_LOCAL_DATE_TIME: &str = "2021-01-01T00:00:00"; const VAL_INTEGER: &str = "1"; const VAL_DOUBLE: &str = "1.3"; const VAL_BOOL: &str = "false"; pub enum JsonValue { Simple(String), Nested(String, bool), } pub fn parse_java_text( json_src: String, app_ctx: &mut AppContext, // dict: &HashMap<String, String>, // log_lines: &mut Vec<String>, ) -> Vec<String> { let mut json_lines = vec![]; let mut block_comment = false; for mut line in json_src.lines() { line = line.trim_matches(|c| c == '\r' || c == '\n' || c == ';' || char::is_whitespace(c)); if line.starts_with('@') || line.starts_with("//") { continue; } if line.starts_with("/*") { block_comment = true; continue; } if block_comment { if line.starts_with("*/") { block_comment = false; } continue; } let words = line .split_whitespace() .filter(|w| !w.is_empty()) .collect::<Vec<_>>(); if words.is_empty() { continue; } if words.get(1).is_none() || words.get(2).is_none() { exit_when_no_pair(app_ctx, &words) } let (j_type, j_property_name) = (words.get(1).unwrap(), words.get(2).unwrap()); let mut quotes_needed = true; let j_value = match map_type_to_value(j_type, &app_ctx.dict) { JsonValue::Nested(text, flag) => { quotes_needed = flag; text } JsonValue::Simple(text) => text, }; let json_string = if quotes_needed { format!("\"{}\" : \"{}\"", j_property_name, j_value) } else { format!("\"{}\" : {}", j_property_name, j_value) }; json_lines.push(json_string) } json_lines } fn map_type_to_value(j_type: &str, dict: &HashMap<String, String>) -> JsonValue { return match j_type { "String" | "string" => JsonValue::Simple(VAL_STRING2.to_string()), "Integer" | "int" => JsonValue::Simple(VAL_INTEGER.to_string()), "Long" | "long" => JsonValue::Simple(VAL_INTEGER.to_string()), "LocalDate" => JsonValue::Simple(VAL_LOCAL_DATE.to_string()), "LocalDateTime" => JsonValue::Simple(VAL_LOCAL_DATE_TIME.to_string()), "Boolean" | "boolean" => JsonValue::Simple(VAL_BOOL.to_string()), "BigDecimal" => JsonValue::Simple(VAL_DOUBLE.to_string()), "UUID" => JsonValue::Simple(Uuid::new_v4().to_string()), _ => { if let Some(val) = dict.get(j_type) { JsonValue::Nested(val.clone(), !val.starts_with('{')) } else { JsonValue::Simple(VAL_DEFAULT.to_string()) } } }; } fn exit_when_no_pair(app_ctx: &mut AppContext, words: &[&str]) { // fn exit_when_no_pair(log_lines: &mut Vec<String>, words: &[&str]) { let error = format!("Input doesn't produce (type,fieldName) pair {:?}", words); println!("{}", &error); // log_lines.push(error); app_ctx.write_log(); std::process::exit(1) }
use iced::{ pick_list, button, scrollable, Element, Row, PickList, Scrollable, Button, Text, Align, Length, Container, }; use crate::gui::{CustomSelect, CustomButton}; use std::fmt::{Display, Formatter, Result}; #[derive(Debug, Clone)] pub struct DefaultAppPage { scroll: scrollable::State, audio_player: (&'static str, pick_list::State<AudioPlayer>, AudioPlayer, button::State), video_player: (&'static str, pick_list::State<VideoPlayer>, VideoPlayer, button::State), image_viewer: (&'static str, pick_list::State<ImageViewer>, ImageViewer, button::State), web_browser: (&'static str, pick_list::State<WebBrowser>, WebBrowser, button::State), term_emulation: (&'static str, pick_list::State<TermEmulation>, TermEmulation, button::State), mail_client: (&'static str, pick_list::State<MailClient>, MailClient, button::State), calendar: (&'static str, pick_list::State<Calendar>, Calendar, button::State), } #[derive(Debug, Clone)] pub enum DefaultAppMsg { // DefAppChanged(usize), // DefAppSearchClicked(usize), AudioPlayerChanged(AudioPlayer), VideoPlayerChanged(VideoPlayer), ImageViewerChanged(ImageViewer), WebBrowserChanged(WebBrowser), TermEmulationChanged(TermEmulation), MailClientChanged(MailClient), CalendarChanged(Calendar), BtnSearchClicked, } impl DefaultAppPage { pub fn new() -> Self { Self { scroll: scrollable::State::new(), audio_player: ("Audio Player", pick_list::State::default(), AudioPlayer::VLC, button::State::new()), video_player: ("Video Player", pick_list::State::default(), VideoPlayer::VLC, button::State::new()), image_viewer: ("Image Viewer", pick_list::State::default(), ImageViewer::GPicView, button::State::new()), web_browser: ("Web Browser", pick_list::State::default(), WebBrowser::Firefox, button::State::new()), term_emulation: ("Terminal Emulation", pick_list::State::default(), TermEmulation::Alacritty, button::State::new()), mail_client: ("Mail Client", pick_list::State::default(), MailClient::Thunderbird, button::State::new()), calendar: ("Calendar", pick_list::State::default(), Calendar::California, button::State::new()), } } pub fn update(&mut self, msg: DefaultAppMsg) { use DefaultAppMsg::*; match msg { AudioPlayerChanged(val) => self.audio_player.2 = val, VideoPlayerChanged(val) => self.video_player.2 = val, ImageViewerChanged(val) => self.image_viewer.2 = val, WebBrowserChanged(val) => self.web_browser.2 = val, TermEmulationChanged(val) => self.term_emulation.2 = val, MailClientChanged(val) => self.mail_client.2 = val, CalendarChanged(val) => self.calendar.2 = val, BtnSearchClicked => println!("Search clicked"), } } pub fn view(&mut self) -> Element<DefaultAppMsg> { let DefaultAppPage { scroll, audio_player, video_player, image_viewer, web_browser, term_emulation, mail_client, calendar, } = self; let txt_def_apps = Text::new("Default Applications").size(14); let audio_player_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", audio_player.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut audio_player.1, &AudioPlayer::ALL[..], Some(audio_player.2), DefaultAppMsg::AudioPlayerChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut audio_player.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); let video_player_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", video_player.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut video_player.1, &VideoPlayer::ALL[..], Some(video_player.2), DefaultAppMsg::VideoPlayerChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut video_player.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); let image_viewer_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", image_viewer.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut image_viewer.1, &ImageViewer::ALL[..], Some(image_viewer.2), DefaultAppMsg::ImageViewerChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut image_viewer.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); let web_browser_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", web_browser.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut web_browser.1, &WebBrowser::ALL[..], Some(web_browser.2), DefaultAppMsg::WebBrowserChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut web_browser.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); let term_emulation_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", term_emulation.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut term_emulation.1, &TermEmulation::ALL[..], Some(term_emulation.2), DefaultAppMsg::TermEmulationChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut term_emulation.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); let mail_client_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", mail_client.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut mail_client.1, &MailClient::ALL[..], Some(mail_client.2), DefaultAppMsg::MailClientChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut mail_client.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); let calendar_sec = Row::new().spacing(10).align_items(Align::Center) .push(Container::new(Text::new(format!("{}:", calendar.0))).width(Length::Units(127))) .push(Container::new(PickList::new(&mut calendar.1, &Calendar::ALL[..], Some(calendar.2), DefaultAppMsg::CalendarChanged).width(Length::Fill).style(CustomSelect::Default)).width(Length::Fill)) .push(Button::new(&mut calendar.3, Text::new(" Search ")).on_press(DefaultAppMsg::BtnSearchClicked).style(CustomButton::Default)); Scrollable::new(scroll).spacing(12).scroller_width(5).scrollbar_width(7) .push(txt_def_apps) .push(audio_player_sec) .push(video_player_sec) .push(image_viewer_sec) .push(web_browser_sec) .push(term_emulation_sec) .push(mail_client_sec) .push(calendar_sec) .into() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AudioPlayer { VLC, Rhythmbox, Clementine, Audacious, CMUS, Sayonara, Museeks, Spotify, } impl AudioPlayer { const ALL: [AudioPlayer; 8] = [ AudioPlayer::VLC, AudioPlayer::Rhythmbox, AudioPlayer::Clementine, AudioPlayer::Audacious, AudioPlayer::CMUS, AudioPlayer::Sayonara, AudioPlayer::Museeks, AudioPlayer::Spotify, ]; } impl Display for AudioPlayer { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { AudioPlayer::VLC => "VLC Media Player", AudioPlayer::Rhythmbox => "Rhythmbox", AudioPlayer::Clementine => "Clementine", AudioPlayer::Audacious => "Audacious", AudioPlayer::CMUS => "CMUS", AudioPlayer::Sayonara => "Sayonara", AudioPlayer::Museeks => "Museeks", AudioPlayer::Spotify => "Spotify", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VideoPlayer { VLC, MPlayer, MPV, FFPlay, GstPlay, } impl VideoPlayer { const ALL: [VideoPlayer; 5] = [ VideoPlayer::VLC, VideoPlayer::MPlayer, VideoPlayer::MPV, VideoPlayer::FFPlay, VideoPlayer::GstPlay, ]; } impl Display for VideoPlayer { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { VideoPlayer::VLC => "VLC Media Player", VideoPlayer::MPlayer => "MPlayer", VideoPlayer::MPV => "MPV Player", VideoPlayer::FFPlay => "FFPlay Media Player", VideoPlayer::GstPlay => "GST Play", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ImageViewer { GPicView, Ephoto, GalaPic, GWenView, QuickImgViewer, } impl ImageViewer { const ALL: [ImageViewer; 5] = [ ImageViewer::GPicView, ImageViewer::Ephoto, ImageViewer::GalaPic, ImageViewer::GWenView, ImageViewer::QuickImgViewer, ]; } impl Display for ImageViewer { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { ImageViewer::GPicView => "GPicView", ImageViewer::Ephoto => "Ephoto", ImageViewer::GalaPic => "GalaPic", ImageViewer::GWenView => "GWenView", ImageViewer::QuickImgViewer => "Quick Image Viewer", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WebBrowser { Firefox, Chrome, Chromium, Brave, } impl WebBrowser { const ALL: [WebBrowser; 4] = [ WebBrowser::Firefox, WebBrowser::Chrome, WebBrowser::Chromium, WebBrowser::Brave, ]; } impl Display for WebBrowser { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { WebBrowser::Firefox => "Firefox web browser", WebBrowser::Chrome => "Google Chrome", WebBrowser::Chromium => "Chromium browser", WebBrowser::Brave => "Brave web browser", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TermEmulation { Alacritty, PuTTY, Kitty, Xterm, Terminator, } impl TermEmulation { const ALL: [TermEmulation; 5] = [ TermEmulation::Alacritty, TermEmulation::PuTTY, TermEmulation::Kitty, TermEmulation::Xterm, TermEmulation::Terminator, ]; } impl Display for TermEmulation { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { TermEmulation::Alacritty => "Alacritty", TermEmulation::PuTTY => "PuTTy", TermEmulation::Kitty => "Kitty", TermEmulation::Xterm => "Xterm", TermEmulation::Terminator => "Terminator", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MailClient { Msmtp, Mutt, SNail, Sup, Thunderbird, } impl MailClient { const ALL: [MailClient; 5] = [ MailClient::Msmtp, MailClient::Mutt, MailClient::SNail, MailClient::Sup, MailClient::Thunderbird, ]; } impl Display for MailClient { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { MailClient::Msmtp => "msmtp", MailClient::Mutt => "Mutt", MailClient::SNail => "S-nail", MailClient::Sup => "Sup", MailClient::Thunderbird => "Thunderbird", } ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Calendar { California, Osmo, Evolution, Korganizer, } impl Calendar { const ALL: [Calendar; 4] = [ Calendar::California, Calendar::Osmo, Calendar::Evolution, Calendar::Korganizer, ]; } impl Display for Calendar { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}", match self { Calendar::California => "California", Calendar::Osmo => "Osmo", Calendar::Evolution => "Evolution", Calendar::Korganizer => "Korganizer", } ) } }
use rppal::gpio::{Gpio, Level, Trigger}; use std::{sync::mpsc, time::Instant}; const PIN: u8 = 4; fn main() { let gpio = Gpio::new().unwrap(); let mut pin = gpio.get(PIN).unwrap().into_input(); let start = Instant::now(); let mut pulses: Vec<(Level, f64)> = vec![]; let (tx, rx) = mpsc::channel(); pin.set_async_interrupt(Trigger::Both, move |level| { tx.send((start.elapsed().as_secs_f64(), level)).unwrap(); }) .unwrap(); for i in 1..=50 { let (time, level) = rx.recv().unwrap(); println!("{:3}: {:.4}: {}", i, time, level); pulses.push((level, time)); } let mut t1 = vec![]; let mut t2 = vec![]; for ((level1, time1), (level2, time2)) in pulses.windows(2).map(|slice| (slice[0], slice[1])) { match (level1, level2) { (Level::High, Level::Low) => t1.push(time2 - time1), (Level::Low, Level::High) => t2.push(time2 - time1), _ => (), } } let t1_avg = t1.iter().sum::<f64>() / t1.len() as f64; let t2_avg = t2.iter().sum::<f64>() / t2.len() as f64; println!( "t1: {:.4e} s, t2: {:.4e} s, f: {:.4e} hz", t1_avg, t2_avg, 1.0 / (t1_avg + t2_avg) ); }
pub fn sort(array: &mut [isize]) { sort_in_range(array, 0, array.len() - 1); } fn sort_in_range(array: &mut [isize], first: usize, last: usize) { if first < last { let midpoint = partition(array, first, last); sort_in_range(array, first, midpoint - 1); sort_in_range(array, midpoint + 1, last); } } fn partition(array: &mut [isize], first: usize, last: usize) -> usize { let pivot = array[last]; let mut i = first; let mut j = first; while j < last { if array[j] < pivot { array.swap(i, j); i += 1; } j += 1; } array.swap(i, last); i } #[cfg(test)] pub mod test { use super::sort; #[test] fn basics() { let mut nums = [7, 2, 4, 6]; sort(&mut nums); assert_eq!(nums, [2, 4, 6, 7]); } }
use std::hash::Hash; use graph_lib::safe_tree::Tree; use policy::policy::Policy; use policy::score::Score; use sim_result::SimResult; use rules::{Action, Rules}; pub(crate) type MctsNode<A> = Tree<A, SimResult>; pub trait Mcts<A: Action, S: Rules<A>> { fn root(&self) -> MctsNode<A>; fn selection<Sc: Score>(&mut self, exploitation: &Sc) -> MctsNode<A>; fn expansion<P: Policy<A, S>>(&mut self, selected: &MctsNode<A>, policy: &P) -> (A, MctsNode<A>); fn backpropagation(&mut self, cursor: &MctsNode<A>, res: SimResult); fn state(&self) -> &S; fn state_mut(&mut self) -> &mut S; }
use std::sync::Arc; use std::sync::Mutex; lazy_static! { static ref APP_STATE: Mutex<Arc<AppState>> = Mutex::new(Arc::new(AppState::new())); } pub fn update_dynamic_data(time: f32, canvas_width: f32, canvas_height: f32) { let mut data = APP_STATE.lock().unwrap(); *data = Arc::new(AppState { canvas_width, canvas_height, time, ..*data.clone() }); } pub fn get_current_state() -> Arc<AppState> { APP_STATE.lock().unwrap().clone() } pub struct AppState { pub canvas_width: f32, pub canvas_height: f32, pub control_bottom: f32, pub control_top: f32, pub control_left: f32, pub control_right: f32, pub time: f32, } impl AppState { fn new() -> AppState { AppState { canvas_width: 0., canvas_height: 0., control_bottom: 0., control_top: 0., control_left: 0., control_right: 0., time: 0. } } }
// RGB standard library // Written in 2020 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the MIT License // along with this software. // If not, see <https://opensource.org/licenses/MIT>. use std::collections::BTreeMap; use lnpbp::bitcoin::util::psbt::PartiallySignedTransaction as Psbt; use lnpbp::bitcoin::OutPoint; use lnpbp::bp::blind::{OutpointHash, OutpointReveal}; use lnpbp::rgb::{Consignment, ContractId, NodeId, Transition}; #[derive(Clone, Debug, Display, LnpApi)] #[lnp_api(encoding = "strict")] #[display_from(Debug)] #[non_exhaustive] pub enum Request { #[lnp_api(type = 0x0101)] AddSchema(::lnpbp::rgb::Schema), #[lnp_api(type = 0x0103)] ListSchemata(), #[lnp_api(type = 0x0105)] ReadSchemata(Vec<::lnpbp::rgb::SchemaId>), #[lnp_api(type = 0x0201)] AddGenesis(::lnpbp::rgb::Genesis), #[lnp_api(type = 0x0203)] ListGeneses(), #[lnp_api(type = 0x0205)] ReadGenesis(::lnpbp::rgb::ContractId), #[lnp_api(type = 0x0301)] ReadTransitions(Vec<::lnpbp::rgb::NodeId>), #[lnp_api(type = 0x0401)] Consign(crate::api::stash::ConsignRequest), #[lnp_api(type = 0x0403)] Validate(::lnpbp::rgb::Consignment), #[lnp_api(type = 0x0405)] Merge(crate::api::stash::MergeRequest), #[lnp_api(type = 0x0407)] Forget(Vec<(::lnpbp::rgb::NodeId, u16)>), } #[derive(Clone, StrictEncode, StrictDecode, Debug, Display)] #[display_from(Debug)] pub struct ConsignRequest { pub contract_id: ContractId, pub inputs: Vec<OutPoint>, pub transition: Transition, pub other_transition_ids: BTreeMap<ContractId, NodeId>, pub outpoints: Vec<OutpointHash>, pub psbt: Psbt, } #[derive(Clone, StrictEncode, StrictDecode, Debug, Display)] #[display_from(Debug)] pub struct MergeRequest { pub consignment: Consignment, pub reveal_outpoints: Vec<OutpointReveal>, }
#[doc = "Reader of register COMP2_CSR"] pub type R = crate::R<u32, super::COMP2_CSR>; #[doc = "Writer for register COMP2_CSR"] pub type W = crate::W<u32, super::COMP2_CSR>; #[doc = "Register COMP2_CSR `reset()`'s with value 0"] impl crate::ResetValue for super::COMP2_CSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "COMP2_CSR register lock bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2LOCK_A { #[doc = "0: COMP2_CSR\\[31:0\\] for comparator 2 are read/write"] READWRITE = 0, #[doc = "1: COMP2_CSR\\[31:0\\] for comparator 2 are read-only"] READONLY = 1, } impl From<COMP2LOCK_A> for bool { #[inline(always)] fn from(variant: COMP2LOCK_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2LOCK`"] pub type COMP2LOCK_R = crate::R<bool, COMP2LOCK_A>; impl COMP2LOCK_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2LOCK_A { match self.bits { false => COMP2LOCK_A::READWRITE, true => COMP2LOCK_A::READONLY, } } #[doc = "Checks if the value of the field is `READWRITE`"] #[inline(always)] pub fn is_read_write(&self) -> bool { *self == COMP2LOCK_A::READWRITE } #[doc = "Checks if the value of the field is `READONLY`"] #[inline(always)] pub fn is_read_only(&self) -> bool { *self == COMP2LOCK_A::READONLY } } #[doc = "Comparator 2 output status bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2VALUE_A { #[doc = "0: Comparator values are not equal"] NOTEQUAL = 0, #[doc = "1: Comparator values are equal"] EQUAL = 1, } impl From<COMP2VALUE_A> for bool { #[inline(always)] fn from(variant: COMP2VALUE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2VALUE`"] pub type COMP2VALUE_R = crate::R<bool, COMP2VALUE_A>; impl COMP2VALUE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2VALUE_A { match self.bits { false => COMP2VALUE_A::NOTEQUAL, true => COMP2VALUE_A::EQUAL, } } #[doc = "Checks if the value of the field is `NOTEQUAL`"] #[inline(always)] pub fn is_not_equal(&self) -> bool { *self == COMP2VALUE_A::NOTEQUAL } #[doc = "Checks if the value of the field is `EQUAL`"] #[inline(always)] pub fn is_equal(&self) -> bool { *self == COMP2VALUE_A::EQUAL } } #[doc = "Comparator 2 polarity selection bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2POLARITY_A { #[doc = "0: Comparator 2 output value not inverted"] NOTINVERTED = 0, #[doc = "1: Comparator 2 output value inverted"] INVERTED = 1, } impl From<COMP2POLARITY_A> for bool { #[inline(always)] fn from(variant: COMP2POLARITY_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2POLARITY`"] pub type COMP2POLARITY_R = crate::R<bool, COMP2POLARITY_A>; impl COMP2POLARITY_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2POLARITY_A { match self.bits { false => COMP2POLARITY_A::NOTINVERTED, true => COMP2POLARITY_A::INVERTED, } } #[doc = "Checks if the value of the field is `NOTINVERTED`"] #[inline(always)] pub fn is_not_inverted(&self) -> bool { *self == COMP2POLARITY_A::NOTINVERTED } #[doc = "Checks if the value of the field is `INVERTED`"] #[inline(always)] pub fn is_inverted(&self) -> bool { *self == COMP2POLARITY_A::INVERTED } } #[doc = "Write proxy for field `COMP2POLARITY`"] pub struct COMP2POLARITY_W<'a> { w: &'a mut W, } impl<'a> COMP2POLARITY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2POLARITY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Comparator 2 output value not inverted"] #[inline(always)] pub fn not_inverted(self) -> &'a mut W { self.variant(COMP2POLARITY_A::NOTINVERTED) } #[doc = "Comparator 2 output value inverted"] #[inline(always)] pub fn inverted(self) -> &'a mut W { self.variant(COMP2POLARITY_A::INVERTED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Comparator 2 LPTIM input 1 propagation bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2LPTIMIN1_A { #[doc = "0: Comparator 2 output gated"] GATED = 0, #[doc = "1: Comparator 2 output sent to LPTIM input 1"] NOTGATED = 1, } impl From<COMP2LPTIMIN1_A> for bool { #[inline(always)] fn from(variant: COMP2LPTIMIN1_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2LPTIMIN1`"] pub type COMP2LPTIMIN1_R = crate::R<bool, COMP2LPTIMIN1_A>; impl COMP2LPTIMIN1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2LPTIMIN1_A { match self.bits { false => COMP2LPTIMIN1_A::GATED, true => COMP2LPTIMIN1_A::NOTGATED, } } #[doc = "Checks if the value of the field is `GATED`"] #[inline(always)] pub fn is_gated(&self) -> bool { *self == COMP2LPTIMIN1_A::GATED } #[doc = "Checks if the value of the field is `NOTGATED`"] #[inline(always)] pub fn is_not_gated(&self) -> bool { *self == COMP2LPTIMIN1_A::NOTGATED } } #[doc = "Write proxy for field `COMP2LPTIMIN1`"] pub struct COMP2LPTIMIN1_W<'a> { w: &'a mut W, } impl<'a> COMP2LPTIMIN1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2LPTIMIN1_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Comparator 2 output gated"] #[inline(always)] pub fn gated(self) -> &'a mut W { self.variant(COMP2LPTIMIN1_A::GATED) } #[doc = "Comparator 2 output sent to LPTIM input 1"] #[inline(always)] pub fn not_gated(self) -> &'a mut W { self.variant(COMP2LPTIMIN1_A::NOTGATED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Comparator 2 LPTIM input 2 propagation bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2LPTIMIN2_A { #[doc = "0: Comparator 2 output gated"] GATED = 0, #[doc = "1: Comparator 2 output sent to LPTIM input 2"] NOTGATED = 1, } impl From<COMP2LPTIMIN2_A> for bool { #[inline(always)] fn from(variant: COMP2LPTIMIN2_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2LPTIMIN2`"] pub type COMP2LPTIMIN2_R = crate::R<bool, COMP2LPTIMIN2_A>; impl COMP2LPTIMIN2_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2LPTIMIN2_A { match self.bits { false => COMP2LPTIMIN2_A::GATED, true => COMP2LPTIMIN2_A::NOTGATED, } } #[doc = "Checks if the value of the field is `GATED`"] #[inline(always)] pub fn is_gated(&self) -> bool { *self == COMP2LPTIMIN2_A::GATED } #[doc = "Checks if the value of the field is `NOTGATED`"] #[inline(always)] pub fn is_not_gated(&self) -> bool { *self == COMP2LPTIMIN2_A::NOTGATED } } #[doc = "Write proxy for field `COMP2LPTIMIN2`"] pub struct COMP2LPTIMIN2_W<'a> { w: &'a mut W, } impl<'a> COMP2LPTIMIN2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2LPTIMIN2_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Comparator 2 output gated"] #[inline(always)] pub fn gated(self) -> &'a mut W { self.variant(COMP2LPTIMIN2_A::GATED) } #[doc = "Comparator 2 output sent to LPTIM input 2"] #[inline(always)] pub fn not_gated(self) -> &'a mut W { self.variant(COMP2LPTIMIN2_A::NOTGATED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Comparator 2 Input Plus connection configuration bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum COMP2INPSEL_A { #[doc = "0: PA3"] PA3 = 0, #[doc = "1: PB4"] PB4 = 1, #[doc = "2: PB5"] PB5 = 2, #[doc = "3: PB6"] PB6 = 3, #[doc = "4: PB7"] PB7 = 4, #[doc = "5: PA7"] PA7 = 5, } impl From<COMP2INPSEL_A> for u8 { #[inline(always)] fn from(variant: COMP2INPSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `COMP2INPSEL`"] pub type COMP2INPSEL_R = crate::R<u8, COMP2INPSEL_A>; impl COMP2INPSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, COMP2INPSEL_A> { use crate::Variant::*; match self.bits { 0 => Val(COMP2INPSEL_A::PA3), 1 => Val(COMP2INPSEL_A::PB4), 2 => Val(COMP2INPSEL_A::PB5), 3 => Val(COMP2INPSEL_A::PB6), 4 => Val(COMP2INPSEL_A::PB7), 5 => Val(COMP2INPSEL_A::PA7), i => Res(i), } } #[doc = "Checks if the value of the field is `PA3`"] #[inline(always)] pub fn is_pa3(&self) -> bool { *self == COMP2INPSEL_A::PA3 } #[doc = "Checks if the value of the field is `PB4`"] #[inline(always)] pub fn is_pb4(&self) -> bool { *self == COMP2INPSEL_A::PB4 } #[doc = "Checks if the value of the field is `PB5`"] #[inline(always)] pub fn is_pb5(&self) -> bool { *self == COMP2INPSEL_A::PB5 } #[doc = "Checks if the value of the field is `PB6`"] #[inline(always)] pub fn is_pb6(&self) -> bool { *self == COMP2INPSEL_A::PB6 } #[doc = "Checks if the value of the field is `PB7`"] #[inline(always)] pub fn is_pb7(&self) -> bool { *self == COMP2INPSEL_A::PB7 } #[doc = "Checks if the value of the field is `PA7`"] #[inline(always)] pub fn is_pa7(&self) -> bool { *self == COMP2INPSEL_A::PA7 } } #[doc = "Write proxy for field `COMP2INPSEL`"] pub struct COMP2INPSEL_W<'a> { w: &'a mut W, } impl<'a> COMP2INPSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2INPSEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "PA3"] #[inline(always)] pub fn pa3(self) -> &'a mut W { self.variant(COMP2INPSEL_A::PA3) } #[doc = "PB4"] #[inline(always)] pub fn pb4(self) -> &'a mut W { self.variant(COMP2INPSEL_A::PB4) } #[doc = "PB5"] #[inline(always)] pub fn pb5(self) -> &'a mut W { self.variant(COMP2INPSEL_A::PB5) } #[doc = "PB6"] #[inline(always)] pub fn pb6(self) -> &'a mut W { self.variant(COMP2INPSEL_A::PB6) } #[doc = "PB7"] #[inline(always)] pub fn pb7(self) -> &'a mut W { self.variant(COMP2INPSEL_A::PB7) } #[doc = "PA7"] #[inline(always)] pub fn pa7(self) -> &'a mut W { self.variant(COMP2INPSEL_A::PA7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 8)) | (((value as u32) & 0x07) << 8); self.w } } #[doc = "Comparator 2 Input Minus connection configuration bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum COMP2INNSEL_A { #[doc = "0: VREFINT"] VREFINT = 0, #[doc = "1: PA2"] PA2 = 1, #[doc = "2: PA4"] PA4 = 2, #[doc = "3: PA5"] PA5 = 3, #[doc = "4: 1/4 VREFINT"] VREFINT_DIV4 = 4, #[doc = "5: 1/2 VREFINT"] VREFINT_DIV2 = 5, #[doc = "6: 3/4 VREFINT"] VREFINT_DIV3_4 = 6, #[doc = "7: PB3"] PB3 = 7, } impl From<COMP2INNSEL_A> for u8 { #[inline(always)] fn from(variant: COMP2INNSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `COMP2INNSEL`"] pub type COMP2INNSEL_R = crate::R<u8, COMP2INNSEL_A>; impl COMP2INNSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2INNSEL_A { match self.bits { 0 => COMP2INNSEL_A::VREFINT, 1 => COMP2INNSEL_A::PA2, 2 => COMP2INNSEL_A::PA4, 3 => COMP2INNSEL_A::PA5, 4 => COMP2INNSEL_A::VREFINT_DIV4, 5 => COMP2INNSEL_A::VREFINT_DIV2, 6 => COMP2INNSEL_A::VREFINT_DIV3_4, 7 => COMP2INNSEL_A::PB3, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `VREFINT`"] #[inline(always)] pub fn is_vrefint(&self) -> bool { *self == COMP2INNSEL_A::VREFINT } #[doc = "Checks if the value of the field is `PA2`"] #[inline(always)] pub fn is_pa2(&self) -> bool { *self == COMP2INNSEL_A::PA2 } #[doc = "Checks if the value of the field is `PA4`"] #[inline(always)] pub fn is_pa4(&self) -> bool { *self == COMP2INNSEL_A::PA4 } #[doc = "Checks if the value of the field is `PA5`"] #[inline(always)] pub fn is_pa5(&self) -> bool { *self == COMP2INNSEL_A::PA5 } #[doc = "Checks if the value of the field is `VREFINT_DIV4`"] #[inline(always)] pub fn is_vrefint_div4(&self) -> bool { *self == COMP2INNSEL_A::VREFINT_DIV4 } #[doc = "Checks if the value of the field is `VREFINT_DIV2`"] #[inline(always)] pub fn is_vrefint_div2(&self) -> bool { *self == COMP2INNSEL_A::VREFINT_DIV2 } #[doc = "Checks if the value of the field is `VREFINT_DIV3_4`"] #[inline(always)] pub fn is_vrefint_div3_4(&self) -> bool { *self == COMP2INNSEL_A::VREFINT_DIV3_4 } #[doc = "Checks if the value of the field is `PB3`"] #[inline(always)] pub fn is_pb3(&self) -> bool { *self == COMP2INNSEL_A::PB3 } } #[doc = "Write proxy for field `COMP2INNSEL`"] pub struct COMP2INNSEL_W<'a> { w: &'a mut W, } impl<'a> COMP2INNSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2INNSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "VREFINT"] #[inline(always)] pub fn vrefint(self) -> &'a mut W { self.variant(COMP2INNSEL_A::VREFINT) } #[doc = "PA2"] #[inline(always)] pub fn pa2(self) -> &'a mut W { self.variant(COMP2INNSEL_A::PA2) } #[doc = "PA4"] #[inline(always)] pub fn pa4(self) -> &'a mut W { self.variant(COMP2INNSEL_A::PA4) } #[doc = "PA5"] #[inline(always)] pub fn pa5(self) -> &'a mut W { self.variant(COMP2INNSEL_A::PA5) } #[doc = "1/4 VREFINT"] #[inline(always)] pub fn vrefint_div4(self) -> &'a mut W { self.variant(COMP2INNSEL_A::VREFINT_DIV4) } #[doc = "1/2 VREFINT"] #[inline(always)] pub fn vrefint_div2(self) -> &'a mut W { self.variant(COMP2INNSEL_A::VREFINT_DIV2) } #[doc = "3/4 VREFINT"] #[inline(always)] pub fn vrefint_div3_4(self) -> &'a mut W { self.variant(COMP2INNSEL_A::VREFINT_DIV3_4) } #[doc = "PB3"] #[inline(always)] pub fn pb3(self) -> &'a mut W { self.variant(COMP2INNSEL_A::PB3) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 4)) | (((value as u32) & 0x07) << 4); self.w } } #[doc = "Comparator 2 power mode selection bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2SPEED_A { #[doc = "0: Slow speed"] SLOW = 0, #[doc = "1: Fast speed"] FAST = 1, } impl From<COMP2SPEED_A> for bool { #[inline(always)] fn from(variant: COMP2SPEED_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2SPEED`"] pub type COMP2SPEED_R = crate::R<bool, COMP2SPEED_A>; impl COMP2SPEED_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2SPEED_A { match self.bits { false => COMP2SPEED_A::SLOW, true => COMP2SPEED_A::FAST, } } #[doc = "Checks if the value of the field is `SLOW`"] #[inline(always)] pub fn is_slow(&self) -> bool { *self == COMP2SPEED_A::SLOW } #[doc = "Checks if the value of the field is `FAST`"] #[inline(always)] pub fn is_fast(&self) -> bool { *self == COMP2SPEED_A::FAST } } #[doc = "Write proxy for field `COMP2SPEED`"] pub struct COMP2SPEED_W<'a> { w: &'a mut W, } impl<'a> COMP2SPEED_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2SPEED_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Slow speed"] #[inline(always)] pub fn slow(self) -> &'a mut W { self.variant(COMP2SPEED_A::SLOW) } #[doc = "Fast speed"] #[inline(always)] pub fn fast(self) -> &'a mut W { self.variant(COMP2SPEED_A::FAST) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Comparator 2 enable bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP2EN_A { #[doc = "0: Comparator 2 switched OFF"] DISABLED = 0, #[doc = "1: Comparator 2 switched ON"] ENABLED = 1, } impl From<COMP2EN_A> for bool { #[inline(always)] fn from(variant: COMP2EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `COMP2EN`"] pub type COMP2EN_R = crate::R<bool, COMP2EN_A>; impl COMP2EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> COMP2EN_A { match self.bits { false => COMP2EN_A::DISABLED, true => COMP2EN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == COMP2EN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == COMP2EN_A::ENABLED } } #[doc = "Write proxy for field `COMP2EN`"] pub struct COMP2EN_W<'a> { w: &'a mut W, } impl<'a> COMP2EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP2EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Comparator 2 switched OFF"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(COMP2EN_A::DISABLED) } #[doc = "Comparator 2 switched ON"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(COMP2EN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 31 - COMP2_CSR register lock bit"] #[inline(always)] pub fn comp2lock(&self) -> COMP2LOCK_R { COMP2LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 20 - Comparator 2 output status bit"] #[inline(always)] pub fn comp2value(&self) -> COMP2VALUE_R { COMP2VALUE_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 15 - Comparator 2 polarity selection bit"] #[inline(always)] pub fn comp2polarity(&self) -> COMP2POLARITY_R { COMP2POLARITY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 13 - Comparator 2 LPTIM input 1 propagation bit"] #[inline(always)] pub fn comp2lptimin1(&self) -> COMP2LPTIMIN1_R { COMP2LPTIMIN1_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - Comparator 2 LPTIM input 2 propagation bit"] #[inline(always)] pub fn comp2lptimin2(&self) -> COMP2LPTIMIN2_R { COMP2LPTIMIN2_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bits 8:10 - Comparator 2 Input Plus connection configuration bit"] #[inline(always)] pub fn comp2inpsel(&self) -> COMP2INPSEL_R { COMP2INPSEL_R::new(((self.bits >> 8) & 0x07) as u8) } #[doc = "Bits 4:6 - Comparator 2 Input Minus connection configuration bit"] #[inline(always)] pub fn comp2innsel(&self) -> COMP2INNSEL_R { COMP2INNSEL_R::new(((self.bits >> 4) & 0x07) as u8) } #[doc = "Bit 3 - Comparator 2 power mode selection bit"] #[inline(always)] pub fn comp2speed(&self) -> COMP2SPEED_R { COMP2SPEED_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 0 - Comparator 2 enable bit"] #[inline(always)] pub fn comp2en(&self) -> COMP2EN_R { COMP2EN_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 15 - Comparator 2 polarity selection bit"] #[inline(always)] pub fn comp2polarity(&mut self) -> COMP2POLARITY_W { COMP2POLARITY_W { w: self } } #[doc = "Bit 13 - Comparator 2 LPTIM input 1 propagation bit"] #[inline(always)] pub fn comp2lptimin1(&mut self) -> COMP2LPTIMIN1_W { COMP2LPTIMIN1_W { w: self } } #[doc = "Bit 12 - Comparator 2 LPTIM input 2 propagation bit"] #[inline(always)] pub fn comp2lptimin2(&mut self) -> COMP2LPTIMIN2_W { COMP2LPTIMIN2_W { w: self } } #[doc = "Bits 8:10 - Comparator 2 Input Plus connection configuration bit"] #[inline(always)] pub fn comp2inpsel(&mut self) -> COMP2INPSEL_W { COMP2INPSEL_W { w: self } } #[doc = "Bits 4:6 - Comparator 2 Input Minus connection configuration bit"] #[inline(always)] pub fn comp2innsel(&mut self) -> COMP2INNSEL_W { COMP2INNSEL_W { w: self } } #[doc = "Bit 3 - Comparator 2 power mode selection bit"] #[inline(always)] pub fn comp2speed(&mut self) -> COMP2SPEED_W { COMP2SPEED_W { w: self } } #[doc = "Bit 0 - Comparator 2 enable bit"] #[inline(always)] pub fn comp2en(&mut self) -> COMP2EN_W { COMP2EN_W { w: self } } }
// This file is part of syslog2. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of syslog2. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. extern crate process; extern crate time; extern crate string_utilities; use self::string_utilities::to_cstr_best_effort; use std::io::Result; use syslogSenders::Rfc3164Facility; use syslogSenders::SyslogSender; use Severity; use syslog_cstr_withFacility; use rfc5424::StructuredData; #[allow(dead_code)] #[derive(Debug, Copy, Clone)] pub struct PosixSyslogSender { } impl PosixSyslogSender { /// Assumes the syslog2 is already open #[allow(dead_code)] fn new() -> Result<PosixSyslogSender> { Ok(PosixSyslogSender { }) } } impl SyslogSender for PosixSyslogSender { fn send(&mut self, rfc3164Facility: Rfc3164Facility, severity: Severity, structured_data_elements: &StructuredData, message: &str) -> Result<()> { let (cStringMessage, errorOption) = to_cstr_best_effort(message); syslog_cstr_withFacility(severity, &cStringMessage, rfc3164Facility.toFacilityMappingSolarisToDaemon()); match errorOption { None => Ok(()), Some(error) => Err(error), } } }
use graphics::math::Vec2d; pub struct AABB { pub center: Vec2d, pub half_size: Vec2d } impl AABB { pub fn new(center: Vec2d, half_size: Vec2d) -> AABB { AABB { center: center, half_size: half_size } } pub fn overlaps(&self, other: AABB) -> bool { if (self.center[0] - other.center[0]).abs() > self.half_size[0] + other.half_size[0] { return false; } if (self.center[1] - other.center[1]).abs() > self.half_size[1] + other.half_size[1] { return false; } return true; } pub fn overlaps_signed(&self, other: &AABB) -> (bool, Vec2d) { if self.half_size[0] == 0.0 || self.half_size[1] == 0.0 || other.half_size[0] == 0.0 || other.half_size[1] == 0.0 || (self.center[0] - other.center[0]).abs() > self.half_size[0] + other.half_size[0] || (self.center[1] - other.center[1]).abs() > self.half_size[1] + other.half_size[1] { return (false, [0.0, 0.0]); } let overlaps = [(self.center[0] - other.center[0]).signum() * ((other.half_size[0] + self.half_size[0]) - (self.center[0] - other.center[0]).abs()), (self.center[1] - other.center[1]).signum() * ((other.half_size[1] + self.half_size[1]) - (self.center[1] - other.center[1]).abs())]; (true, overlaps) } }
use crate::rpc; use crate::transaction_info::{Access, AccessMode, Target, TransactionInfo}; use std::collections::{BinaryHeap, HashMap, HashSet}; use web3::types::U256; fn is_wr_conflict(first: &TransactionInfo, second: &TransactionInfo) -> bool { for acc in second .accesses .iter() .filter(|a| a.mode == AccessMode::Read) { if let Target::Storage(addr, entry) = &acc.target { if first.accesses.contains(&Access::storage_write(addr, entry)) { return true; } } } false } #[derive(Default)] pub struct DependencyGraph { pub predecessors_of: HashMap<usize, Vec<usize>>, pub successors_of: HashMap<usize, Vec<usize>>, } impl DependencyGraph { pub fn simple(txs: &Vec<TransactionInfo>, info: &Vec<rpc::TxInfo>) -> DependencyGraph { DependencyGraph::with_sharding(txs, info, 1) } pub fn with_sharding( txs: &Vec<TransactionInfo>, info: &Vec<rpc::TxInfo>, counter_len: u64, ) -> DependencyGraph { assert!(counter_len > 0); let mut predecessors_of = HashMap::<usize, Vec<usize>>::new(); let mut successors_of = HashMap::<usize, Vec<usize>>::new(); for first in 0..(txs.len().saturating_sub(1)) { for second in (first + 1)..txs.len() { if info[first].from.to_low_u64_be() % counter_len != info[second].from.to_low_u64_be() % counter_len { continue; } if is_wr_conflict(&txs[first], &txs[second]) { predecessors_of.entry(second).or_insert(vec![]).push(first); successors_of.entry(first).or_insert(vec![]).push(second); } } } DependencyGraph { predecessors_of, successors_of, } } fn max_cost_from(&self, tx: usize, gas: &Vec<U256>, memo: &mut HashMap<usize, U256>) -> U256 { if let Some(result) = memo.get(&tx) { return result.clone(); } if !self.successors_of.contains_key(&tx) { return gas[tx]; } let max_of_successors = self.successors_of[&tx] .iter() .map(|succ| self.max_cost_from(*succ, gas, memo)) .max() .unwrap_or(U256::from(0)); let result = max_of_successors + gas[tx]; memo.insert(tx, result); result } pub fn max_costs(&self, gas: &Vec<U256>) -> HashMap<usize, U256> { let mut memo = HashMap::new(); (0..gas.len()) .map(|tx| (tx, self.max_cost_from(tx, gas, &mut memo))) .collect() } pub fn cost(&self, gas: &Vec<U256>, num_threads: usize) -> U256 { let num_txs = gas.len(); let max_cost_from = self.max_costs(gas); let mut threads: Vec<Option<(usize, U256)>> = vec![None; num_threads]; let mut finished: HashSet<usize> = Default::default(); let mut ready_txns: BinaryHeap<(U256, usize)> = Default::default(); let mut num_pre: Vec<usize> = vec![0; num_txs]; for txn_id in 0..num_txs { if self.predecessors_of.contains_key(&txn_id) { num_pre[txn_id] = self.predecessors_of.get(&txn_id).unwrap_or(&vec![]).len(); } else { ready_txns.push((max_cost_from[&txn_id], txn_id)); } } let mut cost = U256::from(0); loop { // exit condition if finished.len() == num_txs { // all threads are idle assert!(threads.iter().all(Option::is_none)); break; } // schedule txs on idle threads for thread_id in 0..threads.len() { if threads[thread_id].is_some() { continue; } let (_cur_max_cost_from, tx) = match ready_txns.pop() { Some((cur_max_cost_from, tx)) => (cur_max_cost_from, tx), None => break, }; // println!("scheduling tx-{} on thread-{}", tx, thread_id); threads[thread_id] = Some((tx, gas[tx])); } // execute transaction let (thread_id, (tx, gas_step)) = threads .iter() .enumerate() .filter(|(_, opt)| opt.is_some()) .map(|(id, opt)| (id, opt.unwrap())) .min_by_key(|(_, (_, gas))| gas.clone()) .unwrap(); // println!("finish executing tx-{} on thread-{}", tx, thread_id); threads[thread_id] = None; finished.insert(tx); for suc_txn in self.successors_of.get(&tx).cloned().unwrap_or(vec![]) { num_pre[suc_txn] -= 1; if num_pre[suc_txn] == 0 { ready_txns.push((max_cost_from[&suc_txn], suc_txn)); } } cost += gas_step; // update gas costs for ii in 0..threads.len() { if let Some((_, gas_left)) = &mut threads[ii] { *gas_left -= gas_step; } } } cost } } #[cfg(test)] mod tests { use super::*; use maplit::{convert_args, hashmap}; #[rustfmt::skip] #[test] fn test_cost() { let mut graph = DependencyGraph::default(); // 0 (1) - 1 (1) // 2 (1) - 3 (1) - 4 (1) - 5 (1) // 6 (1) - 7 (1) graph.predecessors_of = hashmap! { 1 => vec![0], 3 => vec![2], 4 => vec![3], 5 => vec![4], 7 => vec![6] }; graph.successors_of = hashmap! { 0 => vec![1], 2 => vec![3], 3 => vec![4], 4 => vec![5], 6 => vec![7] }; let gas = vec![1.into(); 8]; let expected = convert_args!(values=Into::into, hashmap! ( 0 => 2, 1 => 1, 2 => 4, 3 => 3, 4 => 2, 5 => 1, 6 => 2, 7 => 1 )); assert_eq!(graph.max_costs(&gas), expected); // 0 1 6 7 // 2 3 4 5 assert_eq!(graph.cost(&gas, 2), U256::from(4)); // ---------------------------------------- // 0 (1) - 1 (3) // 2 (1) - 3 (1) - 4 (1) - 5 (1) // 6 (1) - 7 (3) let gas = vec![1, 3, 1, 1, 1, 1, 1, 3].into_iter().map(Into::into).collect(); let expected = convert_args!(values=Into::into, hashmap! ( 0 => 4, 1 => 3, 2 => 4, 3 => 3, 4 => 2, 5 => 1, 6 => 4, 7 => 3 )); assert_eq!(graph.max_costs(&gas), expected); // 0 1 1 1 2 4 // 6 7 7 7 3 5 assert_eq!(graph.cost(&gas, 2), U256::from(6)); // ---------------------------------------- // 0 (1) - 1 (1) \ // 2 (1) - 3 (1) - 4 (1) - 5 (1) // 6 (1) - 7 (1) / graph.predecessors_of.insert(4, vec![1, 3, 7]); graph.successors_of.insert(1, vec![4]); graph.successors_of.insert(7, vec![4]); let gas = vec![U256::from(1); 8]; let expected = convert_args!(values=Into::into, hashmap! ( 0 => 4, 1 => 3, 2 => 4, 3 => 3, 4 => 2, 5 => 1, 6 => 4, 7 => 3 )); assert_eq!(graph.max_costs(&gas), expected); // 0 6 1 4 5 // 2 3 7 assert_eq!(graph.cost(&gas, 2), U256::from(5)); // ---------------------------------------- let graph = DependencyGraph::default(); // 0 (1) // 1 (1) // 2 (1) // 3 (1) // 5 (1) let gas = vec![U256::from(1); 5]; assert_eq!(graph.cost(&gas, 4), U256::from(2)); } }
#[derive(Debug)] #[derive(Clone)] enum Operator { Plus } #[derive(Debug)] #[derive(Clone)] enum Token { LeftParen, RightParen, Int(i32), Operator(Operator), Unknown, } fn tokenize_operator(st: &str) -> Token { return match st { "+" => Token::Operator(Operator::Plus), _ => Token::Unknown } } fn tokenize(st: &str) -> Vec<Token> { let replaced = st.replace("(", " ( ").replace(")", " ) "); return replaced.split_whitespace().map(|ch| { match ch.chars().next().unwrap() { '(' => Token::LeftParen, ')' => Token::RightParen, '+' | '-' | '*' | '/' => tokenize_operator(ch), '0' ... '9' => match ch.parse::<i32>() { Ok(i) => Token::Int(i), Err(_) => Token::Unknown, } _ => Token::Unknown, } }).collect(); } #[derive(Debug)] #[derive(Clone)] enum Op { Add, } #[derive(Debug)] #[derive(Clone)] enum AST { Atom(Token), Expr(Vec<AST>), } fn ast(tokens: Vec<Token>) -> Result<(Vec<AST>, Vec<Token>), &'static str> { let (first, rest) = match tokens.split_first() { Some((first, rest)) => (first, rest), None => return Result::Ok((vec![], vec![])), }; match first { Token::RightParen => { return Result::Ok((vec![], rest.to_vec())); }, Token::Int(_) | Token::Operator(_) => { let (result, rest) = ast(rest.to_vec()).unwrap(); let mut v = vec![AST::Atom(first.clone())]; v.extend(result); Result::Ok((v, rest)) }, Token::LeftParen => { let (result, remainder) = ast(rest.to_vec()).unwrap(); let mut v = vec![AST::Expr(result)]; let (result, _) = ast(remainder.to_vec()).unwrap(); v.extend(result); Result::Ok((v, vec![])) }, _ => return Result::Err("parse error"), } } fn pretty(v: Vec<AST>, prefix: String) { match v.split_first() { None => return, Some((AST::Atom(t), _)) => { println!("{}{:?}", prefix, t); }, Some((AST::Expr(t), _)) => { println!("{}Expr:", prefix); for token in t { pretty(vec![token.clone()], format!("{}{}", prefix, "\t")); } }, } } fn main() { // println!("Hello, world!"); // let input = "+ 500 700"; // println!("Got: {:?}", tokenize(&input)); // let input = "( + 500 700 )"; // println!("Got: {:?}", tokenize(&input)); // let input = "100"; // println!("Got: {:?}", ast(tokenize(&input))); // let input = "+ 100 200"; // println!("Got: {:?}", ast(tokenize(&input))); // let input = "(+ 100 200)"; // println!("Got: {:?}", ast(tokenize(&input))); //let input = "(+ 100 (+ 300 400))"; //println!("Got: {:?}", ast(tokenize(&input))); let input = "(+ (+ 300 400) + 100)"; println!("Got: {:?}", ast(tokenize(&input))); let input = "(+ (+ 200 300) (+ 400 500))"; pretty(ast(tokenize(&input)).unwrap().0, String::new()); let input = "(+ (+ 200 300) (+ (900 1000) 500))"; pretty(ast(tokenize(&input)).unwrap().0, String::new()); }//
use openssl::rsa::{Padding, Rsa}; use openssl::symm::{Cipher, Crypter, Mode}; //base64 use base64; //hex use rustc_serialize::hex::ToHex; //json use serde_json::{json, Value}; //random use rand::Rng; use lazy_static::*; lazy_static! { static ref IV: Vec<u8> = "0102030405060708".to_string().into_bytes(); static ref PRESET_KEY: Vec<u8> = "0CoJUm6Qyw8W8jud".to_string().into_bytes(); static ref LINUX_API_KEY: Vec<u8> = "rFgB&h#%2?^eDg:Q".to_string().into_bytes(); static ref BASE62:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".to_string(); static ref PUBLIC_KEY:String = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgtQn2JZ34ZC28NWYpAUd98iZ37BUrX/aKzmFbt7clFSs6sXqHauqKWqdtLkF2KexO40H1YTX8z2lSgBBOAxLsvaklV8k4cBFK9snQXE9/DDaFt6Rr7iVZMldczhC0JNgTz+SHXT6CBHuX3e9SdB1Ua44oncaTWz7OBGLbCiK45wIDAQAB\n-----END PUBLIC KEY-----".to_string(); static ref EAPI_KEY:Vec<u8> = "e82ckenh8dichen8".to_string().into_bytes(); static ref EMPTY_IV:Vec<u8> = "".to_string().into_bytes(); } pub fn aes_cbc_encrypt(buffer: Vec<u8>, key: &Vec<u8>, iv: &Vec<u8>) -> Vec<u8> { let mut encrypter = Crypter::new(Cipher::aes_128_cbc(), Mode::Encrypt, key, Some(iv)) .expect("fail to create encrypt"); let block_size = Cipher::aes_128_cbc().block_size(); let mut ciphertext = vec![0; buffer.len() + block_size]; let mut count = encrypter .update(buffer.as_slice(), &mut ciphertext) .unwrap(); count += encrypter.finalize(&mut ciphertext[count..]).unwrap(); ciphertext.truncate(count); ciphertext } pub fn aes_ecb_encrypt(buffer: Vec<u8>, key: &Vec<u8>, iv: &Vec<u8>) -> Vec<u8> { let mut encrypter = Crypter::new(Cipher::aes_128_ecb(), Mode::Encrypt, key, Some(iv)) .expect("fail to create encrypt"); let block_size = Cipher::aes_128_ecb().block_size(); let mut ciphertext = vec![0; buffer.len() + block_size]; let mut count = encrypter .update(buffer.as_slice(), &mut ciphertext) .unwrap(); count += encrypter.finalize(&mut ciphertext[count..]).unwrap(); ciphertext.truncate(count); ciphertext } pub fn _aes_ecb_decrypt(buffer: Vec<u8>) -> Vec<u8> { let mut decrypter = Crypter::new(Cipher::aes_128_ecb(), Mode::Encrypt, &(*EAPI_KEY), None) .expect("fail to create decrypt"); let block_size = Cipher::aes_128_ecb().block_size(); let mut plaintext = vec![0; buffer.len() + block_size]; let mut count = decrypter.update(buffer.as_slice(), &mut plaintext).unwrap(); count += decrypter.finalize(&mut plaintext[count..]).unwrap(); plaintext.truncate(count); plaintext } pub fn _rsa_encrypt(buffer: Vec<u8>, key: &String) -> Vec<u8> { let rsa = Rsa::public_key_from_pem((key.clone()).into_bytes().as_slice()).unwrap(); let mut encrypt_buffer = vec![0; 128 - buffer.len()]; encrypt_buffer.append(&mut buffer.clone()); let data = encrypt_buffer.as_slice(); let mut buf = vec![0; rsa.size() as usize]; rsa.public_encrypt(data, &mut buf, Padding::NONE).unwrap(); buf } pub fn weapi(obj: Value) -> Value { let mut rng = rand::thread_rng(); let bytes: Vec<u8> = (0..16).map(|_| rng.gen_range(0, 255)).collect(); let secret_key: String = bytes .iter() .map(|&n| BASE62.chars().nth(n as usize % 62).unwrap() as char) .collect(); let r_key = secret_key.chars().rev().collect::<String>(); json!({ "params":base64::encode(aes_cbc_encrypt( base64::encode(aes_cbc_encrypt(obj.to_string().into_bytes(),&(*PRESET_KEY),&(*IV))).into_bytes(), &secret_key.into_bytes(), &(*IV) )), "encSecKey":_rsa_encrypt(r_key.into_bytes(),&(*PUBLIC_KEY)).to_hex() }) } pub fn linuxapi(obj: Value) -> Value { json!({ "eparams":aes_ecb_encrypt(obj.to_string().into_bytes(),&(*LINUX_API_KEY),&(*EMPTY_IV)).to_hex().to_uppercase() }) } pub fn eapi(obj: Value, url: &String) -> Value { let text = obj.to_string(); let message = format!("nobody{}use{}md5forencrypt", url, text); let digest = md5::compute(&message).to_hex(); let data = format!("{}-36cd479b6b5-{}-36cd479b6b5-{}", url, text, digest); json!({ "params":aes_ecb_encrypt(data.into_bytes(),&(*EAPI_KEY),&(*EMPTY_IV)).to_hex().to_uppercase(), }) } pub fn crypto_test() { let _data: Value = json!({ "phone":"17757156690", // "countrycode":"86", // "password":md5::compute("950926Wg").to_hex(), // "rememberLogin":"true", // "csrf_token":"", }); let res = eapi(_data, &"www.baidu.com".to_string()); println!("res is {:#?}", res); // let s = "{\"phone\":\"17757156690\",\"countrycode\":\"86\",\"password\":\"d16568c8aeeb4606f53d597408eec7f7\",\"rememberLogin\":\"true\",\"csrf_token\":\"09f260f44153079272eebc530f5ad769\"}".to_string(); // let res = base64::encode(aes_cbc_encrypt(s.into_bytes(),&(*PRESET_KEY),&(*IV))); // println!("res is {:#?}",res); // let secret_key = "abcdefghijklmnop".to_string(); // let r_key = secret_key.chars().rev().collect::<String>(); // let res = base64::encode(aes_cbc_encrypt(res.into_bytes(),&secret_key.into_bytes(), &(*IV))); // println!("res is {:#?}", res); // let res2 = _rsa_encrypt(r_key.into_bytes(),&(*PUBLIC_KEY)).to_hex(); // println!("res2 is {:#?}",res2); }
use axum::{ http::StatusCode, response::{IntoResponse, Response}, }; pub struct AppError(anyhow::Error); impl IntoResponse for AppError { fn into_response(self) -> Response { let AppError(err) = self; ( StatusCode::INTERNAL_SERVER_ERROR, err.backtrace().to_string(), ) .into_response() } } impl<E> From<E> for AppError where E: Into<anyhow::Error>, { fn from(err: E) -> Self { Self(err.into()) } }
use tge::error::GameResult; use tge::math::{Vector, Position, Point, Scale, Size, Angle}; use tge::engine::{Engine, EngineBuilder}; use tge::window::WindowConfig; use tge::graphics::*; use tge::mouse::MouseButton; use tge::game::Game; use rand::Rng; use rand::rngs::ThreadRng; const TITLE: &str = "Sprites"; const STEP_COUNT: usize = 100; struct Sprite { position: Position, speed: Vector, angle: Angle, angle_speed: Angle, scale: Scale, color: Color, } impl Sprite { fn new(rand: &mut ThreadRng, graphics_size: &Size) -> Self { let x = rand.gen_range(0.0, graphics_size.width); let y = rand.gen_range(0.0, graphics_size.height); let speed_x = rand.gen_range(-100.0, 100.0); let speed_y = rand.gen_range(-100.0, 100.0); let angle = rand.gen_range(0.0, std::f32::consts::PI * 2.0); let angle_speed = rand.gen_range(-10.0, 10.0); let scale = rand.gen_range(0.5, 1.0); let red = rand.gen_range(0.5, 1.0); let green = rand.gen_range(0.5, 1.0); let blue = rand.gen_range(0.5, 1.0); let alpha = rand.gen_range(0.5, 1.0); Self { position: Position::new(x, y), speed: Vector::new(speed_x, speed_y), angle: Angle::radians(angle), angle_speed: Angle::radians(angle_speed), scale: Scale::new(scale, scale), color: Color::new(red, green, blue, alpha), } } } struct App { zazaka: Texture, rand: ThreadRng, sprites: Vec<Sprite>, } impl App { fn new(engine: &mut Engine) -> GameResult<Self> { let zazaka = Texture::load(engine, "assets/zazaka.png")?; let mut rand = rand::thread_rng(); let mut sprites = Vec::with_capacity(STEP_COUNT); let graphics_size = engine.graphics().size(); for _ in 0..STEP_COUNT { sprites.push(Sprite::new(&mut rand, &graphics_size)); } Ok(Self { zazaka, rand, sprites, }) } } impl Game for App { fn update(&mut self, engine: &mut Engine) -> GameResult { let title = format!("{}: {} - FPS: {}", TITLE, self.sprites.len(), engine.timer().real_time_fps().round()); engine.window().set_title(title); let delta_time_f32 = engine.timer().delta_time().as_secs_f32(); let graphics_size = engine.graphics().size(); if engine.mouse().is_button_down(MouseButton::Left) { for _ in 0..STEP_COUNT { self.sprites.push(Sprite::new(&mut self.rand, &graphics_size)); } } for sprite in &mut self.sprites { sprite.position.x += sprite.speed.x * delta_time_f32; sprite.position.y += sprite.speed.y * delta_time_f32; if sprite.position.x < 0.0 { sprite.position.x = 0.0; sprite.speed.x *= -1.0; } if sprite.position.x > graphics_size.width { sprite.position.x = graphics_size.width; sprite.speed.x *= -1.0; } if sprite.position.y < 0.0 { sprite.position.y = 0.0; sprite.speed.y *= -1.0; } if sprite.position.y > graphics_size.height { sprite.position.y = graphics_size.height; sprite.speed.y *= -1.0; } sprite.angle += sprite.angle_speed * delta_time_f32; } Ok(()) } fn render(&mut self, engine: &mut Engine) -> GameResult { engine.graphics().clear(Color::BLACK); let origin = { let size = self.zazaka.size(); Point::new(size.width as f32 / 2.0, size.height as f32 / 2.0) }; for sprite in self.sprites.iter() { engine.graphics().draw_sprite( Some(&self.zazaka), SpriteDrawParams::default() .origin(origin) .position(sprite.position) .rotation(sprite.angle) .scale(sprite.scale) .color(sprite.color), ); } Ok(()) } } fn main() -> GameResult { EngineBuilder::new() .window_config(WindowConfig::new() .title(TITLE) .inner_size((1280.0, 720.0))) .graphics_config(GraphicsConfig::new() .default_filter(Filter::new( FilterMode::Nearest, FilterMode::Nearest, None, ))) .build()? .run_with(App::new) }
use std::convert::TryFrom; use std::path::Path; use std::str; use anyhow::{Context, Result}; use needletail::{parse_sequence_path, SequenceRecord}; use crate::{Alignment, Sequence}; /// Reads an Alignment contained in a fasta file into the Alignment struct. /// The name of the Alignment is the `file_stem` (the non-extension part) /// of the provided path. pub fn parse(path: impl AsRef<Path>) -> Result<Alignment> { let mut sequences = vec![]; parse_sequence_path(&path, |_| {}, |seq| sequences.push(Sequence::try_from(seq)))?; let aligned_data: Vec<_> = sequences.into_iter().collect::<Result<_>>()?; let name = path .as_ref() .file_stem() .context("No filestem for fasta file")? .to_string_lossy() .into_owned(); let alig_len = aligned_data.first().context("Empty alignment")?.data.len(); let core_blocks = vec![true; alig_len]; Ok(Alignment::new(name, aligned_data, core_blocks)) } impl<'a> TryFrom<SequenceRecord<'a>> for Sequence { type Error = anyhow::Error; fn try_from(seq: SequenceRecord) -> Result<Self> { Ok(Sequence { name: str::from_utf8(&seq.id)?.to_string(), data: seq.seq.to_vec(), }) } }
use crate::bot::utils::Utils; use crate::extensions::ClientContextExt; use serenity::model::prelude::Guild; use serenity::prelude::Context; pub struct GuildCreateEvent; impl GuildCreateEvent { pub async fn run(ctx: &Context, guild: &Guild, is_new: &bool) { if !is_new { return; } let config = ctx.get_config().await; match guild.system_channel_id { Some(channel) => Utils::check_msg( channel .send_message(&ctx.http, |m| { m.embed(|e| { e.title("Thanks for adding me!") .description( "To start you need to setup a launches channel. \ This can be done with `>config channel #launches`. \ I will send launch reminders in that channel", ) .footer(|f| { f.text(&guild.name).icon_url( &guild.icon_url().unwrap_or_else(|| " ".to_string()), ) }) }) }) .await, ), None => return, } let log_channel = config.log_channel_id.fetch(ctx).await.unwrap(); let owner_name = match Utils::fetch_user_forced(ctx, guild.owner_id.0).await { Some(owner) => owner.name, None => "Owner not found".to_string(), }; Utils::check_msg( log_channel .id() .send_message(&ctx.http, |m| { m.embed(|e| { e.title("Joined Guild") .description(format!( "➤ Member count: **{}**\n➤ Owner: **{}**", &guild.member_count, owner_name )) .footer(|f| { f.text(&guild.name) .icon_url(&guild.icon_url().unwrap_or_else(|| " ".to_string())) }) .thumbnail(&guild.icon_url().unwrap_or_else(|| " ".to_string())) }) }) .await, ) } }
//! Sup Commands use crate::result::Result; use std::path::PathBuf; use structopt::{clap::AppSettings, StructOpt}; pub mod new; pub mod source; pub mod tag; pub mod update; pub mod upgrade; #[derive(StructOpt, Debug)] #[structopt(setting = AppSettings::InferSubcommands)] enum Opt { /// Create a new substrate node template New { /// Package path #[structopt(name = "PATH")] path: PathBuf, /// If skip toolchain check #[structopt(short, long)] skip: bool, }, /// List available tags Tag { /// The limit count of tags #[structopt(short, long, default_value = "10")] limit: usize, /// If update registry #[structopt(short, long)] update: bool, }, /// Update registry Update, /// List Source Source { /// Show dependencies contain <query> #[structopt(short, long, default_value = "")] query: String, /// If show versions #[structopt(short, long)] version: bool, }, /// Upgrade substrate project Upgrade { /// Project path #[structopt(short, long, default_value = ".")] path: PathBuf, /// Registry tag #[structopt(short, long, default_value = "")] tag: String, /// If update registry #[structopt(short, long)] update: bool, }, } /// Exec commands pub fn exec() -> Result<()> { let opt = Opt::from_args(); match opt { Opt::New { path, skip } => new::exec(path, skip)?, Opt::Tag { limit, update } => tag::exec(limit, update)?, Opt::Update => update::exec()?, Opt::Upgrade { tag, path, update } => upgrade::exec(path, tag, update)?, Opt::Source { query, version } => source::exec(query, version)?, } Ok(()) }
use sqlx::postgres::PgPool; use crate::utils::config::{is_containerized_development_mode, is_production_mode, CONFIG}; // Mode control lazy_static! { static ref DATABASE_URL: String = { match is_production_mode() { true => format!( "postgres://{}:{}@{}:{}/{}", CONFIG.production.database.pg_user, CONFIG.production.database.pg_pass, CONFIG.production.database.pg_host, CONFIG.production.database.pg_port, CONFIG.production.database.pg_db, ), false => match is_containerized_development_mode() { true => format!( "postgres://{}:{}@{}:{}/{}", CONFIG.containerized.database.pg_user, CONFIG.containerized.database.pg_pass, CONFIG.containerized.database.pg_host, CONFIG.containerized.database.pg_port, CONFIG.containerized.database.pg_db, ), false => format!( "postgres://{}:{}@{}:{}/{}", CONFIG.development.database.pg_user, CONFIG.development.database.pg_pass, CONFIG.development.database.pg_host, CONFIG.development.database.pg_port, CONFIG.development.database.pg_db, ), }, } }; } pub async fn get_pg_pool() -> anyhow::Result<PgPool> { Ok(PgPool::connect(&DATABASE_URL).await?) }
use std::error::Error; use std::fs; use std::path::Path; use heed::types::*; use heed::{Database, EnvOpenOptions}; fn main() -> Result<(), Box<dyn Error>> { let env1_path = Path::new("target").join("env1.mdb"); let env2_path = Path::new("target").join("env2.mdb"); fs::create_dir_all(&env1_path)?; let env1 = EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(env1_path)?; fs::create_dir_all(&env2_path)?; let env2 = EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(env2_path)?; let db1: Database<Str, ByteSlice> = env1.create_database(Some("hello"))?; let db2: Database<OwnedType<u32>, OwnedType<u32>> = env2.create_database(Some("hello"))?; // clear db let mut wtxn = env1.write_txn()?; db1.clear(&mut wtxn)?; wtxn.commit()?; // clear db let mut wtxn = env2.write_txn()?; db2.clear(&mut wtxn)?; wtxn.commit()?; // ----- let mut wtxn1 = env1.write_txn()?; db1.put(&mut wtxn1, "what", &[4, 5][..])?; db1.get(&wtxn1, "what")?; wtxn1.commit()?; let rtxn2 = env2.read_txn()?; let ret = db2.last(&rtxn2)?; assert_eq!(ret, None); Ok(()) }
use rand; use rand::Rng; /// Generates random numbers with help of random-number /// generator `rand::Rng` obtained via `rand::thread_rng` /// https://docs.rs/rand/ pub fn run_basic() { // Each thread has an automatically-initialised random number generator: let mut rng = rand::thread_rng(); // Integers are uniformly distributed over the type's whole range: let n1: u8 = rng.gen(); let n2: u16 = rng.gen(); println!("random u8: {}", n1); println!("random u16: {}", n2); println!("random u32: {}", rng.gen::<u32>()); println!("random i32: {}", rng.gen::<i32>()); // Floating point numbers are uniformly distributed in the half-open range [0, 1)] println!("Random float: {}", rng.gen::<f64>()); } /// Generates a random value within half-open [0, 10) range (not include 10) with /// `Rng::gen_range` pub fn run_with_a_range() { let mut rng = rand::thread_rng(); println!("Range integer in [0, 10): {}", rng.gen_range(0, 10)); println!("Range float in [0, 10): {}", rng.gen_range(0.0, 10.0)); } // One can use `Range` to obtain value with [uniform // distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)). // This has the same effect, but may be faster when repeatedly generating numbers // in the same range. use rand::distributions::{Range, IndependentSample}; pub fn run_with_a_range_independent() { let mut rng = rand::thread_rng(); let die = Range::new(1, 7); loop { let throw = die.ind_sample(&mut rng); println!("Rool the die: {}", throw); if throw == 6 { break; } } } /// By default, random numbers are generated with uniform distribution. /// To generate numbers with other distributions you instantiate a distribution, /// then sample from that distribution using `IndependentSample::ind_sample` with /// help of a random-number generator `rand::Rng`. /// /// The [distributions available are documented /// here](https://doc.rust-lang.org/rand/rand/distributions/index.html). An example using the /// `Normal` distribution is shown below. use rand::distributions::Normal; pub fn run_with_given_distribution() { let mut rng = rand::thread_rng(); // mean 2, standard deviation: 3 let normal = Normal::new(2.0, 3.0); let v = normal.ind_sample(&mut rng); println!("{} if from a N(2, 3) distribtuion", v); } /// # Generate random values of a custom type /// Randomly generates a tumple (i32, bool, f64) and variable of user defined type Point. /// Implements the `rand::Rand` trait for Point in order to allow random generation. use rand::Rand; #[derive(Debug)] struct Point { x: i32, y: i32, } impl Rand for Point { fn rand<R: Rng>(rng: &mut R) -> Point { let (rand_x, rand_y) = rng.gen(); Point { x: rand_x, y: rand_y, } } } pub fn run_range_for_a_type() { let mut rng = rand::thread_rng(); let rand_tuple = rng.gen::<(i32, bool, f64)>(); let rand_point: Point = rng.gen(); println!("Random tuple: {:?}", rand_tuple); println!("Random Point: {:?}", rand_point); }
#[doc = "Reader of register _9BITADDR"] pub type R = crate::R<u32, super::_9BITADDR>; #[doc = "Writer for register _9BITADDR"] pub type W = crate::W<u32, super::_9BITADDR>; #[doc = "Register _9BITADDR `reset()`'s with value 0"] impl crate::ResetValue for super::_9BITADDR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `ADDR`"] pub type ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADDR`"] pub struct ADDR_W<'a> { w: &'a mut W, } impl<'a> ADDR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } #[doc = "Reader of field `_9BITEN`"] pub type _9BITEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `_9BITEN`"] pub struct _9BITEN_W<'a> { w: &'a mut W, } impl<'a> _9BITEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } impl R { #[doc = "Bits 0:7 - Self Address for 9-Bit Mode"] #[inline(always)] pub fn addr(&self) -> ADDR_R { ADDR_R::new((self.bits & 0xff) as u8) } #[doc = "Bit 15 - Enable 9-Bit Mode"] #[inline(always)] pub fn _9biten(&self) -> _9BITEN_R { _9BITEN_R::new(((self.bits >> 15) & 0x01) != 0) } } impl W { #[doc = "Bits 0:7 - Self Address for 9-Bit Mode"] #[inline(always)] pub fn addr(&mut self) -> ADDR_W { ADDR_W { w: self } } #[doc = "Bit 15 - Enable 9-Bit Mode"] #[inline(always)] pub fn _9biten(&mut self) -> _9BITEN_W { _9BITEN_W { w: self } } }
//! Custom test runner for building/running unit tests on the 3DS. extern crate test; use std::io; use test::{ColorConfig, OutputFormat, TestDescAndFn, TestFn, TestOpts}; use crate::prelude::*; /// A custom runner to be used with `#[test_runner]`. This simple implementation /// runs all tests in series, "failing" on the first one to panic (really, the /// panic is just treated the same as any normal application panic). pub(crate) fn run(tests: &[&TestDescAndFn]) { let gfx = Gfx::new().unwrap(); let mut hid = Hid::new().unwrap(); let apt = Apt::new().unwrap(); let mut top_screen = gfx.top_screen.borrow_mut(); top_screen.set_wide_mode(true); let _console = Console::new(top_screen); let opts = TestOpts { force_run_in_process: true, run_tests: true, // TODO: color doesn't work because of TERM/TERMINFO. // With RomFS we might be able to fake this out nicely... color: ColorConfig::AutoColor, format: OutputFormat::Pretty, // Hopefully this interface is more stable vs specifying individual options, // and parsing the empty list of args should always work, I think. // TODO Ideally we could pass actual std::env::args() here too ..test::test::parse_opts(&[]).unwrap().unwrap() }; // Use the default test implementation with our hardcoded options let _success = run_static_tests(&opts, tests).unwrap(); // Make sure the user can actually see the results before we exit println!("Press START to exit."); while apt.main_loop() { gfx.wait_for_vblank(); hid.scan_input(); if hid.keys_down().contains(KeyPad::START) { break; } } } /// Adapted from [`test::test_main_static`] and [`test::make_owned_test`]. fn run_static_tests(opts: &TestOpts, tests: &[&TestDescAndFn]) -> io::Result<bool> { let tests = tests.iter().map(make_owned_test).collect(); test::run_tests_console(opts, tests) } /// Clones static values for putting into a dynamic vector, which test_main() /// needs to hand out ownership of tests to parallel test runners. /// /// This will panic when fed any dynamic tests, because they cannot be cloned. fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn { match test.testfn { TestFn::StaticTestFn(f) => TestDescAndFn { testfn: TestFn::StaticTestFn(f), desc: test.desc.clone(), }, TestFn::StaticBenchFn(f) => TestDescAndFn { testfn: TestFn::StaticBenchFn(f), desc: test.desc.clone(), }, _ => panic!("non-static tests passed to test::test_main_static"), } }
// pub enum Dir { // N, // S, // E, // W // } use commons::add_u32; #[derive(Debug, Clone, Copy, PartialEq, Hash)] pub struct GridCoord { pub x: u32, pub y: u32, } impl GridCoord { pub fn new(x: u32, y: u32) -> Self { GridCoord { x, y } } pub fn translate(&self, dx: i32, dy: i32) -> Option<GridCoord> { let new_x = add_u32(self.x, dx)?; let new_y = add_u32(self.y, dy)?; Some(GridCoord::new(new_x, new_y)) } } impl From<(u32, u32)> for GridCoord { fn from((x, y): (u32, u32)) -> Self { GridCoord { x, y } } } #[derive(Debug, Clone)] pub struct Grid<T> { pub width: u32, pub height: u32, pub list: Vec<Option<T>>, } impl<T> Grid<T> { pub fn new(width: u32, height: u32) -> Self { let mut list = vec![]; for _ in 0..width * height { list.push(None); } Grid { width, height, list, } } // TODO: should it exists? pub fn set(&mut self, index: u32, value: Option<T>) { self.list[index as usize] = value; } pub fn set_at(&mut self, coord: GridCoord, value: Option<T>) { if !self.is_valid_coords(coord) { panic!("invalid coords {:?}", coord); } let index = self.coords_to_index(coord); self.list[index as usize] = value; } // TODO: should it exists? pub fn get(&self, index: u32) -> Option<&T> { self.list[index as usize].as_ref() } pub fn get_at(&self, coord: GridCoord) -> Option<&T> { if !self.is_valid_coords(coord) { panic!("invalid coords {:?}", coord); } let index = self.coords_to_index(coord); self.list[index as usize].as_ref() } pub fn is_valid_coords(&self, coords: GridCoord) -> bool { coords.x < self.width && coords.y < self.height } // TODO: should return option? pub fn coords_to_index(&self, coords: GridCoord) -> u32 { coords.y * self.width + coords.x } pub fn get_neighbours(&self, coords: GridCoord) -> Vec<GridCoord> { let mut result = vec![]; for dy in &[-1, 0, 1] { for dx in &[-1, 0, 1] { if *dx == 0 && *dy == 0 { continue; } let new_point = match coords.translate(*dx, *dy) { None => continue, Some(v) => v, }; if new_point.x >= self.width || new_point.y >= self.height { continue; } result.push(new_point); } } result } pub fn raytrace(&self, pos: GridCoord, dir_x: i32, dir_y: i32) -> Vec<GridCoord> { let mut current = pos; let mut result = vec![]; loop { let nx = current.x as i32 + dir_x; let ny = current.y as i32 + dir_y; if nx < 0 || ny < 0 { break; } current = (nx as u32, ny as u32).into(); if !self.is_valid_coords(current) { break; } match self.get_at(current) { Some(value) => result.push(current), None => break, } } result } } #[cfg(test)] mod test { use super::*; #[test] pub fn test_grid_get_neighbors() { let mut grid = Grid::<u32>::new(2, 2); let neighbours = grid.get_neighbours(GridCoord::new(0, 0)); assert_eq!( neighbours, vec![ GridCoord::new(1, 0), GridCoord::new(0, 1), GridCoord::new(1, 1), ] ); } #[test] pub fn test_grid_raytrace() { let mut grid = Grid::<u32>::new(4, 2); // X### // ### assert_eq!(grid.raytrace((0, 0).into(), -1, 0), Vec::<GridCoord>::new()); // #X## // #### assert_eq!(grid.raytrace((1, 0).into(), -1, 0), Vec::<GridCoord>::new()); // 0### // #### grid.set_at((0, 0).into(), Some(0)); // 0X## // #### assert_eq!(grid.raytrace((1, 0).into(), -1, 0), vec![(0, 0).into()]); // 00## // #### grid.set_at((1, 0).into(), Some(0)); // 00X# // #### assert_eq!( grid.raytrace((2, 0).into(), -1, 0), vec![(1, 0).into(), (0, 0).into()] ); // 00#X // #### assert_eq!(grid.raytrace((3, 0).into(), -1, 0), vec![]); // X0## // #### assert_eq!(grid.raytrace((0, 0).into(), 1, 0), vec![(1, 0).into()]); } #[test] pub fn test_grid_group() { // TODO } }
use crate::{ geom::Rectangle, graphics::Image }; use std::rc::Rc; #[derive(Debug)] struct AnimationData { frames: Vec<Image> } #[derive(Clone, Debug)] /// A linear series of images with a constant frame delay /// /// Frames advance by discrete ticks, which should be run in the `update` section of a /// quicksilver application loop rather than the `draw` section. Draws may happen as /// often as possible, whereas updates will have consistent rates pub struct Animation { data: Rc<AnimationData>, current: usize, current_time: u32, frame_delay: u32 } impl Animation { /// Create a new animation from a series of images and a frame delay pub fn new<I>(images: I, frame_delay: u32) -> Animation where I: IntoIterator<Item = Image> { let frames = images.into_iter().collect(); Animation { data: Rc::new(AnimationData { frames }), current: 0, current_time: 0, frame_delay } } /// Create a new animation from regions of images from a spritesheet pub fn from_spritesheet<R>(sheet: Image, regions: R, frame_delay: u32) -> Animation where R: IntoIterator<Item = Rectangle> { Animation::new(regions.into_iter() .map(|region| sheet.subimage(region)), frame_delay) } /// Tick the animation forward by one step pub fn tick(&mut self) { self.current_time += 1; if self.current_time >= self.frame_delay { self.current = (self.current + 1) % self.data.frames.len(); self.current_time = 0; } } /// Get the current frame of the animation pub fn current_frame(&self) -> &Image { &self.data.frames[self.current] } }
// Sedgewick, p.249 // Cormen, p.29 /// Selection sort. /// /// Time complexity: /// /// * best: Ω(n^2) /// * avg: Θ(n^2) /// * worst: O(n^2) /// /// Space complexity: /// /// * O(1) pub fn sort<T: Ord>(input: &mut Vec<T>) { let size = input.len(); for i in 0..size { let mut min = i; for j in (i + 1)..size { if input[j] < input[min] { min = j; } } input.swap(i, min); } } add_common_tests!();
mod with_atom_process_identifier; mod with_local_pid_process_identifier; mod with_tuple_process_identifier; use super::*; #[test] fn without_process_identifier_errors_badarg() { with_process_arc(|arc_process| { TestRunner::new(Config::with_source_file(file!())) .run( &is_not_process_identifier(arc_process.clone()), |process_identifier| { prop_assert_badarg!( result(&arc_process, r#type(), process_identifier), "process identifier must be `pid | registered_name() | {registered_name(), node()}`" ); Ok(()) }, ) .unwrap(); }); } fn is_not_process_identifier(arc_process: Arc<Process>) -> BoxedStrategy<Term> { prop_oneof![ strategy::term::is_list(arc_process.clone()), strategy::term::local_reference(arc_process.clone()), strategy::term::is_function(arc_process.clone()), strategy::term::is_number(arc_process.clone()), strategy::term::is_bitstring(arc_process.clone()) ] .boxed() } fn r#type() -> Term { Atom::str_to_term("process") }
use std::ops; use std::f32; use super::deg2rad; #[derive(Debug, Clone, PartialEq)] pub struct Vec2 { pub x: f32, pub y: f32 } // indices impl ops::Index<usize> for Vec2 { type Output = f32; fn index<'a>(&'a self, index: usize) -> &f32 { match index { 0 => &self.x, 1 => &self.y, _ => panic!() } } } impl ops::IndexMut<usize> for Vec2 { fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut f32 { match index { 0 => &mut self.x, 1 => &mut self.y, _ => panic!() } } } // add ops impl ops::Add for Vec2 { type Output = Vec2; fn add(self, other: Vec2) -> Vec2 { Vec2 { x: self.x + other.x, y: self.y + other.y } } } impl ops::AddAssign for Vec2 { fn add_assign(&mut self, other: Vec2) { *self = self.clone() + other; } } // sub ops impl ops::Sub for Vec2 { type Output = Vec2; fn sub(self, other: Vec2) -> Vec2 { Vec2 { x: self.x - other.x, y: self.y - other.y } } } impl ops::SubAssign for Vec2 { fn sub_assign(&mut self, other: Vec2) { *self = self.clone() - other; } } // mul ops impl ops::Mul<Vec2> for Vec2 { type Output = Vec2; fn mul(self, other: Vec2) -> Vec2 { Vec2 { x: self.x * other.x, y: self.y * other.y } } } impl ops::Mul<f32> for Vec2 { type Output = Vec2; fn mul(self, real: f32) -> Vec2 { Vec2 { x: self.x * real, y: self.y * real } } } impl ops::MulAssign<Vec2> for Vec2 { fn mul_assign(&mut self, other: Vec2) { *self = self.clone() * other; } } impl ops::MulAssign<f32> for Vec2 { fn mul_assign(&mut self, other: f32) { *self = self.clone() * other; } } // div ops impl ops::Div<Vec2> for Vec2 { type Output = Vec2; fn div(self, other: Vec2) -> Vec2 { Vec2 { x: self.x / other.x, y: self.y / other.y } } } impl ops::Div<f32> for Vec2 { type Output = Vec2; fn div(self, real: f32) -> Vec2 { Vec2 { x: self.x / real, y: self.y / real } } } impl ops::DivAssign<Vec2> for Vec2 { fn div_assign(&mut self, other: Vec2) { *self = self.clone() / other; } } impl ops::DivAssign<f32> for Vec2 { fn div_assign(&mut self, other: f32) { *self = self.clone() / other; } } // other functions impl Vec2 { pub fn lenght(&self) -> f32 { (self.x * self.x + self.y * self.y).sqrt() } pub fn dot(&self, other: Vec2) -> f32 { self.x * other.x + self.y * other.y } pub fn normalized(&self) -> Vec2 { self.clone() / self.clone().lenght() } pub fn distance_to(&self, other: Vec2) -> f32 { ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt() } pub fn rotate(&self, degrees: f32) -> Vec2 { let rad = deg2rad(degrees); let a_cos = rad.cos(); let a_sin = rad.sin(); Vec2 { x: self.x * a_cos - self.y * a_sin, y: self.x * a_sin + self.y * a_cos } } }
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn main() { input! { n: usize, s: [String; n], } let mut count = HashMap::new(); for si in &s { if !count.contains_key(&si) { count.insert(si, 0); } *count.get_mut(&si).unwrap() += 1; } let mut count = count.into_iter().map(|(k, v)| (v, k)).collect::<Vec<_>>(); count.sort(); count.reverse(); let c = count[0].0; let count = count .into_iter() .filter(|(ci, _)| *ci == c) .collect::<Vec<_>>(); for (_, si) in count.iter().rev() { println!("{}", si); } }
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for #36053. ICE was caused due to obligations being // added to a special, dedicated fulfillment cx during a // probe. Problem seems to be related to the particular definition of // `FusedIterator` in std but I was not able to isolate that into an // external crate. use std::iter::FusedIterator; struct Thing<'a>(&'a str); impl<'a> Iterator for Thing<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { None } } impl<'a> FusedIterator for Thing<'a> {} fn main() { Thing("test").fuse().filter(|_| true).count(); }
#[macro_export] macro_rules! name_type { ($ident:ident) => { #[derive( Debug, PartialEq, Eq, Clone, Copy, Default, Hash, PartialOrd, Ord, crate::bytes::Read, crate::bytes::Write, crate::bytes::NumBytes, )] #[eosio(crate_path = "crate::bytes")] pub struct $ident($crate::name::Name); impl $ident { #[must_use] pub const fn new(value: u64) -> Self { Self($crate::name::Name::new(value)) } #[must_use] pub const fn as_u64(&self) -> u64 { self.0.as_u64() } #[must_use] pub const fn as_name(&self) -> $crate::name::Name { self.0 } } impl core::ops::Deref for $ident { type Target = $crate::name::Name; #[must_use] fn deref(&self) -> &Self::Target { &self.0 } } impl core::convert::AsRef<$crate::name::Name> for $ident { #[must_use] fn as_ref(&self) -> &$crate::name::Name { &self.0 } } impl core::convert::AsRef<$ident> for $ident { #[must_use] fn as_ref(&self) -> &Self { self } } impl From<u64> for $ident { #[must_use] fn from(value: u64) -> Self { Self::new(value) } } impl From<$ident> for u64 { #[must_use] fn from(value: $ident) -> Self { value.as_u64() } } impl From<$crate::name::Name> for $ident { #[must_use] fn from(value: $crate::name::Name) -> Self { Self(value) } } impl From<$ident> for $crate::name::Name { #[must_use] fn from(value: $ident) -> Self { value.as_name() } } impl core::str::FromStr for $ident { type Err = $crate::name::ParseNameError; #[inline] fn from_str(s: &str) -> Result<Self, Self::Err> { let name = $crate::name::Name::from_str(s)?; Ok(Self(name)) } } }; }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_GBFR { bits: bool, } impl EMAC_MMCTXIM_GBFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_GBFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_GBFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_SCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_SCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_SCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_SCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_MCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_MCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_MCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_MCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_OCTCNTR { bits: bool, } impl EMAC_MMCTXIM_OCTCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_OCTCNTW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_OCTCNTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&self) -> EMAC_MMCTXIM_GBFR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_MMCTXIM_GBFR { bits } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&self) -> EMAC_MMCTXIM_SCOLLGFR { let bits = ((self.bits >> 14) & 1) != 0; EMAC_MMCTXIM_SCOLLGFR { bits } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&self) -> EMAC_MMCTXIM_MCOLLGFR { let bits = ((self.bits >> 15) & 1) != 0; EMAC_MMCTXIM_MCOLLGFR { bits } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&self) -> EMAC_MMCTXIM_OCTCNTR { let bits = ((self.bits >> 20) & 1) != 0; EMAC_MMCTXIM_OCTCNTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&mut self) -> _EMAC_MMCTXIM_GBFW { _EMAC_MMCTXIM_GBFW { w: self } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&mut self) -> _EMAC_MMCTXIM_SCOLLGFW { _EMAC_MMCTXIM_SCOLLGFW { w: self } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&mut self) -> _EMAC_MMCTXIM_MCOLLGFW { _EMAC_MMCTXIM_MCOLLGFW { w: self } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&mut self) -> _EMAC_MMCTXIM_OCTCNTW { _EMAC_MMCTXIM_OCTCNTW { w: self } } }
//! use chart_builder::charts::*; /// Structure used for storing chart related data and the drawing of a Box and Whisker Plot. /// /// This chart is used for statistical analysis of data. /// Shows variations within a set of data. #[derive(Clone)] pub struct BoxWhiskerPlot { data_labels: Vec<String>, data: Vec<Vec<f64>>, pub chart_prop: ChartProp, pub axis_prop: AxisProp, } impl BoxWhiskerPlot { /// Creates a new instance of a BoxWhiskerPlot. /// /// ```chart_title``` is the String to specify the name of the chart displayed at the top of the window. /// /// ```new_data_labels``` contains strings placed under each box and whisker plot naming them. /// /// ```new_data``` is the number data for which statistics are generated to create a box plot. /// Each inner vector represents a new box and whisker plot named by the same index element in new_data_labels. pub fn new( chart_title: String, new_data_labels: Vec<String>, new_data: Vec<Vec<f64>>, ) -> BoxWhiskerPlot { let x_axis_bounds = (0.0, 0.0); let x_axis_scale = 1.0 / (new_data_labels.len() as f64); let y_axis_props = calc_axis_props(&new_data, true, false); // take bar let y_axis_bounds = y_axis_props.0; let y_axis_scale = y_axis_props.1; let axis_type: AxisType = if y_axis_bounds.0 < 0.0 && y_axis_bounds.1 > 0.0 { AxisType::DoubleVertical } else { AxisType::Single }; BoxWhiskerPlot { data_labels: new_data_labels, data: new_data, chart_prop: ChartProp::new(chart_title, &axis_type), axis_prop: AxisProp::new(x_axis_bounds, y_axis_bounds, x_axis_scale, y_axis_scale), } } pub fn draw_chart(&self, drawing_area: &DrawingArea) { let data_labels = self.data_labels.clone(); let data = self.data.clone(); let chart_title = self.chart_prop.chart_title.clone(); let x_axis_title = self.axis_prop.x_axis_title.clone(); let x_axis_scale = self.axis_prop.x_axis_scale; let y_axis_title = self.axis_prop.y_axis_title.clone(); let y_axis_scale = self.axis_prop.y_axis_scale; let y_axis_bounds: (f64, f64) = self.axis_prop.y_axis_bounds; let y_axis_min = y_axis_bounds.0; let y_axis_max = y_axis_bounds.1; let screen_size = self.chart_prop.screen_size; let mut h_scale = screen_size.1 / screen_size.0; let mut v_scale = screen_size.0 / screen_size.1; // Always make text and objects smaller rather than bigger as guarnteed to fit on screen if h_scale < v_scale { v_scale = 1.0; } else { h_scale = 1.0; } let scalings: (f64, f64, f64, f64, f64, f64); scalings = get_normal_scale(); let _horizontal_scaling = scalings.0; let _vertical_scaling = scalings.1; let _left_bound = scalings.2; let _right_bound = scalings.3; let _lower_bound = scalings.4; let _upper_bound = scalings.5; // calculate cote values for drawing box plot let mut lq: Vec<f64> = Vec::new(); let mut med: Vec<f64> = Vec::new(); let mut uq: Vec<f64> = Vec::new(); let mut iqr: Vec<f64> = Vec::new(); let mut outliers: Vec<Vec<f64>> = Vec::new(); let mut min: Vec<f64> = Vec::new(); let mut max: Vec<f64> = Vec::new(); for i in 0..data.len() { // Sort data for determing percentile let mut sorted_data = data[i].clone(); sorted_data.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); // Lower quartile is the (n + 1) ÷ 4 th value. lq.push(percentile(&sorted_data, 0.25)); // Median is the (n + 1) ÷ 2 th value. med.push(percentile(&sorted_data, 0.5)); // Upper quartile is the 3 (n + 1) ÷ 4 th value. uq.push(percentile(&sorted_data, 0.75)); // uq - lq iqr.push(uq[i] - lq[i]); // Outliers - remove from data set and place in outliers - allow limit with default being 1.5iqr from lq and uq // set limits for outliers let lower_limit = lq[i] - iqr[i] * 1.5; let upper_limit = uq[i] + iqr[i] * 1.5; // store all outlier values let mut temp = sorted_data.clone(); temp.retain(|&i| i < lower_limit || i > upper_limit); outliers.push(temp); // remove outliers vaules from main data sorted_data.retain(|&i| i > lower_limit && i < upper_limit); // get min and max from remaining data min.push( sorted_data .iter() .fold(-0. / 0., |cur_min, &x| cur_min.min(x)), ); max.push( sorted_data .iter() .fold(0. / 0., |cur_max, &x| cur_max.max(x)), ); } drawing_area.connect_draw(move |_, cr| { cr.set_dash(&[3., 2., 1.], 1.); assert_eq!(cr.get_dash(), (vec![3., 2., 1.], 1.)); set_defaults(cr, screen_size); // Drawing box whisker plot components // radius scaling (determining size) always goes with the smaller scaling so guarnteed to fit into screen. let radius_scaling; if screen_size.1 > screen_size.0 { radius_scaling = _horizontal_scaling.min(_vertical_scaling); } else { radius_scaling = _horizontal_scaling.max(_vertical_scaling); } let mark_radius = 0.008 * radius_scaling; use std::f64::consts::PI; let intercept = calc_x_intercept( calc_zero_intercept(y_axis_min, y_axis_max), _vertical_scaling, _lower_bound, _upper_bound, ); let x_delimiter_interval: f64 = _horizontal_scaling * x_axis_scale; let bar_width = 0.6 / (data.len() as f64); for i in 0..data.len() { let x = _left_bound - (x_delimiter_interval / 2.0) + x_delimiter_interval * ((i + 1) as f64); set_nth_colour(cr, i); // draw outliers first cr.set_line_width(0.0025); for j in 0..outliers[i].len() { let y_val = outliers[i][j]; let y = _lower_bound - (get_percentage_in_bounds(y_val, y_axis_min, y_axis_max) * _vertical_scaling); // draw mark (round) at (x,y) cr.save(); // Moving drawing origin to (x,y) cr.translate(x, y); // Scaling the current transformation matrix by different amounts in the X and Y directions. // This is done to assure a circlular object in a rectangular screen. cr.scale(h_scale, v_scale); cr.arc(0.0, 0.0, mark_radius, 0.0, 2.0 * PI); cr.stroke(); cr.restore(); } cr.set_line_width(0.002); // draw lq to uq block cr.rectangle( x - (bar_width / 2.0) * _horizontal_scaling, _lower_bound - (get_percentage_in_bounds(lq[i], y_axis_min, y_axis_max) * _vertical_scaling), bar_width * _horizontal_scaling, _lower_bound - (get_percentage_in_bounds(iqr[i], y_axis_min, y_axis_max) * _vertical_scaling) - intercept, ); // preserve used to keep shape to draw outline cr.fill_preserve(); cr.stroke_preserve(); cr.set_source_rgb(0.0, 0.0, 0.0); // median line cr.move_to( x - bar_width * _horizontal_scaling / 2.0, _lower_bound - (get_percentage_in_bounds(med[i], y_axis_min, y_axis_max) * _vertical_scaling), ); cr.line_to( x + bar_width * _horizontal_scaling / 2.0, _lower_bound - (get_percentage_in_bounds(med[i], y_axis_min, y_axis_max) * _vertical_scaling), ); // line from lq to min cr.move_to( x, _lower_bound - (get_percentage_in_bounds(lq[i], y_axis_min, y_axis_max) * _vertical_scaling), ); cr.line_to( x, _lower_bound - (get_percentage_in_bounds(min[i], y_axis_min, y_axis_max) * _vertical_scaling), ); // end of min line cr.move_to( x - bar_width * _horizontal_scaling * 0.2, _lower_bound - (get_percentage_in_bounds(min[i], y_axis_min, y_axis_max) * _vertical_scaling), ); cr.line_to( x + bar_width * _horizontal_scaling * 0.2, _lower_bound - (get_percentage_in_bounds(min[i], y_axis_min, y_axis_max) * _vertical_scaling), ); // line from uq to max cr.move_to( x, _lower_bound - (get_percentage_in_bounds(uq[i], y_axis_min, y_axis_max) * _vertical_scaling), ); cr.line_to( x, _lower_bound - (get_percentage_in_bounds(max[i], y_axis_min, y_axis_max) * _vertical_scaling), ); // end of max line cr.move_to( x - bar_width * _horizontal_scaling * 0.2, _lower_bound - (get_percentage_in_bounds(max[i], y_axis_min, y_axis_max) * _vertical_scaling), ); cr.line_to( x + bar_width * _horizontal_scaling * 0.2, _lower_bound - (get_percentage_in_bounds(max[i], y_axis_min, y_axis_max) * _vertical_scaling), ); cr.stroke(); } // Chart Title draw_title( cr, _left_bound, _upper_bound, h_scale, v_scale, &chart_title, ); // Draw Axis draw_x_axis_cat( cr, scalings, &data_labels, x_axis_scale, calc_zero_intercept(y_axis_min, y_axis_max), &x_axis_title, screen_size, false, ); draw_y_axis_con( cr, scalings, y_axis_min, y_axis_max, y_axis_scale, 0.0, &y_axis_title, screen_size, ); Inhibit(false) }); } pub(in chart_builder) fn get_chart_prop(&self) -> ChartProp { self.chart_prop.clone() } } impl Chart for BoxWhiskerPlot { fn draw(&self) { build_window(ChartType::BoxWhisk(self.clone())); } }
use std::error::Error; use std::fs; type MyResult<T> = Result<T, Box<Error>>; fn main() -> MyResult<()> { let input = fs::read_to_string("test.txt")?; let polymer : Vec<char> = input.chars().collect(); part1(polymer)?; Ok(()) } fn part1(input : Vec<char>) -> MyResult<()> { // let test : Vec<&[char]> = input.chunks(2) // .filter(|x| !x.is_empty()) // .collect(); let test : Vec<&[char]> = input.chunks(2) .filter(|x| x.is_empty()) .collect(); Ok(()) }
use core::fmt::{self, Display}; use core::ops::{Add, Div, Mul, Rem, Sub}; use core::time::Duration; use num_bigint::BigInt; // Must be at least a `u64` because `u32` is only ~49 days (`(1 << 32)`) /// A duration in milliseconds between `Monotonic` times. #[derive(Clone, Copy, Eq, Debug, PartialEq, PartialOrd)] pub struct Milliseconds(pub u64); impl Milliseconds { pub const fn const_div(self, rhs: u64) -> Self { Self(self.0 / rhs) } pub const fn as_u64(self) -> u64 { self.0 } } impl Add<Milliseconds> for Milliseconds { type Output = Milliseconds; fn add(self, rhs: Milliseconds) -> Self::Output { Self(self.0 + rhs.0) } } impl Div<u64> for Milliseconds { type Output = Milliseconds; fn div(self, rhs: u64) -> Self::Output { self.const_div(rhs) } } impl Mul<u64> for Milliseconds { type Output = Milliseconds; fn mul(self, rhs: u64) -> Self::Output { Self(self.0 * rhs) } } impl From<Milliseconds> for BigInt { fn from(milliseconds: Milliseconds) -> Self { milliseconds.0.into() } } impl From<Milliseconds> for u64 { fn from(milliseconds: Milliseconds) -> Self { milliseconds.0 } } impl From<Monotonic> for Milliseconds { fn from(monotonic: Monotonic) -> Self { Self(monotonic.0) } } /// The absolute time #[derive(Clone, Copy, Eq, Debug, Ord, PartialEq, PartialOrd)] #[repr(transparent)] pub struct Monotonic(pub u64); impl Monotonic { pub fn from_millis<T: Into<u64>>(to: T) -> Self { Self(to.into()) } pub fn checked_sub(&self, rhs: Self) -> Option<Milliseconds> { self.0.checked_sub(rhs.0).map(Milliseconds) } pub fn round_down(&self, divisor: u64) -> Self { Self((self.0 / divisor) * divisor) } } impl PartialEq<u64> for Monotonic { fn eq(&self, other: &u64) -> bool { self.0.eq(other) } } impl PartialOrd<u64> for Monotonic { fn partial_cmp(&self, other: &u64) -> Option<std::cmp::Ordering> { Some(self.0.cmp(other)) } } impl Add<Duration> for Monotonic { type Output = Monotonic; fn add(self, rhs: Duration) -> Self::Output { Self(self.0 + (rhs.as_millis() as u64)) } } impl Add<Milliseconds> for Monotonic { type Output = Monotonic; fn add(self, rhs: Milliseconds) -> Self::Output { Self(self.0 + rhs.0) } } impl Display for Monotonic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} ms", self.0) } } impl Rem<Milliseconds> for Monotonic { type Output = Milliseconds; fn rem(self, rhs: Milliseconds) -> Self::Output { Milliseconds(self.0 % rhs.0) } } impl Sub<Milliseconds> for Monotonic { type Output = Monotonic; fn sub(self, rhs: Milliseconds) -> Self::Output { Self(self.0 - rhs.0) } } impl Sub<Monotonic> for Monotonic { type Output = Milliseconds; fn sub(self, rhs: Monotonic) -> Self::Output { Milliseconds(self.0 - rhs.0) } }
// Original PistonDevelopers/camera_controllers license: // // The MIT License (MIT) // // Copyright (c) 2015 PistonDevelopers // // 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. //! A 3D first-person camera type. //! //! Adapted from PistonDevelopers/camera_controllers under the MIT license //! https://github.com/PistonDevelopers/camera_controllers/blob/8edf8a464b57107683c2585bbdc55d9e46994783/src/first_person.rs use vecmath::traits::{ Float, Radians }; use Camera; bitflags!(pub struct Actions: u8 { const MOVE_FORWARD = 0b00000001; const MOVE_BACKWARD = 0b00000010; const STRAFE_LEFT = 0b00000100; const STRAFE_RIGHT = 0b00001000; const FLY_UP = 0b00010000; const FLY_DOWN = 0b00100000; const MOVE_FASTER = 0b01000000; }); /// First person camera settings. pub struct FirstPersonSettings<T=f32> { /// The horizontal movement speed. /// /// This is measured in units per second. pub speed_horizontal: T, /// The vertical movement speed. /// /// This is measured in units per second. pub speed_vertical: T, /// The horizontal mouse sensitivity. /// /// This is a multiplier applied to horizontal mouse movements. pub mouse_sensitivity_horizontal: T, /// The vertical mouse sensitivity. /// /// This is a multiplier applied to vertical mouse movements. pub mouse_sensitivity_vertical: T, } impl<T> Default for FirstPersonSettings<T> where T: Float { /// Creates new first person camera settings with wasd defaults. fn default() -> FirstPersonSettings<T> { FirstPersonSettings { speed_horizontal: T::one(), speed_vertical: T::one(), mouse_sensitivity_horizontal: T::one(), mouse_sensitivity_vertical: T::one(), } } } /// Models a flying first person camera. pub struct FirstPerson<T=f32> { /// The first person camera settings. pub settings: FirstPersonSettings<T>, /// The yaw angle (in radians). pub yaw: T, /// The pitch angle (in radians). pub pitch: T, /// The position of the camera. pub position: [T; 3], /// The velocity we are moving. pub velocity: T, /// The active actions. pub actions: Actions, } impl<T> FirstPerson<T> where T: Float { /// Creates a new first person camera. pub fn new( position: [T; 3], settings: FirstPersonSettings<T> ) -> FirstPerson<T> { let _0: T = T::zero(); FirstPerson { settings: settings, yaw: _0, pitch: _0, position: position, velocity: T::one(), actions: Actions::empty(), } } /// Computes camera. pub fn camera(&self, dt: T) -> Camera<T> { let dh = dt * self.velocity * self.settings.speed_horizontal; let (dx, dy, dz) = self.movement_direction(); let (s, c) = (self.yaw.sin(), self.yaw.cos()); let mut camera = Camera::new([ self.position[0] + (s * dx - c * dz) * dh, self.position[1] + dy * dt * self.settings.speed_vertical, self.position[2] + (s * dz + c * dx) * dh ]); camera.set_yaw_pitch(self.yaw, self.pitch); camera } /// Updates the camera for an elapsed number of seconds. pub fn update(&mut self, dt: T) { let cam = self.camera(dt); self.position = cam.position; } /// Updates the camera for a mouse movement. pub fn update_mouse(&mut self, relative_dx: T, relative_dy: T) { let FirstPerson { ref mut yaw, ref mut pitch, ref settings, .. } = *self; let dx = relative_dx * settings.mouse_sensitivity_horizontal; let dy = relative_dy * settings.mouse_sensitivity_vertical; let pi: T = Radians::_180(); let _0 = T::zero(); let _1 = T::one(); let _2 = _1 + _1; let _3 = _2 + _1; let _4 = _3 + _1; let _360 = T::from_isize(360); *yaw = (*yaw - dx / _360 * pi / _4) % (_2 * pi); *pitch = *pitch + dy / _360 * pi / _4; *pitch = (*pitch).min(pi / _2).max(-pi / _2); } /// Gets the direction of movement. pub fn movement_direction(&self) -> (T, T, T) { let (mut dx, mut dy, mut dz) = (T::zero(), T::zero(), T::zero()); let set_axis = |axis: &mut T, positive, negative| { if self.actions.contains(positive) && self.actions.contains(negative) { *axis = T::zero(); } else if self.actions.contains(positive) { *axis = T::one(); } else if self.actions.contains(negative) { *axis = -T::one(); } }; set_axis(&mut dx, Actions::MOVE_BACKWARD, Actions::MOVE_FORWARD); set_axis(&mut dz, Actions::STRAFE_LEFT, Actions::STRAFE_RIGHT); set_axis(&mut dy, Actions::FLY_UP, Actions::FLY_DOWN); (dx,dy,dz) } pub fn enable_actions(&mut self, actions: Actions) { self.actions |= actions; } pub fn disable_action(&mut self, action: Actions) { self.actions &= !action; } }
use crate::game::{self, Action, Game}; use crate::{rng, Direction, PLAYER}; #[derive(Debug)] pub enum Ai { Basic, Idle, Confused { previous: Box<Ai>, num_turns: i32 }, } impl Ai { /// Calculate an Ai turn pub fn turn(self, id: usize, game: &Game) -> (game::Turn, Self) { match self { Ai::Basic => basic(id, &game), Ai::Idle => idle(id, &game), Ai::Confused { previous, num_turns, } => confused(id, &game, previous, num_turns), } } } /// When the monster is confused fn confused(id: usize, _game: &Game, previous: Box<Ai>, num_turns: i32) -> (game::Turn, Ai) { let mut turn = vec![]; let ai = if num_turns >= 1 { let num_turns = num_turns - 1; turn.push(Action::Move( id, Direction(rng::within(-1, 1), rng::within(-1, 1)), )); Ai::Confused { previous, num_turns, } } else { *previous }; (turn, ai) } /// When the monster sees the player fn basic(id: usize, game: &Game) -> (game::Turn, Ai) { let mut turn = vec![]; let object = &game.objects[id]; let player = &game.objects[PLAYER]; if game.visible(&object.loc) { if game::distance(&object.loc, &player.loc) >= 2.0 { if rng::d12() > 11 { turn.push(Action::Bark(id)); } turn.push(Action::Move(id, game::direction(&object.loc, &player.loc))); (turn, Ai::Basic) } else if player.fighter.map_or(false, |f| f.health > 0) { turn.push(Action::Attack(id, PLAYER)); (turn, Ai::Basic) } else { (turn, Ai::Basic) } } else { (turn, Ai::Idle) } } /// When the monster does not see the player fn idle(id: usize, game: &Game) -> (game::Turn, Ai) { let mut turn = vec![]; let object = &game.objects[id]; if game.visible(&object.loc) { (turn, Ai::Basic) } else if rng::dx(1000) > 999 { turn.push(Action::Mumble(id)); (turn, Ai::Idle) } else { (turn, Ai::Idle) } }
use tonic::{transport::Server, Request, Response, Status}; use tokio::sync::mpsc; use std::collections::HashMap; use std::sync::{Arc, RwLock}; pub mod pubsub { tonic::include_proto!("pubsub"); } use pubsub::message_service_server::{MessageService, MessageServiceServer}; use pubsub::{Message, SubscribeRequest}; type Subscribes = HashMap<String, mpsc::Sender<Result<Message, Status>>>; #[derive(Debug, Default)] struct SampleMessageService { subscribes: Arc<RwLock<Subscribes>>, } type RpcResult<T> = Result<Response<T>, Status>; #[tonic::async_trait] impl MessageService for SampleMessageService { type SubscribeStream = mpsc::Receiver<Result<Message, Status>>; async fn publish(&self, req: Request<Message>) -> RpcResult<()> { println!("*** publish: {:?}", req); let msg = req.into_inner(); let rs = self.subscribes.read().unwrap().clone(); for (k, v) in rs.iter() { let r = v.clone().send(Ok(msg.clone())).await; println!("{:?}", r); if r.is_err() { println!("remove client_id: {}", k); let mut ws = self.subscribes.write().unwrap(); ws.remove(k); } } Ok(Response::new(())) } async fn subscribe(&self, req: Request<SubscribeRequest>) -> RpcResult<Self::SubscribeStream> { println!("*** subscribe: {:?}", req); let (tx, rx) = mpsc::channel(4); let mut ws = self.subscribes.write().unwrap(); let sr = req.into_inner(); if ws.contains_key(&sr.client_id) { println!("*** exists client_id: {}", sr.client_id); let msg = format!("exists client_id={}", sr.client_id); return Err(Status::already_exists(msg)) } ws.insert(sr.client_id, tx); Ok(Response::new(rx)) } } #[tokio::main] async fn main() { println!("run server"); let addr = "127.0.0.1:50051".parse().unwrap(); let svc = SampleMessageService::default(); Server::builder() .add_service(MessageServiceServer::new(svc)) .serve(addr) .await .unwrap(); }
//! Initialization code #![feature(panic_implementation)] #![no_std] #[macro_use] extern crate cortex_m; #[macro_use] extern crate cortex_m_rt; extern crate f3; use core::panic::PanicInfo; pub use cortex_m::asm::bkpt; use cortex_m::asm; pub use cortex_m::peripheral::ITM; use cortex_m_rt::ExceptionFrame; pub use f3::hal::prelude; use f3::hal::prelude::*; pub use f3::hal::serial::Serial; pub use f3::hal::stm32f30x::usart1; use f3::hal::stm32f30x::{self, USART1}; pub use f3::hal::time::MonoTimer; pub fn init() -> (&'static mut usart1::RegisterBlock, MonoTimer, ITM) { let cp = cortex_m::Peripherals::take().unwrap(); let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpioa = dp.GPIOA.split(&mut rcc.ahb); let tx = gpioa.pa9.into_af7(&mut gpioa.moder, &mut gpioa.afrh); let rx = gpioa.pa10.into_af7(&mut gpioa.moder, &mut gpioa.afrh); Serial::usart1(dp.USART1, (tx, rx), 115_200.bps(), clocks, &mut rcc.apb2); unsafe { ( &mut *(USART1::ptr() as *mut _), MonoTimer::new(cp.DWT, clocks), cp.ITM, ) } } #[allow(deprecated)] #[panic_implementation] fn panic(info: &PanicInfo) -> ! { let itm = unsafe { &mut *ITM::ptr() }; iprintln!(&mut itm.stim[0], "{}", info); cortex_m::asm::bkpt(); loop {} } exception!(HardFault, hard_fault); fn hard_fault(_ef: &ExceptionFrame) -> ! { asm::bkpt(); loop {} } exception!(*, default_handler); fn default_handler(_irqn: i16) { loop {} }
use serde::Deserialize; use serde_yaml; use std::collections::HashMap; #[derive(Debug, Deserialize)] pub struct AppConfig { pub commands: HashMap<String, AppCommand>, pub hosts: HashMap<String, AppHost>, } #[derive(Debug, Deserialize)] pub struct AppCommand { pub command: String, } #[derive(Debug, Deserialize)] pub struct AppHost { pub ip: String, pub user: String, pub password: Option<String>, } pub fn load_config_file(config_file: &str) -> crate::AppResult<AppConfig> { let config_file = std::fs::File::open(config_file)?; let parsed_config: AppConfig = serde_yaml::from_reader(config_file)?; println!("Cfg: {:?}", &parsed_config); Ok(parsed_config) }
use crate::{ caveat::{CaveatBuilder, CaveatType}, error::MacaroonError, serialization::macaroon_builder::MacaroonBuilder, Macaroon, }; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use serde::{Deserialize, Serialize}; use std::str; #[derive(Debug, Default, Deserialize, Serialize)] struct CaveatV2J { i: Option<String>, i64: Option<String>, l: Option<String>, l64: Option<String>, v: Option<Vec<u8>>, v64: Option<Vec<u8>>, } #[derive(Debug, Default, Deserialize, Serialize)] struct V2JSerialization { v: u8, i: Option<String>, i64: Option<String>, l: Option<String>, l64: Option<String>, c: Vec<CaveatV2J>, s: Option<Vec<u8>>, s64: Option<String>, } impl V2JSerialization { fn from_macaroon(macaroon: Macaroon) -> Result<V2JSerialization, MacaroonError> { let mut serialized: V2JSerialization = V2JSerialization { v: 2, i: Some(macaroon.identifier().to_owned()), i64: None, l: macaroon.location(), l64: None, c: Vec::new(), s: None, s64: Some(macaroon.signature().to_base64(STANDARD)), }; for caveat in macaroon.caveats() { match caveat.get_type() { CaveatType::FirstParty => { let first_party = caveat.as_first_party().unwrap(); let serialized_caveat: CaveatV2J = CaveatV2J { i: Some(first_party.predicate()), i64: None, l: None, l64: None, v: None, v64: None, }; serialized.c.push(serialized_caveat); } CaveatType::ThirdParty => { let third_party = caveat.as_third_party().unwrap(); let serialized_caveat: CaveatV2J = CaveatV2J { i: Some(third_party.id()), i64: None, l: Some(third_party.location()), l64: None, v: Some(third_party.verifier_id()), v64: None, }; serialized.c.push(serialized_caveat); } } } Ok(serialized) } } impl Macaroon { fn from_v2j(ser: V2JSerialization) -> Result<Macaroon, MacaroonError> { if ser.i.is_some() && ser.i64.is_some() { return Err(MacaroonError::DeserializationError(String::from( "Found i and i64 fields", ))); } if ser.l.is_some() && ser.l64.is_some() { return Err(MacaroonError::DeserializationError(String::from( "Found l and l64 fields", ))); } if ser.s.is_some() && ser.s64.is_some() { return Err(MacaroonError::DeserializationError(String::from( "Found s and s64 fields", ))); } let mut builder: MacaroonBuilder = MacaroonBuilder::new(); builder.set_identifier(&match ser.i { Some(id) => id, None => match ser.i64 { Some(id) => String::from_utf8(id.from_base64()?)?, None => { return Err(MacaroonError::DeserializationError(String::from( "No identifier found", ))) } }, }); match ser.l { Some(loc) => builder.set_location(&loc), None => { if let Some(loc) = ser.l64 { builder.set_location(&String::from_utf8(loc.from_base64()?)?) } } }; builder.set_signature(&match ser.s { Some(sig) => sig, None => match ser.s64 { Some(sig) => sig.from_base64()?, None => { return Err(MacaroonError::DeserializationError(String::from( "No signature found", ))) } }, }); let mut caveat_builder: CaveatBuilder = CaveatBuilder::new(); for c in ser.c { caveat_builder.add_id(match c.i { Some(id) => id, None => match c.i64 { Some(id64) => String::from_utf8(id64.from_base64()?)?, None => { return Err(MacaroonError::DeserializationError(String::from( "No caveat ID found", ))) } }, }); match c.l { Some(loc) => caveat_builder.add_location(loc), None => { if let Some(loc64) = c.l64 { caveat_builder.add_location(String::from_utf8(loc64.from_base64()?)?) } } }; match c.v { Some(vid) => caveat_builder.add_verifier_id(vid), None => { if let Some(vid64) = c.v64 { caveat_builder.add_verifier_id(vid64.from_base64()?) } } }; builder.add_caveat(caveat_builder.build()?); caveat_builder = CaveatBuilder::new(); } Ok(builder.build()?) } } pub fn serialize_v2j(macaroon: &Macaroon) -> Result<Vec<u8>, MacaroonError> { let serialized: String = serde_json::to_string(&V2JSerialization::from_macaroon(macaroon.clone())?)?; Ok(serialized.into_bytes()) } pub fn deserialize_v2j(data: &[u8]) -> Result<Macaroon, MacaroonError> { let v2j: V2JSerialization = serde_json::from_slice(data)?; Macaroon::from_v2j(v2j) } #[cfg(test)] mod tests { use super::super::Format; use crate::Macaroon; const SERIALIZED_V2J: &str = "{\"v\":2,\"l\":\"http://example.org/\",\"i\":\"keyid\",\ \"c\":[{\"i\":\"account = 3735928559\"},{\"i\":\"user = \ alice\"}],\"s64\":\ \"S-lnzR6gxrJrr2pKlO6bBbFYhtoLqF6MQqk8jQ4SXvw\"}"; const SIGNATURE_V2: [u8; 32] = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ]; #[test] fn test_deserialize_v2j() { let serialized_v2j: Vec<u8> = SERIALIZED_V2J.as_bytes().to_vec(); let macaroon = super::deserialize_v2j(&serialized_v2j).unwrap(); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!("keyid", macaroon.identifier()); assert_eq!(2, macaroon.caveats().len()); assert_eq!( "account = 3735928559", macaroon.caveats()[0].as_first_party().unwrap().predicate() ); assert_eq!( "user = alice", macaroon.caveats()[1].as_first_party().unwrap().predicate() ); assert_eq!(SIGNATURE_V2.to_vec(), macaroon.signature()); } #[test] fn test_serialize_deserialize_v2j() { let mut macaroon = Macaroon::create("http://example.org/", &SIGNATURE_V2, "keyid").unwrap(); macaroon.add_first_party_caveat("user = alice"); macaroon.add_third_party_caveat("https://auth.mybank.com/", b"my key", "keyid"); let serialized = macaroon.serialize(Format::V2J).unwrap(); let other = Macaroon::deserialize(&serialized).unwrap(); assert_eq!(macaroon, other); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::DCCMP0 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct ADC_DCCMP0_COMP0R { bits: u16, } impl ADC_DCCMP0_COMP0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_DCCMP0_COMP0W<'a> { w: &'a mut W, } impl<'a> _ADC_DCCMP0_COMP0W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits &= !(4095 << 0); self.w.bits |= ((value as u32) & 4095) << 0; self.w } } #[doc = r"Value of the field"] pub struct ADC_DCCMP0_COMP1R { bits: u16, } impl ADC_DCCMP0_COMP1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_DCCMP0_COMP1W<'a> { w: &'a mut W, } impl<'a> _ADC_DCCMP0_COMP1W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits &= !(4095 << 16); self.w.bits |= ((value as u32) & 4095) << 16; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:11 - Compare 0"] #[inline(always)] pub fn adc_dccmp0_comp0(&self) -> ADC_DCCMP0_COMP0R { let bits = ((self.bits >> 0) & 4095) as u16; ADC_DCCMP0_COMP0R { bits } } #[doc = "Bits 16:27 - Compare 1"] #[inline(always)] pub fn adc_dccmp0_comp1(&self) -> ADC_DCCMP0_COMP1R { let bits = ((self.bits >> 16) & 4095) as u16; ADC_DCCMP0_COMP1R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:11 - Compare 0"] #[inline(always)] pub fn adc_dccmp0_comp0(&mut self) -> _ADC_DCCMP0_COMP0W { _ADC_DCCMP0_COMP0W { w: self } } #[doc = "Bits 16:27 - Compare 1"] #[inline(always)] pub fn adc_dccmp0_comp1(&mut self) -> _ADC_DCCMP0_COMP1W { _ADC_DCCMP0_COMP1W { w: self } } }
// Enables `quote!` to work on bigger chunks of code. #![recursion_limit = "256"] #![deny(bare_trait_objects, unused_lifetimes)] #![warn(clippy::all)] use utils::generated_file; pub mod ast; mod constraint; mod flat_filter; pub mod ir; pub mod lexer; generated_file!(pub parser); pub mod error; mod print; mod truth_table; use utils::*; use log::{debug, info}; use std::{fs, io, path, process}; /// Converts a choice name to a rust type name. fn to_type_name(name: &str) -> String { let mut result = "".to_string(); let mut is_new_word = true; let mut last_is_sep = true; for c in name.chars() { if c != '_' || last_is_sep { if is_new_word { result.extend(c.to_uppercase()); } else { result.push(c); } } last_is_sep = c == '_'; is_new_word = last_is_sep || c.is_numeric(); } result } /// Process a file and stores the result in an other file. This is meant to be used from build.rs /// files and may print output to be interpreted by cargo on stdout. pub fn process_file( input_path: &path::Path, output_path: &path::Path, format: bool, ) -> Result<(), error::Error> { let mut output = fs::File::create(path::Path::new(output_path)).unwrap(); info!( "compiling {} to {}", input_path.display(), output_path.display() ); process(None, &mut output, input_path)?; if format { match process::Command::new("rustfmt") .arg(output_path.as_os_str()) .status() { Ok(status) => { if !status.success() { println!("cargo:warning=failed to rustfmt {}", output_path.display()); } } Err(_) => { println!("cargo:warning=failed to execute rustfmt"); } } } Ok(()) } /// Parses a constraint description file. pub fn process<T: io::Write>( input: Option<&mut dyn io::Read>, output: &mut T, input_path: &path::Path, ) -> Result<(), error::Error> { // Parse and check the input. let tokens = if let Some(stream) = input { lexer::Lexer::from_input(stream) } else { lexer::Lexer::from_file(input_path) }; let ast: ast::Ast = parser::parse_ast(tokens) .map_err(|c| error::Error::from((input_path.to_path_buf(), c)))?; let (mut ir_desc, constraints) = ast.type_check().unwrap(); debug!("constraints: {:?}", constraints); // Generate flat filters. let mut filters = FxMultiHashMap::default(); for mut constraint in constraints { constraint.dedup_inputs(&ir_desc); for (choice, filter) in constraint.gen_filters(&ir_desc) { filters.insert(choice, filter); } } debug!("filters: {:?}", filters); // Merge and generate structured filters. for (choice, filters) in filters { for filter in flat_filter::merge(filters, &ir_desc) { debug!("compiling filter for choice {}: {:?}", choice, filter); let (vars, inputs, rules, set_constraints) = filter.deconstruct(); let rules = truth_table::opt_rules(&inputs, rules, &ir_desc); let arguments = ir_desc .get_choice(&choice) .arguments() .sets() .enumerate() .map(|(id, set)| (ir::Variable::Arg(id), set)) .map(|(v, set)| set_constraints.find_set(v).unwrap_or(set)) .chain(&vars) .cloned() .collect(); let new_filter = ir::Filter { arguments, rules, inputs, }; debug!("adding filter to {}: {:?}", choice, new_filter); ir_desc.add_filter(choice.clone(), new_filter, vars, set_constraints); } } write!(output, "{}", print::print(&ir_desc)).unwrap(); Ok(()) } #[cfg(test)] mod tests { use super::print; use std::path::Path; /// Ensure that the output of telamon-gen is stable across calls. #[test] fn stable_output() { let path = Path::new("../src/search_space/choices.exh"); let ref_out = { let mut ref_out = Vec::new(); super::process(None, &mut ref_out, &path).unwrap(); ref_out }; // Ideally we would want to run this loop more than once, but // generation is currently too slow to be worth it. for _ in 0..1 { print::reset(); let mut out_buf = Vec::new(); super::process(None, &mut out_buf, &path).unwrap(); assert_eq!( ::std::str::from_utf8(&out_buf), ::std::str::from_utf8(&ref_out) ); } } } // TODO(cleanup): avoid name conflicts in the printer // TODO(feature): allow multiple supersets // TODO(filter): group filters if one iterates on a subtype of the other // TODO(filter): generate negative filter when there is at most one input. // TODO(filter): merge filters even if one input requires a type constraint // TODO(cc_perf): Only iterate on the lower triangular part of symmetric rather than // dynamically filtering out half of the cases // TODO(cc_perf): in truth table, intersect rules with rules with weaker conditions, // FIXME: fix counters: // * Discard full counters. Might re-enable them later if we can find a way to make // lowerings commute // * Fordid resrtricting the FALSE value of the repr flag from conditions that involve // other decisions // > this makes lowering commute. Otherwise we can force the counter to be >0, which can // be true or not depending if another lowering has already occured. // FIXME: make sure the quotient set works correctly with things that force the repr flag // to TRUE (for example the constraint on reduction). One problem might be that the flag // is forced to FALSE but can be merged with a dim whose flag can be set to TRUE. The // solutions for this may be to ensure: // - conditions on flags are uniform for merged dims // - the flag has a third state "ok to be true, but onyl if merged to another"
use models; use schema; use diesel::prelude::*; use diesel::MysqlConnection; use super::file_entry_types; /// Queries a single organization with the given slug. pub fn find_by_user( user_id: i32, titan_primary: &MysqlConnection ) -> Result<Vec<models::UserFileEntryWithType>, diesel::result::Error> { let file_entries_res = schema::user_file_entries::table .inner_join(schema::user_file_entry_types::table) .select(( schema::user_file_entries::all_columns, schema::user_file_entry_types::all_columns )) .filter(schema::user_file_entries::user_id.eq(user_id)) .order_by(schema::user_file_entries::start_date.desc()) .get_results::<(models::UserFileEntry, models::UserFileEntryType)>(titan_primary)?; let mut file_entries: Vec<models::UserFileEntryWithType> = vec![]; for entry in file_entries_res { file_entries.push(models::UserFileEntryWithType { id: entry.0.id, file_entry_type: entry.1, user_id: entry.0.user_id, start_date: entry.0.start_date, end_date: entry.0.end_date, comments: entry.0.comments, date_modified: entry.0.date_modified, modified_by: entry.0.modified_by }); } Ok(file_entries) } /// Queries the last inserted file entry. pub fn find_most_recent( titan_db: &MysqlConnection ) -> Result<models::UserFileEntry, diesel::result::Error> { schema::user_file_entries::table .order_by(schema::user_file_entries::id.desc()) .first(titan_db) } /// Creates a new file entry. pub fn create_file_entry( new_file_entry: &models::NewUserFileEntry, titan_db: &MysqlConnection ) -> Result<models::UserFileEntryWithType, diesel::result::Error> { diesel::insert_into(schema::user_file_entries::table) .values(new_file_entry) .execute(titan_db)?; let last_inserted = find_most_recent(titan_db)?; let entry_type = file_entry_types::find_by_id( last_inserted.user_file_entry_type_id, titan_db )?; Ok(models::UserFileEntryWithType { id: last_inserted.id, file_entry_type: entry_type, user_id: last_inserted.user_id, start_date: last_inserted.start_date, end_date: last_inserted.end_date, comments: last_inserted.comments, date_modified: last_inserted.date_modified, modified_by: last_inserted.modified_by }) }
fn main() { let array1 = [1, 2, 3]; let array2 = [1, 2, 3]; let array3 = [2, 3, 4]; if array1.eq(&array2) { println!("array1 dan array2 sama!"); } if array1.ne(&array3) { println!("array1 dan array3 tidak sama!"); } }
use std::mem; // handle of binary-search-tree #[derive(Debug)] pub struct BST { pub root: Link, size: usize, } // branch to node #[derive(Debug, PartialEq)] pub enum Link { Empty, More(Box<Node>), } // populated node #[derive(Debug, PartialEq)] pub struct Node { elem: i32, left: Link, right: Link, } impl Link { /// Create a new Link with a populated Node containing /// the given elem and empty branches. fn new(n: i32) -> Link { Link::More( Box::new( Node{elem: n, left: Link::Empty, right: Link::Empty, } ) ) } } /// Traverse tree to appropriate node and insert if /// node is not already popualated. fn tree_insert(link: &mut Link, item: i32) -> bool { match link { &mut Link::Empty => { let newlink = Link::new(item); mem::replace(link, newlink); true } &mut Link::More(ref mut node) => { if item == node.elem { false } else if item < node.elem { tree_insert(&mut node.left, item) } else { tree_insert(&mut node.right, item) } } } } /// Traverse tree until item or an empty link is found fn tree_search(link: &Link, item: i32) -> bool { match link { &Link::Empty => false, &Link::More(ref node) => { if item == node.elem { true } else if item < node.elem { tree_search(&node.left, item) } else { tree_search(&node.right, item) } } } } /// Collect tree nodes in ascending order into a vec fn tree_collect(mut vec: &mut Vec<i32>, link: &Link) { match link { &Link::More(ref node) => { if node.left != Link::Empty { tree_collect(&mut vec, &node.left); } vec.push(node.elem); if node.right != Link::Empty { tree_collect(&mut vec, &node.right); } } _ => (), }; } impl BST { pub fn new() -> BST { BST{root: Link::Empty, size: 0} } pub fn insert(&mut self, item: i32) -> bool { self.size += 1; if self.root == Link::Empty { mem::replace(&mut self.root, Link::new(item)); true } else { tree_insert(&mut self.root, item) } } pub fn search(&self, item: i32) -> bool { if self.root == Link::Empty { false } else { tree_search(&self.root, item) } } pub fn as_vec(&self) -> Vec<i32> { let mut vec = Vec::with_capacity(self.size); tree_collect(&mut vec, &self.root); vec } }
use image::{DynamicImage, Rgba}; use imageproc::definitions::HasBlack; use imageproc::drawing::{draw_text_mut, Canvas}; use rusttype::{Font, Point, Scale}; use std::fs; fn open_font(font: &str) -> std::vec::Vec<u8> { let font_vec1 = fs::read(font).expect("Unable to read file"); return font_vec1; } #[derive(Debug)] pub struct Text<'a> { pub text: &'a str, pub font_size: f32, pub color: Rgba<u8>, pub font: &'a Font<'static>, } fn get_actual_box_size(text_box: &Text) -> (u32, u32) { let scale = Scale::uniform(text_box.font_size as f32); let start_point = Point { x: 0f32, y: 0f32 }; // 根据字库字型,计算每个文字的坐标、大小等 let mut glyphs_iter = text_box.font.layout(text_box.text, scale, start_point); // 取第一和最后一个字符 // TODO: 考虑过少字符的情况 let first_char = glyphs_iter.nth(0).unwrap().pixel_bounding_box().unwrap(); let last_char = glyphs_iter.last().unwrap().pixel_bounding_box().unwrap(); // 取整段文字的左上角和右下角点返回 ( (last_char.max.x - first_char.min.x) as u32, (last_char.max.y - first_char.min.y) as u32, ) } fn draw_text(canvas: &mut DynamicImage, x: u32, y: u32, text: &Text<'_>) { let scale = Scale::uniform(text.font_size as f32); draw_text_mut(canvas, text.color, x, y, scale, text.font, text.text); } fn add_multi_text_ex(bg: &mut DynamicImage, texts: Vec<Text<'_>>) { let (image_w, image_h) = Canvas::dimensions(bg); // 画布大小 (宽,高)为图像大小的 3/4 let (canvas_w, canvas_h) = ( (image_w as f32 * 0.8f32) as u32, // 文字所占最大宽度为图像宽度的 80% (image_h as f32 * 0.75f32) as u32, // 文字所占最大高度为图像高度的 75% ); // 计算所有文本大小 let mut all_text_height = 0; let mut texts = texts .into_iter() .map(|each_line| { let (width, height) = get_actual_box_size(&each_line); all_text_height += height; (width, height, each_line) }) .collect::<Vec<(u32, u32, Text<'_>)>>(); // 重新计算所有文本高度和字号 let mut all_text_height_2 = 0; for (width, height, text) in &mut texts { // 按照高度比例重新计算文本框大小 let mut new_height = ((*height as f32 / all_text_height as f32) * canvas_h as f32) as u32; let mut new_width = ((new_height as f32 / *height as f32) * *width as f32) as u32; // 如果满足高度的同时,宽度超过最大宽度,则以宽度为准:缩小到原来的 canvas_w / new_width if new_width > canvas_w { new_height = (new_height as f32 * (canvas_w as f32 / new_width as f32)) as u32; new_width = canvas_w; } // 计算最终缩放比例,并缩放字体大小 text.font_size *= new_height as f32 / *height as f32; all_text_height_2 += new_height; *width = new_width; *height = new_height; } println!("{:?}", texts); // 让所有文字垂直居中,计算左上角 y 轴坐标 let mut start_y = (image_h - all_text_height_2 - 30 * texts.len() as u32) / 2; // 开始画画 for (width, height, text) in texts { let x = (image_w - width) / 2; println!("x = {}, y = {}", x, start_y); draw_text(bg, x, start_y, &text); start_y += height + 30; } } fn add_multi_text(bg: &mut DynamicImage, texts: &[&str], font: Font<'static>) { add_multi_text_ex( bg, texts .into_iter() .map(|x| Text { text: x, font_size: 72f32, color: Rgba::black(), font: &font, }) .collect(), ); } fn main() { let file = "backgrounds/common-1.png"; let mut img = image::open(file).unwrap(); // Read font let font_data = open_font("fonts/华文中宋.ttf"); let font: Font<'static> = Font::try_from_vec(font_data).unwrap(); let text = "机器人爱好者协会"; let text2 = "这是一张测试用的图片!!"; add_multi_text(&mut img, &[text, text2], font); let img2 = img.resize(800, 600, image::imageops::FilterType::Triangle); img2.save("Hello.png"); }
use anyhow::{Context as _, Error}; use std::path::PathBuf; use std::sync::Arc; use swc::common::FileName; use swc::config::{Options, SourceMapsConfig}; use swc::{Compiler, TransformOutput}; use swc_ecmascript::ast::Program; use swc_wallaby::transform::{ exec_transform, my_transform, TransformOptions, TransformOutputWithRanges, }; use testing::{StdErr, Tester}; extern crate swc_wallaby; #[test] fn ranges() { println!("Hello"); let runner = || { compile_str( FileName::Real(PathBuf::from("not-unique.js")), "var a = b ? c() : d();\nvar a = b ? c() : d();", TransformOptions { swc: swc::config::Options { // filename: "unique.js".into(), // source_maps: Some(SourceMapsConfig::Bool(true)), ..Default::default() }, // TODO(vjpr): Next.js stuff. Remove. disable_next_ssg: false, pages_dir: None, }, ) }; let ranges1 = runner().unwrap().ranges; let ranges2 = runner().unwrap().ranges; println!("{:?}", ranges1); println!("{:?}", ranges2); // TODO(vjpr): Should be identical! //assert!(map.contains("entry-foo")); } fn compile_str( filename: FileName, content: &str, options: TransformOptions, ) -> Result<TransformOutputWithRanges, StdErr> { Tester::new().print_errors(|cm, handler| { let c = Arc::new(Compiler::new(cm.clone())); let is_module = false; let s = my_transform(c, content, is_module, options, |c, content, options| { Ok(c.cm.new_source_file( if options.swc.filename.is_empty() { FileName::Anon } else { FileName::Real(options.swc.filename.clone().into()) }, content.to_string(), )) }); match s { Ok(v) => { if handler.has_errors() { Err(()) } else { Ok(v) } } Err(err) => panic!("Error: {:?}", err), } }) }
#[repr(C)] #[derive(Debug, Copy, Clone, Default)] pub struct VkViewport { pub x: f32, pub y: f32, pub width: f32, pub height: f32, pub minDepth: f32, pub maxDepth: f32, }
//! Runtime helpers for keeping track of Kubernetes resources mod informer; mod reflector; pub use informer::Informer; pub use reflector::Reflector;
#[derive(Debug)] struct User { name: String, addr: String } impl User { fn get_name(&self) ->&str { &(self.name[..]) } fn get_addr(&self) ->&str { &(self.addr[..]) } } fn main() { let user = User{ name: String::from("wuhaurou"), addr: String::from("中国") }; println!("user -> {:?}", user); println!("user.name -> {}", user.get_name()); println!("user.name -> {}", user.get_addr()); }
use std::{cell::RefCell, rc::Rc}; use futures::StreamExt as _; use medea_reactive::ObservableVec; use tokio::task::spawn_local; use crate::{component, sys::RtcPeerConnection}; pub struct Room { pub peers: RefCell<ObservableVec<Rc<component::Peer>>>, } impl Room { pub fn new() -> Self { Self { peers: RefCell::new(ObservableVec::new()), } } pub fn spawn_tasks(&self) { self.spawn_on_peer_created(); } pub fn spawn_on_peer_created(&self) { let mut on_peer_created = self.peers.borrow().on_push(); spawn_local(async move { while let Some(peer) = on_peer_created.next().await { let rtc_peer = RtcPeerConnection::new(); Rc::clone(&peer).spawn_tasks(rtc_peer); } }); } }
use crate::renderer::Renderer; use fs_extra::dir; use log::info; use model::Site; use std::{ fs, path::{Path, PathBuf}, process::Command, }; use structopt::StructOpt; mod markdown; mod model; mod renderer; #[derive(Debug, StructOpt)] #[structopt( name = "static-wiki", about = "Generate static html files and search index for a wiki." )] struct Opt { /// Input folder #[structopt(parse(from_os_str), short)] input: PathBuf, /// Output folder #[structopt(parse(from_os_str), short)] output: PathBuf, /// Template folder #[structopt(parse(from_os_str), short)] template: PathBuf, /// Static folder #[structopt(parse(from_os_str), short, long = "static")] static_path: PathBuf, } fn main() { env_logger::init(); let opt: Opt = Opt::from_args(); let template_path = opt .template .to_str() .unwrap() .trim_end_matches('/') .to_string() + "/*"; info!("Loading templates from {} ...", template_path); let renderer = Renderer::load_from_path(&template_path); info!("Loading data from {:?} ...", opt.input); let site = Site::load_from_path(opt.input); info!("Render to {:?} ...", opt.output); renderer.render_to(site, &opt.output); info!( "Copy static from {:?} to {:?} ...", opt.static_path, opt.output ); copy_static(opt.static_path, opt.output); } fn copy_static(static_path: impl AsRef<Path>, output_base_path: impl AsRef<Path>) { let options = dir::CopyOptions { overwrite: true, copy_inside: true, ..Default::default() }; dir::copy( &static_path, &output_base_path.as_ref().join("static"), &options, ) .unwrap(); fs::copy( &output_base_path .as_ref() .join("static") .join("manifest.json"), &output_base_path.as_ref().join("manifest.json"), ) .unwrap(); fs::remove_file( &output_base_path .as_ref() .join("static") .join("manifest.json"), ) .unwrap(); let pattern = output_base_path .as_ref() .join("static") .to_str() .unwrap() .trim_end_matches('/') .to_string() + "/*.ts"; let subprocesses = glob::glob(&pattern) .expect("Failed to read glob pattern") .map(|entry| match entry { Ok(path) => { let command = Command::new("tsc") .arg("--target") .arg("es5") .arg(&path.file_name().unwrap().to_str().unwrap()) .current_dir(output_base_path.as_ref().join("static")) .spawn() .expect("failed to execute process"); (command, path) } Err(e) => { panic!("{:?}", e) } }) .collect::<Vec<_>>(); for (mut subprocess, path) in subprocesses { subprocess.wait().unwrap(); fs::remove_file(path).unwrap(); } }
// Translation of vector operations to LLVM IR, in destination-passing style. import back::abi; import lib::llvm::llvm; import llvm::ValueRef; import middle::trans; import middle::trans_common; import middle::trans_dps; import middle::ty; import syntax::ast; import syntax::codemap::span; import trans::alloca; import trans::load_inbounds; import trans::new_sub_block_ctxt; import trans::type_of_or_i8; import trans_common::block_ctxt; import trans_common::struct_elt; import trans_common::C_int; import trans_common::C_null; import trans_common::C_uint; import trans_common::T_int; import trans_common::T_ivec_heap; import trans_common::T_ivec_heap_part; import trans_common::T_opaque_ivec; import trans_common::T_ptr; import trans_common::bcx_ccx; import trans_common::bcx_tcx; import trans_dps::dest; import trans_dps::llsize_of; import trans_dps::mk_temp; import std::option::none; import std::option::some; import tc = middle::trans_common; // Returns the length of an interior vector and a pointer to its first // element, in that order. // // TODO: We can optimize this in the cases in which we statically know the // vector must be on the stack. fn get_len_and_data(cx: &@block_ctxt, t: ty::t, llvecptr: ValueRef) -> {bcx: @block_ctxt, len: ValueRef, data: ValueRef} { let bcx = cx; // If this interior vector has dynamic size, we can't assume anything // about the LLVM type of the value passed in, so we cast it to an // opaque vector type. let unit_ty = ty::sequence_element_type(bcx_tcx(bcx), t); let v; if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) { v = bcx.build.PointerCast(llvecptr, T_ptr(T_opaque_ivec())); } else { v = llvecptr; } let llunitty = type_of_or_i8(bcx, unit_ty); let stack_len = load_inbounds(bcx, v, ~[C_int(0), C_uint(abi::ivec_elt_len)]); let stack_elem = bcx.build.InBoundsGEP(v, ~[C_int(0), C_uint(abi::ivec_elt_elems), C_int(0)]); let on_heap = bcx.build.ICmp(lib::llvm::LLVMIntEQ, stack_len, C_int(0)); let on_heap_cx = new_sub_block_ctxt(bcx, "on_heap"); let next_cx = new_sub_block_ctxt(bcx, "next"); bcx.build.CondBr(on_heap, on_heap_cx.llbb, next_cx.llbb); let heap_stub = on_heap_cx.build.PointerCast(v, T_ptr(T_ivec_heap(llunitty))); let heap_ptr = load_inbounds(on_heap_cx, heap_stub, ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)]); // Check whether the heap pointer is null. If it is, the vector length // is truly zero. let llstubty = T_ivec_heap(llunitty); let llheapptrty = struct_elt(llstubty, abi::ivec_heap_stub_elt_ptr); let heap_ptr_is_null = on_heap_cx.build.ICmp(lib::llvm::LLVMIntEQ, heap_ptr, C_null(T_ptr(llheapptrty))); let zero_len_cx = new_sub_block_ctxt(bcx, "zero_len"); let nonzero_len_cx = new_sub_block_ctxt(bcx, "nonzero_len"); on_heap_cx.build.CondBr(heap_ptr_is_null, zero_len_cx.llbb, nonzero_len_cx.llbb); // Technically this context is unnecessary, but it makes this function // clearer. let zero_len = C_int(0); let zero_elem = C_null(T_ptr(llunitty)); zero_len_cx.build.Br(next_cx.llbb); // If we're here, then we actually have a heapified vector. let heap_len = load_inbounds(nonzero_len_cx, heap_ptr, ~[C_int(0), C_uint(abi::ivec_heap_elt_len)]); let heap_elem = { let v = ~[C_int(0), C_uint(abi::ivec_heap_elt_elems), C_int(0)]; nonzero_len_cx.build.InBoundsGEP(heap_ptr, v) }; nonzero_len_cx.build.Br(next_cx.llbb); // Now we can figure out the length of |v| and get a pointer to its // first element. let len = next_cx.build.Phi(T_int(), ~[stack_len, zero_len, heap_len], ~[bcx.llbb, zero_len_cx.llbb, nonzero_len_cx.llbb]); let elem = next_cx.build.Phi(T_ptr(llunitty), ~[stack_elem, zero_elem, heap_elem], ~[bcx.llbb, zero_len_cx.llbb, nonzero_len_cx.llbb]); ret {bcx: next_cx, len: len, data: elem}; } fn trans_concat(cx: &@block_ctxt, in_dest: &dest, sp: &span, t: ty::t, lhs: &@ast::expr, rhs: &@ast::expr) -> @block_ctxt { let bcx = cx; // TODO: Detect "a = a + b" and promote to trans_append. // TODO: Detect "a + [ literal ]" and optimize to copying the literal // elements in directly. let t = ty::expr_ty(bcx_tcx(bcx), lhs); let skip_null = ty::type_is_str(bcx_tcx(bcx), t); // Translate the LHS and RHS. Pull out their length and data. let lhs_tmp = trans_dps::dest_alias(bcx_tcx(bcx), t); bcx = trans_dps::trans_expr(bcx, lhs_tmp, lhs); let lllhsptr = trans_dps::dest_ptr(lhs_tmp); let rhs_tmp = trans_dps::dest_alias(bcx_tcx(bcx), t); bcx = trans_dps::trans_expr(bcx, rhs_tmp, rhs); let llrhsptr = trans_dps::dest_ptr(rhs_tmp); let r0 = get_len_and_data(bcx, t, lllhsptr); bcx = r0.bcx; let lllhslen = r0.len; let lllhsdata = r0.data; r0 = get_len_and_data(bcx, t, llrhsptr); bcx = r0.bcx; let llrhslen = r0.len; let llrhsdata = r0.data; if skip_null { lllhslen = bcx.build.Sub(lllhslen, C_int(1)); } // Allocate the destination. let r1 = trans_dps::spill_alias(bcx, in_dest, t); bcx = r1.bcx; let dest = r1.dest; let unit_t = ty::sequence_element_type(bcx_tcx(bcx), t); let unit_sz = trans_dps::size_of(bcx_ccx(bcx), sp, unit_t); let stack_elems_sz = unit_sz * abi::ivec_default_length; let lldestptr = trans_dps::dest_ptr(dest); let llunitty = trans::type_of(bcx_ccx(bcx), sp, unit_t); // Decide whether to allocate the result on the stack or on the heap. let llnewlen = bcx.build.Add(lllhslen, llrhslen); let llonstack = bcx.build.ICmp(lib::llvm::LLVMIntULE, llnewlen, C_uint(stack_elems_sz)); let on_stack_bcx = new_sub_block_ctxt(bcx, "on_stack"); let on_heap_bcx = new_sub_block_ctxt(bcx, "on_heap"); bcx.build.CondBr(llonstack, on_stack_bcx.llbb, on_heap_bcx.llbb); // On-stack case. let next_bcx = new_sub_block_ctxt(bcx, "next"); trans::store_inbounds(on_stack_bcx, llnewlen, lldestptr, ~[C_int(0), C_uint(abi::ivec_elt_len)]); trans::store_inbounds(on_stack_bcx, C_uint(stack_elems_sz), lldestptr, ~[C_int(0), C_uint(abi::ivec_elt_alen)]); let llonstackdataptr = on_stack_bcx.build.InBoundsGEP(lldestptr, ~[C_int(0), C_uint(abi::ivec_elt_elems), C_int(0)]); on_stack_bcx.build.Br(next_bcx.llbb); // On-heap case. let llheappartty = tc::T_ivec_heap(llunitty); let lldeststubptr = on_heap_bcx.build.PointerCast(lldestptr, tc::T_ptr(llheappartty)); trans::store_inbounds(on_heap_bcx, C_int(0), lldeststubptr, ~[C_int(0), C_uint(abi::ivec_elt_len)]); trans::store_inbounds(on_heap_bcx, llnewlen, lldeststubptr, ~[C_int(0), C_uint(abi::ivec_elt_alen)]); let llheappartptrptr = on_heap_bcx.build.InBoundsGEP(lldeststubptr, ~[C_int(0), C_uint(abi::ivec_elt_elems)]); let llsizeofint = C_uint(llsize_of(bcx_ccx(bcx), tc::T_int())); on_heap_bcx = trans_dps::malloc(on_heap_bcx, llheappartptrptr, trans_dps::hp_shared, some(on_heap_bcx.build.Add(llnewlen, llsizeofint))); let llheappartptr = on_heap_bcx.build.Load(llheappartptrptr); trans::store_inbounds(on_heap_bcx, llnewlen, llheappartptr, ~[C_int(0), C_uint(abi::ivec_heap_elt_len)]); let llheapdataptr = on_heap_bcx.build.InBoundsGEP(llheappartptr, ~[C_int(0), C_uint(abi::ivec_heap_elt_elems), C_int(0)]); on_heap_bcx.build.Br(next_bcx.llbb); // Perform the memmove. let lldataptr = next_bcx.build.Phi(T_ptr(llunitty), ~[llonstackdataptr, llheapdataptr], ~[on_stack_bcx.llbb, on_heap_bcx.llbb]); trans_dps::memmove(next_bcx, lldataptr, lllhsdata, lllhslen); trans_dps::memmove(next_bcx, next_bcx.build.InBoundsGEP(lldataptr, ~[lllhslen]), llrhsdata, llrhslen); ret next_bcx; }
use std::mem; use liblumen_alloc::erts::exception::InternalResult; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::Process; use crate::distribution::external_term_format::try_split_at; use crate::distribution::nodes::node; use super::{arc_node, u16, u32, u64}; pub fn decode<'a>( process: &Process, safe: bool, bytes: &'a [u8], ) -> InternalResult<(Term, &'a [u8])> { let (u32_len_u16, after_len_bytes) = u16::decode(bytes)?; let len_usize = (u32_len_u16 as usize) * mem::size_of::<u32>(); let (arc_node, after_node_bytes) = arc_node::decode(safe, after_len_bytes)?; // TODO use creation to differentiate respawned nodes let (_creation, after_creation_bytes) = u32::decode(after_node_bytes)?; try_split_at(after_creation_bytes, len_usize).and_then(|(id_bytes, after_id_bytes)| { if arc_node == node::arc_node() { let (scheduler_id_u32, after_scheduler_id_bytes) = u32::decode(id_bytes)?; let (number_u64, _) = u64::decode(after_scheduler_id_bytes)?; let reference = process.reference_from_scheduler(scheduler_id_u32.into(), number_u64); Ok((reference, after_id_bytes)) } else { unimplemented!() } }) }
wit_bindgen::generate!("cart"); struct Component; export_cart!(Component); impl Cart for Component { fn create(id: CartId) -> CartData { CartData::EmptyCart(EmptyCart { id: id.clone() }) } fn add_item(state: CartData, item: ItemId, qty: Quantity) -> Option<CartData> { if qty == 0 { return None } find_price(&item) .and_then(|p| add_cart_item(state, CartItem { item: item.clone(), qty, unit_price: p }) ) } } fn add_cart_item(state: CartData, citem: CartItem) -> Option<CartData> { match state { CartData::EmptyCart(EmptyCart { id }) => { Some(CartData::ActiveCart(ActiveCart { id: id.clone(), items: vec![citem] })) } CartData::ActiveCart(ActiveCart { id, items }) => { let new_items = insert_or_update(&items, citem); Some(CartData::ActiveCart(ActiveCart { id: id.clone(), items: new_items })) } } } fn insert_or_update(src: &Vec<CartItem>, citem: CartItem) -> Vec<CartItem> { let mut res = vec![]; let mut upd = false; for v in src { if v.item == citem.item { res.push(CartItem { qty: v.qty + citem.qty, ..v.clone() }); upd = true; } else { res.push(v.clone()); } } if !upd { res.push(citem); } res }
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate bcrypt; extern crate rusqlite; extern crate rocket_contrib; extern crate rocket; extern crate serde_json; #[macro_use] extern crate serde_derive; use rocket::http; use rocket::Response; use rocket::response::{Redirect, NamedFile, Failure}; use rocket::request::{Form, Request}; use rocket_contrib::Template; use std::path::{PathBuf, Path}; mod contexts; mod forms; mod db; #[get("/")] fn root() -> Redirect { Redirect::to("/home") } #[get("/home")] fn home(cookies: &http::Cookies) -> Redirect { match cookies.find("user") { Some(cookie) => Redirect::to( format!("/home/{}", cookie.value()).as_str()), None => Redirect::to("/login"), } } #[get("/home/<user>", rank = 2)] fn home_user(user: String) -> Result<Template, Failure> { let db = match db::get() { Ok(connection) => connection, Err(_) => return Err(Failure(http::Status::InternalServerError)), }; match db.query_row( "SELECT * FROM users WHERE name=?1", &[&user], |row| {row.get::<&str, String>("name")}, ) { Ok(_) => { /* continue */ }, Err(_) => return Err(Failure(http::Status::NotFound)), }; let context = contexts::User { user: user, movies: vec![ "Bee Movie".to_string(), "Home Alone".to_string() ], }; Ok(Template::render("index", &context)) } #[get("/login")] fn login_page() -> Template { let context = contexts::Empty {}; Template::render("login", &context) } #[post("/login", data = "<user>")] fn login(cookies: &http::Cookies, user: Form<forms::Login>) -> Result<Redirect, Failure> { // get user data from inside the Form object let login_data = user.into_inner(); let name = login_data.name.clone(); let mut pass = login_data.pass.clone(); drop(login_data); // hash the password pass = match bcrypt::hash(pass.as_str(), bcrypt::DEFAULT_COST) { Ok(hash) => hash, Err(_) => return Err(Failure(http::Status::InternalServerError)), }; // get a db connection let db = match db::get() { Ok(connection) => connection, Err(_) => return Err(Failure(http::Status::InternalServerError)), }; // look up password in db and compare to transmitted password let success = match db.query_row::<String, _>( "SELECT password FROM users WHERE name=?1", &[&name], |row| {row.get(0)}) { Ok(p) => match bcrypt::verify(p.as_str(), pass.as_str()) { Ok(valid) => valid, Err(_) => return Err(Failure(http::Status::InternalServerError)), }, // return forbidden if the password is wrong Err(_) => return Err(Failure(http::Status::Forbidden)), }; if !success { panic!("impossible!"); } // add cookie for username cookies.add(http::Cookie::new("user", name)); // add cookie for session token cookies.add(http::Cookie::new("session", "goodsessiontoken")); Ok(Redirect::to("/")) } //#[post("/register")] //fn register(form: Form<forms::Register>) -> Redirect { //// TODO //Redirect::to("/") //} #[get("/static/<file..>")] fn static_content(file: PathBuf) -> Option<NamedFile> { NamedFile::open(Path::new("static/").join(file)).ok() } #[error(404)] fn not_found(req: &Request) -> Template { let context = contexts::NotFound { uri: req.uri().to_string(), }; Template::render("404", &context) } fn main() { let routes = routes![ root, home, home_user, login_page, login, static_content ]; let errors = errors![ not_found, ]; rocket::ignite() .mount("/", routes) .catch(errors) .launch(); }
use std::collections::HashMap; use std::io; fn valid_day2a_password(password: &str, param: char, min_count: usize, max_count: usize) -> bool { let mut counts = HashMap::new(); for c in password.chars() { let counter = counts.entry(c).or_insert(0); *counter += 1; } let char_count = match counts.get(&param) { Some(n) => *n, None => 0, }; char_count >= min_count && char_count <= max_count } fn valid_day2b_password(password: &str, param: char, pos_a: usize, pos_b: usize) -> bool { (password.chars().nth(pos_a - 1).unwrap() == param) ^ (password.chars().nth(pos_b - 1).unwrap() == param) } pub fn day2(part_a: bool) { // read values from stdin let val_fn = if part_a { valid_day2a_password } else { valid_day2b_password }; let mut num_valid = 0; loop { let mut line = String::new(); match io::stdin().read_line(&mut line) { Ok(0) => break, Ok(_) => { let parts: Vec<&str> = line.trim().split_whitespace().collect(); let counts: Vec<&str> = parts[0].split('-').collect(); let min_count = match counts[0].parse::<usize>() { Ok(n) => n, Err(_) => { panic!("got non-number {}", counts[0]); } }; let max_count = match counts[1].parse::<usize>() { Ok(n) => n, Err(_) => { panic!("got non-number {}", counts[0]); } }; let letter = parts[1].chars().next().unwrap(); let password = parts[2]; if val_fn(password, letter, min_count, max_count) { num_valid += 1; } } Err(error) => { panic!("error: {}", error); } } } println!("Number of valid passwords: {}", num_valid); }
use std::borrow::Cow; use std::env; use crate::spec::{FramePointer, LldFlavor, SplitDebugInfo, TargetOptions}; pub fn opts(os: &'static str) -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6 // either the linker will complain if it is used or the binary will end up // segfaulting at runtime when run on 10.6. Rust by default supports macOS // 10.7+, but there is a standard environment variable, // MACOSX_DEPLOYMENT_TARGET, which is used to signal targeting older // versions of macOS. For example compiling on 10.10 with // MACOSX_DEPLOYMENT_TARGET set to 10.6 will cause the linker to generate // warnings about the usage of ELF TLS. // // Here we detect what version is being requested, defaulting to 10.7. ELF // TLS is flagged as enabled if it looks to be supported. The architecture // only matters for default deployment target which is 11.0 for ARM64 and // 10.7 for everything else. let has_thread_local = macos_deployment_target("x86_64") >= (10, 7); TargetOptions { os: os.into(), vendor: "apple".into(), // macOS has -dead_strip, which doesn't rely on function_sections function_sections: false, dynamic_linking: true, linker_is_gnu: false, families: vec!["unix".into()], is_like_osx: true, default_dwarf_version: 2, frame_pointer: FramePointer::Always, has_rpath: true, dll_suffix: ".dylib".into(), archive_format: "darwin".into(), has_thread_local, abi_return_struct_as_int: true, emit_debug_gdb_scripts: false, eh_frame_header: false, lld_flavor: LldFlavor::Ld64, // The historical default for macOS targets is to run `dsymutil` which // generates a packed version of debuginfo split from the main file. split_debuginfo: SplitDebugInfo::Packed, // This environment variable is pretty magical but is intended for // producing deterministic builds. This was first discovered to be used // by the `ar` tool as a way to control whether or not mtime entries in // the archive headers were set to zero or not. It appears that // eventually the linker got updated to do the same thing and now reads // this environment variable too in recent versions. // // For some more info see the commentary on #47086 link_env: vec![("ZERO_AR_DATE".into(), "1".into())], ..Default::default() } } fn deployment_target(var_name: &str) -> Option<(u32, u32)> { let deployment_target = env::var(var_name).ok(); deployment_target .as_ref() .and_then(|s| s.split_once('.')) .and_then(|(a, b)| { a.parse::<u32>() .and_then(|a| b.parse::<u32>().map(|b| (a, b))) .ok() }) } fn macos_default_deployment_target(arch: &str) -> (u32, u32) { if arch == "arm64" { (11, 0) } else { (10, 7) } } fn macos_deployment_target(arch: &str) -> (u32, u32) { deployment_target("MACOSX_DEPLOYMENT_TARGET") .unwrap_or_else(|| macos_default_deployment_target(arch)) } pub fn macos_llvm_target(arch: &str) -> Cow<'static, str> { let (major, minor) = macos_deployment_target(arch); format!("{}-apple-macosx{}.{}.0", arch, major, minor).into() } pub fn macos_link_env_remove() -> Vec<Cow<'static, str>> { let mut env_remove = Vec::with_capacity(2); // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which // may occur when we're linking a custom build script while targeting iOS for example. if let Ok(sdkroot) = env::var("SDKROOT") { if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("iPhoneSimulator.platform") { env_remove.push("SDKROOT".into()) } } // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld", // although this is apparently ignored when using the linker at "/usr/bin/ld". env_remove.push("IPHONEOS_DEPLOYMENT_TARGET".into()); env_remove } fn ios_deployment_target() -> (u32, u32) { deployment_target("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or((7, 0)) } pub fn ios_llvm_target(arch: &str) -> String { // Modern iOS tooling extracts information about deployment target // from LC_BUILD_VERSION. This load command will only be emitted when // we build with a version specific `llvm_target`, with the version // set high enough. Luckily one LC_BUILD_VERSION is enough, for Xcode // to pick it up (since std and core are still built with the fallback // of version 7.0 and hence emit the old LC_IPHONE_MIN_VERSION). let (major, minor) = ios_deployment_target(); format!("{}-apple-ios{}.{}.0", arch, major, minor) } pub fn ios_sim_llvm_target(arch: &str) -> String { let (major, minor) = ios_deployment_target(); format!("{}-apple-ios{}.{}.0-simulator", arch, major, minor) }
use std::time::Duration; use hyper::{ client::{Client, HttpConnector}, Body, }; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; pub type HttpClient = Client<HttpsConnector<HttpConnector>, Body>; /// Create a HTTP 1 client instance. /// /// Parameter: Timeout for idle sockets being kept-alive pub fn make_client(pool_idle_timeout_seconds: u64) -> HttpClient { let https = HttpsConnectorBuilder::new() .with_native_roots() .https_or_http() .enable_http1() .build(); Client::builder() .pool_idle_timeout(Duration::from_secs(pool_idle_timeout_seconds)) .build(https) }
#[doc = "Reader of register SR2"] pub type R = crate::R<u32, super::SR2>; #[doc = "Writer for register SR2"] pub type W = crate::W<u32, super::SR2>; #[doc = "Register SR2 `reset()`'s with value 0"] impl crate::ResetValue for super::SR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TIM8F`"] pub type TIM8F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM8F`"] pub struct TIM8F_W<'a> { w: &'a mut W, } impl<'a> TIM8F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `USART1F`"] pub type USART1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USART1F`"] pub struct USART1F_W<'a> { w: &'a mut W, } impl<'a> USART1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `TIM15F`"] pub type TIM15F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM15F`"] pub struct TIM15F_W<'a> { w: &'a mut W, } impl<'a> TIM15F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `TIM16F`"] pub type TIM16F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM16F`"] pub struct TIM16F_W<'a> { w: &'a mut W, } impl<'a> TIM16F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `TIM17F`"] pub type TIM17F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM17F`"] pub struct TIM17F_W<'a> { w: &'a mut W, } impl<'a> TIM17F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `SAI1F`"] pub type SAI1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SAI1F`"] pub struct SAI1F_W<'a> { w: &'a mut W, } impl<'a> SAI1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `SAI2F`"] pub type SAI2F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SAI2F`"] pub struct SAI2F_W<'a> { w: &'a mut W, } impl<'a> SAI2F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `DFSDM1F`"] pub type DFSDM1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DFSDM1F`"] pub struct DFSDM1F_W<'a> { w: &'a mut W, } impl<'a> DFSDM1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `CRCF`"] pub type CRCF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CRCF`"] pub struct CRCF_W<'a> { w: &'a mut W, } impl<'a> CRCF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `TSCF`"] pub type TSCF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TSCF`"] pub struct TSCF_W<'a> { w: &'a mut W, } impl<'a> TSCF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `ICACHEF`"] pub type ICACHEF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ICACHEF`"] pub struct ICACHEF_W<'a> { w: &'a mut W, } impl<'a> ICACHEF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `ADCF`"] pub type ADCF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ADCF`"] pub struct ADCF_W<'a> { w: &'a mut W, } impl<'a> ADCF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `AESF`"] pub type AESF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AESF`"] pub struct AESF_W<'a> { w: &'a mut W, } impl<'a> AESF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `HASHF`"] pub type HASHF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HASHF`"] pub struct HASHF_W<'a> { w: &'a mut W, } impl<'a> HASHF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `RNGF`"] pub type RNGF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RNGF`"] pub struct RNGF_W<'a> { w: &'a mut W, } impl<'a> RNGF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `PKAF`"] pub type PKAF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PKAF`"] pub struct PKAF_W<'a> { w: &'a mut W, } impl<'a> PKAF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `SDMMC1F`"] pub type SDMMC1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SDMMC1F`"] pub struct SDMMC1F_W<'a> { w: &'a mut W, } impl<'a> SDMMC1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `FMC_REGF`"] pub type FMC_REGF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FMC_REGF`"] pub struct FMC_REGF_W<'a> { w: &'a mut W, } impl<'a> FMC_REGF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `OCTOSPI1_REGF`"] pub type OCTOSPI1_REGF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OCTOSPI1_REGF`"] pub struct OCTOSPI1_REGF_W<'a> { w: &'a mut W, } impl<'a> OCTOSPI1_REGF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `RTCF`"] pub type RTCF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RTCF`"] pub struct RTCF_W<'a> { w: &'a mut W, } impl<'a> RTCF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `PWRF`"] pub type PWRF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PWRF`"] pub struct PWRF_W<'a> { w: &'a mut W, } impl<'a> PWRF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `SYSCFGF`"] pub type SYSCFGF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYSCFGF`"] pub struct SYSCFGF_W<'a> { w: &'a mut W, } impl<'a> SYSCFGF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `DMA1F`"] pub type DMA1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA1F`"] pub struct DMA1F_W<'a> { w: &'a mut W, } impl<'a> DMA1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `DMA2F`"] pub type DMA2F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA2F`"] pub struct DMA2F_W<'a> { w: &'a mut W, } impl<'a> DMA2F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `DMAMUX1F`"] pub type DMAMUX1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMAMUX1F`"] pub struct DMAMUX1F_W<'a> { w: &'a mut W, } impl<'a> DMAMUX1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `RCCF`"] pub type RCCF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RCCF`"] pub struct RCCF_W<'a> { w: &'a mut W, } impl<'a> RCCF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `FLASHF`"] pub type FLASHF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLASHF`"] pub struct FLASHF_W<'a> { w: &'a mut W, } impl<'a> FLASHF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `FLASH_REGF`"] pub type FLASH_REGF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLASH_REGF`"] pub struct FLASH_REGF_W<'a> { w: &'a mut W, } impl<'a> FLASH_REGF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `EXTIF`"] pub type EXTIF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EXTIF`"] pub struct EXTIF_W<'a> { w: &'a mut W, } impl<'a> EXTIF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `OTFDEC1F`"] pub type OTFDEC1F_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OTFDEC1F`"] pub struct OTFDEC1F_W<'a> { w: &'a mut W, } impl<'a> OTFDEC1F_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } impl R { #[doc = "Bit 0 - TIM8F"] #[inline(always)] pub fn tim8f(&self) -> TIM8F_R { TIM8F_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - USART1F"] #[inline(always)] pub fn usart1f(&self) -> USART1F_R { USART1F_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - TIM15F"] #[inline(always)] pub fn tim15f(&self) -> TIM15F_R { TIM15F_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - TIM16F"] #[inline(always)] pub fn tim16f(&self) -> TIM16F_R { TIM16F_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - TIM17F"] #[inline(always)] pub fn tim17f(&self) -> TIM17F_R { TIM17F_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - SAI1F"] #[inline(always)] pub fn sai1f(&self) -> SAI1F_R { SAI1F_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - SAI2F"] #[inline(always)] pub fn sai2f(&self) -> SAI2F_R { SAI2F_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - DFSDM1F"] #[inline(always)] pub fn dfsdm1f(&self) -> DFSDM1F_R { DFSDM1F_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - CRCF"] #[inline(always)] pub fn crcf(&self) -> CRCF_R { CRCF_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - TSCF"] #[inline(always)] pub fn tscf(&self) -> TSCF_R { TSCF_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - ICACHEF"] #[inline(always)] pub fn icachef(&self) -> ICACHEF_R { ICACHEF_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - ADCF"] #[inline(always)] pub fn adcf(&self) -> ADCF_R { ADCF_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - AESF"] #[inline(always)] pub fn aesf(&self) -> AESF_R { AESF_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - HASHF"] #[inline(always)] pub fn hashf(&self) -> HASHF_R { HASHF_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - RNGF"] #[inline(always)] pub fn rngf(&self) -> RNGF_R { RNGF_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - PKAF"] #[inline(always)] pub fn pkaf(&self) -> PKAF_R { PKAF_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - SDMMC1F"] #[inline(always)] pub fn sdmmc1f(&self) -> SDMMC1F_R { SDMMC1F_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - FMC_REGF"] #[inline(always)] pub fn fmc_regf(&self) -> FMC_REGF_R { FMC_REGF_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - OCTOSPI1_REGF"] #[inline(always)] pub fn octospi1_regf(&self) -> OCTOSPI1_REGF_R { OCTOSPI1_REGF_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - RTCF"] #[inline(always)] pub fn rtcf(&self) -> RTCF_R { RTCF_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - PWRF"] #[inline(always)] pub fn pwrf(&self) -> PWRF_R { PWRF_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - SYSCFGF"] #[inline(always)] pub fn syscfgf(&self) -> SYSCFGF_R { SYSCFGF_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - DMA1F"] #[inline(always)] pub fn dma1f(&self) -> DMA1F_R { DMA1F_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - DMA2F"] #[inline(always)] pub fn dma2f(&self) -> DMA2F_R { DMA2F_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - DMAMUX1F"] #[inline(always)] pub fn dmamux1f(&self) -> DMAMUX1F_R { DMAMUX1F_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - RCCF"] #[inline(always)] pub fn rccf(&self) -> RCCF_R { RCCF_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - FLASHF"] #[inline(always)] pub fn flashf(&self) -> FLASHF_R { FLASHF_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - FLASH_REGF"] #[inline(always)] pub fn flash_regf(&self) -> FLASH_REGF_R { FLASH_REGF_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - EXTIF"] #[inline(always)] pub fn extif(&self) -> EXTIF_R { EXTIF_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - OTFDEC1F"] #[inline(always)] pub fn otfdec1f(&self) -> OTFDEC1F_R { OTFDEC1F_R::new(((self.bits >> 29) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TIM8F"] #[inline(always)] pub fn tim8f(&mut self) -> TIM8F_W { TIM8F_W { w: self } } #[doc = "Bit 1 - USART1F"] #[inline(always)] pub fn usart1f(&mut self) -> USART1F_W { USART1F_W { w: self } } #[doc = "Bit 2 - TIM15F"] #[inline(always)] pub fn tim15f(&mut self) -> TIM15F_W { TIM15F_W { w: self } } #[doc = "Bit 3 - TIM16F"] #[inline(always)] pub fn tim16f(&mut self) -> TIM16F_W { TIM16F_W { w: self } } #[doc = "Bit 4 - TIM17F"] #[inline(always)] pub fn tim17f(&mut self) -> TIM17F_W { TIM17F_W { w: self } } #[doc = "Bit 5 - SAI1F"] #[inline(always)] pub fn sai1f(&mut self) -> SAI1F_W { SAI1F_W { w: self } } #[doc = "Bit 6 - SAI2F"] #[inline(always)] pub fn sai2f(&mut self) -> SAI2F_W { SAI2F_W { w: self } } #[doc = "Bit 7 - DFSDM1F"] #[inline(always)] pub fn dfsdm1f(&mut self) -> DFSDM1F_W { DFSDM1F_W { w: self } } #[doc = "Bit 8 - CRCF"] #[inline(always)] pub fn crcf(&mut self) -> CRCF_W { CRCF_W { w: self } } #[doc = "Bit 9 - TSCF"] #[inline(always)] pub fn tscf(&mut self) -> TSCF_W { TSCF_W { w: self } } #[doc = "Bit 10 - ICACHEF"] #[inline(always)] pub fn icachef(&mut self) -> ICACHEF_W { ICACHEF_W { w: self } } #[doc = "Bit 11 - ADCF"] #[inline(always)] pub fn adcf(&mut self) -> ADCF_W { ADCF_W { w: self } } #[doc = "Bit 12 - AESF"] #[inline(always)] pub fn aesf(&mut self) -> AESF_W { AESF_W { w: self } } #[doc = "Bit 13 - HASHF"] #[inline(always)] pub fn hashf(&mut self) -> HASHF_W { HASHF_W { w: self } } #[doc = "Bit 14 - RNGF"] #[inline(always)] pub fn rngf(&mut self) -> RNGF_W { RNGF_W { w: self } } #[doc = "Bit 15 - PKAF"] #[inline(always)] pub fn pkaf(&mut self) -> PKAF_W { PKAF_W { w: self } } #[doc = "Bit 16 - SDMMC1F"] #[inline(always)] pub fn sdmmc1f(&mut self) -> SDMMC1F_W { SDMMC1F_W { w: self } } #[doc = "Bit 17 - FMC_REGF"] #[inline(always)] pub fn fmc_regf(&mut self) -> FMC_REGF_W { FMC_REGF_W { w: self } } #[doc = "Bit 18 - OCTOSPI1_REGF"] #[inline(always)] pub fn octospi1_regf(&mut self) -> OCTOSPI1_REGF_W { OCTOSPI1_REGF_W { w: self } } #[doc = "Bit 19 - RTCF"] #[inline(always)] pub fn rtcf(&mut self) -> RTCF_W { RTCF_W { w: self } } #[doc = "Bit 20 - PWRF"] #[inline(always)] pub fn pwrf(&mut self) -> PWRF_W { PWRF_W { w: self } } #[doc = "Bit 21 - SYSCFGF"] #[inline(always)] pub fn syscfgf(&mut self) -> SYSCFGF_W { SYSCFGF_W { w: self } } #[doc = "Bit 22 - DMA1F"] #[inline(always)] pub fn dma1f(&mut self) -> DMA1F_W { DMA1F_W { w: self } } #[doc = "Bit 23 - DMA2F"] #[inline(always)] pub fn dma2f(&mut self) -> DMA2F_W { DMA2F_W { w: self } } #[doc = "Bit 24 - DMAMUX1F"] #[inline(always)] pub fn dmamux1f(&mut self) -> DMAMUX1F_W { DMAMUX1F_W { w: self } } #[doc = "Bit 25 - RCCF"] #[inline(always)] pub fn rccf(&mut self) -> RCCF_W { RCCF_W { w: self } } #[doc = "Bit 26 - FLASHF"] #[inline(always)] pub fn flashf(&mut self) -> FLASHF_W { FLASHF_W { w: self } } #[doc = "Bit 27 - FLASH_REGF"] #[inline(always)] pub fn flash_regf(&mut self) -> FLASH_REGF_W { FLASH_REGF_W { w: self } } #[doc = "Bit 28 - EXTIF"] #[inline(always)] pub fn extif(&mut self) -> EXTIF_W { EXTIF_W { w: self } } #[doc = "Bit 29 - OTFDEC1F"] #[inline(always)] pub fn otfdec1f(&mut self) -> OTFDEC1F_W { OTFDEC1F_W { w: self } } }
rs_prog login: [ input : [name(X), password(Y)], output: [loginSuccessful, loginUnsuccessful], module get_login: [ input : [name(X), password(Y), goodLogin, badLogin, tooManyAttempts], output : [loginSuccessful, loginUnsuccessful, checkLogin(X,Y)], t_signal:[], p_signal: [gotName(X), gotPassword(Y)], var : [], initially: [nl, write('Enter name and password'), activate(rules)], on_exception:[], name(X) ===> [up(gotName(X))], password(X) ===> [up(gotPassword(X))], #[gotName(X), gotPassword(Y)] ===> [emit(checkLogin(X,Y))], goodLogin ===> [emit(loginSuccessful)], badLogin ===> [nl, write('Please, repeat name and password')], tooManyAttempts ===> [emit(loginUnsuccessful)] ], module check_login: [ input : [checkLogin(X,Y)], output : [goodLogin, badLogin, tooManyAttempts], t_signal:[], p_signal: [], var : [count], initially: [count := 0, activate(rules)], on_exception:[], ~ checkLogin(X,Y) ===> case [ user(X,Y) ---> [count:=0, emit(goodLogin)], count>=2 ---> [emit(tooManyAttempts)], else ---> [count:=count+1, emit(badLogin)] ] ] ]. user(sst, aaa). user(lvt, bbb).
//! Static configuration (the bootstrap node(s)). /// The supported bootstrap nodes (/dnsaddr is not yet supported). This will be updated to contain /// the latest known supported IPFS bootstrap peers. // FIXME: it would be nice to parse these into MultiaddrWithPeerId with const fn. pub const BOOTSTRAP_NODES: &[&str] = &["/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]; #[cfg(test)] mod tests { use crate::p2p::MultiaddrWithPeerId; #[test] fn bootstrap_nodes_are_multiaddr_with_peerid() { super::BOOTSTRAP_NODES .iter() .try_for_each(|s| s.parse::<MultiaddrWithPeerId>().map(|_| ())) .unwrap(); } }
use lock_api::{MutexGuard, RawMutex}; use std::{fmt, marker::PhantomData, ops::Deref}; /// A mutex guard that has an exclusive lock, but only an immutable reference; useful if you /// need to map a mutex guard with a function that returns an `&T`. Construct using the /// [`MapImmutable`] trait. pub struct ImmutableMappedMutexGuard<'a, R: RawMutex, T: ?Sized> { raw: &'a R, data: *const T, _marker: PhantomData<(&'a T, R::GuardMarker)>, } // main constructor for ImmutableMappedMutexGuard // TODO: patch lock_api to have a MappedMutexGuard::raw method, and have this implementation be for // MappedMutexGuard impl<'a, R: RawMutex, T: ?Sized> MapImmutable<'a, R, T> for MutexGuard<'a, R, T> { fn map_immutable<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U> where F: FnOnce(&T) -> &U, { let raw = unsafe { MutexGuard::mutex(&s).raw() }; let data = f(&s) as *const U; std::mem::forget(s); ImmutableMappedMutexGuard { raw, data, _marker: PhantomData, } } } impl<'a, R: RawMutex, T: ?Sized> ImmutableMappedMutexGuard<'a, R, T> { pub fn map<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U> where F: FnOnce(&T) -> &U, { let raw = s.raw; let data = f(&s) as *const U; std::mem::forget(s); ImmutableMappedMutexGuard { raw, data, _marker: PhantomData, } } } impl<'a, R: RawMutex, T: ?Sized> Deref for ImmutableMappedMutexGuard<'a, R, T> { type Target = T; fn deref(&self) -> &Self::Target { // SAFETY: self.data is valid for the lifetime of the guard unsafe { &*self.data } } } impl<'a, R: RawMutex, T: ?Sized> Drop for ImmutableMappedMutexGuard<'a, R, T> { fn drop(&mut self) { // SAFETY: An ImmutableMappedMutexGuard always holds the lock unsafe { self.raw.unlock() } } } impl<'a, R: RawMutex, T: fmt::Debug + ?Sized> fmt::Debug for ImmutableMappedMutexGuard<'a, R, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl<'a, R: RawMutex, T: fmt::Display + ?Sized> fmt::Display for ImmutableMappedMutexGuard<'a, R, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } pub trait MapImmutable<'a, R: RawMutex, T: ?Sized> { fn map_immutable<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U> where F: FnOnce(&T) -> &U; }
#![allow(non_camel_case_types)] pub type u1 = u8; pub type u2 = u16; pub type u4 = u32;
//! # parse_chg //! //! Парсинг файла формата *.chg (Мономах) //! //! Парсим файл, затем собираем его обратно. Модули _raw для анализа фрагментов исходного файла //! //! <hr/> #![recursion_limit = "128"] extern crate nom; #[macro_use] extern crate arrayref; extern crate byteorder; extern crate core; extern crate walkdir; mod read_write; mod sig; mod slits_for_lira; mod tests; use crate::read_write::{read_file, read_file_raw, write_by_file_raw, write_recognize_sig}; use std::path::Path; fn main() { let input = Path::new(r"test_cases/Угольный_2этап_27.chg"); let building_s = read_file_raw(input); let building = read_file(input); write_by_file_raw(&building_s); write_recognize_sig(); println!("{}", &building); //slits_for_lira::write_slits_for_lira(); }
use ::yaml_rust::Yaml; use ::std::collections::BTreeMap; use ::std::collections::btree_map::Entry; use ::parse::*; use ::errors::*; pub fn pathjoin<'a>(paths: &[&YamlPath]) -> YamlPath { let mut ret = vec![]; for elem in paths.iter().flat_map(|x| x.iter()) { match elem { YamlPathElem::Up => { ret.pop(); }, // It's okay if we pop an empty Vec // TODO Is this the best way to ignore the return value? YamlPathElem::Root => ret.clear(), _ => ret.push(elem.clone()), // TODO Is this clone necessary? }; } ret } pub fn get<'a>(root: &'a Yaml, path: &YamlPath) -> &'a Yaml { let mut cur = root; let mut stack = vec![]; for elem in path.iter() { cur = match elem { YamlPathElem::Down(ref key) => { stack.push(cur); match cur { Yaml::Hash(ref map) => map.get(&Yaml::String(key.to_string())).unwrap_or(&Yaml::BadValue), Yaml::Array(ref arr) => key.parse::<usize>().ok().and_then(|i| arr.get(i)).unwrap_or(&Yaml::BadValue), _ => &Yaml::BadValue, } }, YamlPathElem::Up => stack.pop().unwrap_or(root), YamlPathElem::Root => root, }; } cur } pub fn bool(yaml: &Yaml) -> bool { match yaml { Yaml::BadValue | Yaml::Null | Yaml::Boolean(false) => false, Yaml::Array(ref a) => ! a.is_empty(), Yaml::Hash(ref h) => ! h.is_empty(), _ => true, } } pub fn string(yaml: &Yaml, ignore: bool) -> Result<String> { match yaml { Yaml::Real(x) => Ok(x.to_string()), Yaml::Integer(x) => Ok(x.to_string()), Yaml::String(x) => Ok(x.to_string()), Yaml::Boolean(x) => Ok(x.to_string()), Yaml::Null => Ok("".to_string()), _ => if ignore { Ok("".to_string()) } else { Err(Error::from("Can't stringify type")) }, // TODO This error message (and a lot of others) needs to be better } } pub fn merge(yamls: Vec<Yaml>) -> Yaml { fn recursive_merge(acc: &mut Yaml, cur: &Yaml) { // TODO Is there a way to do this without all the clones? We should take ownership of cur so we can butcher it for its pieces. match (acc, cur) { (Yaml::Array(orig), Yaml::Array(new)) => orig.extend(new.iter().cloned()), (Yaml::Hash(orig), Yaml::Hash(new)) => for (k, v) in new.iter() { match orig.entry(k.clone()) { Entry::Vacant(entry) => { entry.insert(v.clone()); }, Entry::Occupied(mut entry) => { recursive_merge(entry.get_mut(), v); }, } } (orig, new) => *orig = new.clone(), } } yamls.into_iter().fold(Yaml::Hash(BTreeMap::new()), |mut ret, cur| { // Flatten all YAMLs into one sequence, and then fold successive ones into earlier ones recursive_merge(&mut ret, &cur); // Each fold appends lists, recursively merges objects, and overwrites everything else with the new values ret }) } #[cfg(test)] mod tests { use super::*; use ::std::collections::BTreeMap; use ::yaml_rust::YamlLoader; #[test] fn pathjoin_basic() { use YamlPathElem::*; assert_eq!(pathjoin(&vec![]), vec![]); assert_eq!(pathjoin(&vec![ &vec![Down("a".to_string()), Down(1.to_string())], &vec![Down(0.to_string())], ]), vec![Down("a".to_string()), Down(1.to_string()), Down(0.to_string())]); assert_eq!(pathjoin(&vec![ &vec![Down("a".to_string()), Down(1.to_string())], &vec![Root, Down("b".to_string()), Down("c".to_string())], &vec![Up, Down(10.to_string())], ]), vec![Down("b".to_string()), Down(10.to_string())]); assert_eq!(pathjoin(&vec![ &vec![Root, Up, Up], &vec![Down("x".to_string()), Up, Up, Up], &vec![Down("y".to_string())], ]), vec![Down("y".to_string())]); } #[test] fn get_basic() { use ::parse::YamlPathElem::*; let doc = &YamlLoader::load_from_str(" array: - one - two - three object: nested: somewhat: deeply int: 1 float: 2.0 bool: true nothing: null ").unwrap()[0]; assert_eq!(get(doc, &vec![Down("array".to_string())]), &Yaml::Array(vec![Yaml::String("one".to_string()), Yaml::String("two".to_string()), Yaml::String("three".to_string())])); assert_eq!(get(doc, &vec![Down("object".to_string()), Down("nested".to_string()), Up, Down("nested".to_string()), Down("somewhat".to_string())]), &Yaml::String("deeply".to_string())); assert_eq!(get(doc, &vec![Down("int".to_string())]), &Yaml::Integer(1)); assert_eq!(get(doc, &vec![Down("float".to_string())]), &Yaml::Real("2.0".to_string())); assert_eq!(get(doc, &vec![Down("bool".to_string())]), &Yaml::Boolean(true)); assert_eq!(get(doc, &vec![Down("nothing".to_string())]), &Yaml::Null); assert_eq!(get(doc, &vec![Down("missing".to_string())]), &Yaml::BadValue); } #[test] fn bool_basic() { let bad = vec![ Yaml::Boolean(false), Yaml::Null, Yaml::BadValue, Yaml::Array(vec![]), Yaml::Hash(BTreeMap::new()) ]; let good = vec![ Yaml::String("".to_string()), Yaml::Boolean(true), Yaml::Integer(0), Yaml::Integer(-1), Yaml::Array(vec![Yaml::Boolean(false)]), Yaml::Hash(vec![(Yaml::String("".to_string()), Yaml::Null)].into_iter().collect()) ]; for item in bad.into_iter() { assert!(! bool(&item)); } for item in good.into_iter() { assert!(bool(&item)) } } #[test] fn string_basic() { assert_eq!(string(&Yaml::String("".to_string()), false).unwrap(), ""); assert_eq!(string(&Yaml::String("hello".to_string()), false).unwrap(), "hello"); assert_eq!(string(&Yaml::Null, false).unwrap(), ""); assert_eq!(string(&Yaml::Integer(-1), false).unwrap(), "-1"); assert_eq!(string(&Yaml::Real("2.5".to_string()), false).unwrap(), "2.5"); assert_eq!(string(&Yaml::Boolean(true), false).unwrap(), "true"); assert_eq!(string(&Yaml::BadValue, true).unwrap(), ""); assert_eq!(string(&Yaml::Hash(BTreeMap::new()), true).unwrap(), ""); assert_eq!(string(&Yaml::Array(vec![]), true).unwrap(), ""); assert!(string(&Yaml::BadValue, false).is_err()); assert!(string(&Yaml::Hash(BTreeMap::new()), false).is_err()); assert!(string(&Yaml::Array(vec![]), false).is_err()); } #[test] fn merge_basic() { let doc1 = YamlLoader::load_from_str(" arr_append: - a - b arr_untouched: - c obj_append: d: e f: g obj_modify: h: i j: k obj_untouched: l: m number: 1 change_type: true ").unwrap().into_iter().next().unwrap(); let doc2 = YamlLoader::load_from_str(" arr_append: - n - o obj_append: p: q r: s obj_modify: j: t number: 42 change_type: - u - v new_object: w: 1 x: null ").unwrap().into_iter().next().unwrap(); let doc_res = YamlLoader::load_from_str(" arr_append: - a - b - n - o arr_untouched: - c obj_append: d: e f: g p: q r: s obj_modify: h: i j: t obj_untouched: l: m number: 42 change_type: - u - v new_object: w: 1 x: null ").unwrap().into_iter().next().unwrap(); assert_eq!(merge(vec![doc1, doc2]), doc_res); } }
use std::collections::{VecDeque}; use std::rc::{Rc}; use std::cell::{RefCell}; use template::{EventHook}; /// Data for interacting with an active UI component tree inserted through a template. #[derive(Clone)] pub struct EventSink { events: Rc<RefCell<VecDeque<String>>>, } impl EventSink { pub(crate) fn new() -> Self { EventSink { events: Default::default(), } } /// Retrieves the next event raised by a component, or returns None. pub fn next(&self) -> Option<String> { self.events.borrow_mut().pop_front() } /// Raises an event. pub fn raise(&self, event: &EventHook) { match *event { EventHook::Direct(ref value) => self.events.borrow_mut().push_back(value.clone()), EventHook::Script(ref _script) => unimplemented!(), } } }
use graphics::math::*; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::cell::RefMut; use opengl_graphics::Texture; use super::texture_loader::TextureLoader; use super::animator::Animator; pub struct AnimationManager { animators: HashMap<String, RefCell<Animator>>, tex_loader: Rc<TextureLoader> } impl AnimationManager { pub fn new(tex_loader: Rc<TextureLoader>) -> AnimationManager { AnimationManager { animators: HashMap::<String, RefCell<Animator>>::new(), tex_loader } } pub fn add_sequence(&mut self, name: String, file_name: &str, interval: f64, start: i8, stop: i8, box_size: Vec2d) { let mut textures = Vec::<Texture>::new(); for i in start..stop + 1 { let texture = self.tex_loader.load_texture(&format!("{} ({}).png", file_name, i)); textures.push(texture); } let animator = RefCell::new(Animator::new(textures, interval, box_size)); self.animators.insert(name, animator); } pub fn get_animator(&self, name: String) -> RefMut<Animator> { self.animators[&name].borrow_mut() } }
use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use boots::cfg::ControlFlowGraph; use boots::dfg::DataFlowGraph; struct Function { next_block: usize, dfg: DataFlowGraph, cfg: ControlFlowGraph, } impl Function { fn new() -> Function { Function { next_block: 0, dfg: DataFlowGraph::new(), cfg: ControlFlowGraph::new(), } } fn make_block(&mut self) -> Block { let block = self.next_block; self.next_block += 1; Block::new(block) } } #[derive(PartialEq, Eq, Hash)] pub struct Inst(u32); impl VecKey for Inst { fn new(value: usize) -> Inst { Inst(value as u32) } fn index(&self) -> usize { self.0 as usize } } #[derive(PartialEq, Eq, Hash)] pub struct Block(u32); impl VecKey for Block { fn new(value: usize) -> Block { Block(value as u32) } fn index(&self) -> usize { self.0 as usize } } pub struct UserList(Vec<Inst>); impl UserList { pub fn new() -> UserList { UserList(Vec::new()) } } pub enum CmpOp { Lt, Le, Eq, Ne, Gt, Ge, } pub enum InstData { Add { ty: Type, lhs: Inst, rhs: Inst, }, Sub { ty: Type, lhs: Inst, rhs: Inst, }, Goto { target: Block, }, If { opnd: Inst, then_block: Block, else_block: Block, }, Cmp { ty: Type, op: CmpOp, lhs: Inst, rhs: Inst, }, Ret { opnd: Option<Inst>, }, TrueConst, FalseConst, NilConst, Int8Const(u8), Int32Const(i32), Int64Const(i64), Float32Const(f32), Float64Const(f64), Param { ty: Type, idx: u32, }, Deleted, } pub enum Type { Bool, Int8, Int32, Int64, Float32, Float64, Reference, } pub struct VecMap<K, V> where K: VecKey, { data: Vec<V>, unused: PhantomData<K>, } impl<K, V> VecMap<K, V> where K: VecKey, { pub fn new() -> VecMap<K, V> { VecMap { data: Vec::new(), unused: PhantomData, } } pub fn push(&mut self, value: V) -> K { let idx = self.data.len(); self.data.push(value); K::new(idx) } } impl<K, V> Index<K> for VecMap<K, V> where K: VecKey, { type Output = V; fn index(&self, k: K) -> &V { &self.data[k.index()] } } impl<K, V> IndexMut<K> for VecMap<K, V> where K: VecKey, { fn index_mut(&mut self, k: K) -> &mut V { &mut self.data[k.index()] } } pub trait VecKey { fn new(value: usize) -> Self; fn index(&self) -> usize; } #[cfg(test)] mod tests { use super::Function; #[test] fn simple_fn() { let mut fct = Function::new(); let _blk = fct.make_block(); } }
use proconio::input; fn len(mut x: u64) -> usize { let mut l = 0; while x > 0 { x /= 10; l += 1; } l } fn main() { input! { n: usize, a: [u64; n], }; let mut b = a.clone(); b.sort_by_key(|&x| len(x)); b.reverse(); let v = if len(b[0]) == len(b[1]) && len(b[1]) == len(b[2]) { let l = len(b[0]); let mut c: Vec<u64> = a.iter().copied().filter(|&x| len(x) == l).collect(); c.sort(); c.reverse(); assert!(c.len() >= 3); vec![c[0], c[1], c[2]] } else if len(b[0]) == len(b[1]) && len(b[1]) > len(b[2]) { let l = len(b[2]); let mut c: Vec<u64> = a.iter().copied().filter(|&x| len(x) == l).collect(); c.sort(); c.reverse(); assert!(c.len() >= 1); vec![b[0].max(b[1]), b[0].min(b[1]), c[0]] } else if len(b[0]) > len(b[1]) && len(b[1]) == len(b[2]) { let l = len(b[1]); let mut c: Vec<u64> = a.iter().copied().filter(|&x| len(x) == l).collect(); c.sort(); c.reverse(); assert!(c.len() >= 2); vec![b[0], c[0], c[1]] } else if len(b[0]) > len(b[1]) && len(b[1]) > len(b[2]) { let l = len(b[2]); let mut c: Vec<u64> = a.iter().copied().filter(|&x| len(x) == l).collect(); c.sort(); c.reverse(); assert!(c.len() >= 1); vec![b[0], b[1], c[0]] } else { unreachable!(); }; let mut ans = 0_u64; for &(i, j, k) in &[ (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0), ] { let s = format!("{}{}{}", v[i], v[j], v[k]); ans = ans.max(s.parse::<u64>().unwrap()); } println!("{}", ans); }
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // 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::fmt::{self, Display, Formatter}; #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable)] pub enum Status { Ok, Warning, Critical, Unknown, } #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable)] pub struct CheckResult { pub status: Status, pub output: String, } impl CheckResult { pub fn ok(output: String) -> Self { Self::new(Status::Ok, output) } pub fn warning(output: String) -> Self { Self::new(Status::Warning, output) } pub fn critical(output: String) -> Self { Self::new(Status::Critical, output) } pub fn unknown(output: String) -> Self { Self::new(Status::Unknown, output) } fn new(status: Status, output: String) -> Self { CheckResult { status: status, output: output, } } } impl Display for CheckResult { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let status_code = match self.status { Status::Ok => "OK", Status::Warning => "WARNING", Status::Critical => "CRITICAL", Status::Unknown => "UNKNOWN", }; write!(f, "{} - {}", status_code, self.output) } }
use bytes::BytesMut; const BUFFER_CHUNK_SIZE: usize = 25 * 1024 * 1024; // 25mb #[derive(Clone)] pub struct WriteBuffer { pub offset: u64, pub data: BytesMut, } impl WriteBuffer { pub fn new(offset: u64, data: &[u8]) -> Self { Self { offset, data: data.into(), } } pub fn write(&mut self, offset: u64, data: &[u8]) -> bool { if self.data.len() >= BUFFER_CHUNK_SIZE { return false; } if offset >= self.offset && (offset + data.len() as u64) <= self.offset + self.data.len() as u64 { // We stay within the buffer, we can simply write to it. let start_offset = offset - self.offset; let buffer_slice = &mut self.data[start_offset as usize..(start_offset as usize + data.len())]; for (l, r) in buffer_slice.iter_mut().zip(data) { *l = *r; } true } else if offset < self.offset && (offset + data.len() as u64) >= self.offset { if (offset + data.len() as u64) <= self.offset + self.data.len() as u64 { // We don't overflow the buffer, only underflow. So we need to prepend zeros. let prepended_segment_size = (self.offset - offset) as usize; let new_buffer_length = self.data.len() + prepended_segment_size; let mut new_buffer = BytesMut::with_capacity(new_buffer_length); new_buffer.resize(new_buffer_length, 0); // Copy the old buffer in the new one. for (l, r) in new_buffer[prepended_segment_size..] .iter_mut() .zip(&self.data) { *l = *r; } // Then we write the new buffer. for (l, r) in new_buffer[0..data.len()].iter_mut().zip(data) { *l = *r } self.data = new_buffer; } else { // We underflow *and* overflow, this is easy. self.data = BytesMut::from(data); } self.offset = offset; true } else if offset > self.offset && offset <= (self.offset + self.data.len() as u64) && (offset + data.len() as u64) > (self.offset + self.data.len() as u64) { // We overflow the buffer, we need to extend it. let overflow_amount = (offset + data.len() as u64) - (self.offset + self.data.len() as u64); let new_buffer_size = self.data.len() + overflow_amount as usize; debug_assert!(new_buffer_size > self.data.len()); self.data.resize(new_buffer_size, 0); // After extending we're free to write. for (l, r) in self.data[(offset - self.offset) as usize..] .iter_mut() .zip(data) { *l = *r; } true } else { false } } } #[cfg(test)] mod tests { use super::*; #[test] fn sequential_write() { let mut buf = WriteBuffer::new(0, &vec![1, 2, 3, 4]); assert!(buf.write(4, &vec![5, 6, 7, 8])); assert!(buf.write(8, &vec![9, 10, 11, 12])); assert!(buf.write(12, &vec![13, 14, 15, 16])); assert_eq!( &buf.data, &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] ); assert_eq!(buf.offset, 0); } #[test] fn discontinuous_overflow_write() { let mut buf = WriteBuffer::new(0, &vec![1, 2, 3, 4]); assert!(!buf.write(5, &vec! {5, 6, 7, 8})); assert_eq!(&buf.data, &vec![1, 2, 3, 4]); } #[test] fn discontinous_underflow_write() { let mut buf = WriteBuffer::new(10, &vec![1, 2, 3]); assert!(!buf.write(6, &vec![4, 5, 6])); assert_eq!(&buf.data, &vec![1, 2, 3]); } #[test] fn continuous_underflow_write() { let mut buf = WriteBuffer::new(10, &vec![1, 2, 3]); assert!(buf.write(7, &vec![4, 5, 6, 7, 8])); assert_eq!(&buf.data.as_ref(), &vec![4, 5, 6, 7, 8, 3]); assert_eq!(buf.offset, 7); } #[test] fn continuous_overflow_write() { let mut buf = WriteBuffer::new(10, &vec![1, 2, 3]); assert!(buf.write(11, &vec![4, 5, 6])); assert_eq!(&buf.data.as_ref(), &vec![1, 4, 5, 6]); } #[test] fn continuous_full_overwrite() { let mut buf = WriteBuffer::new(10, &vec![1, 2, 3]); assert!(buf.write(9, &vec![4, 5, 6, 7, 8])); assert_eq!(buf.offset, 9); assert_eq!(&buf.data.as_ref(), &vec![4, 5, 6, 7, 8]); } #[test] fn interior_write_no_resize() { let mut buf = WriteBuffer::new(10, &vec![1, 2, 3, 4]); assert!(buf.write(11, &vec![5, 6])); assert_eq!(buf.offset, 10); assert_eq!(&buf.data.as_ref(), &vec![1, 5, 6, 4]); } }
import syntax::ast::*; import syntax::visit; import std::ivec; import std::option::*; import aux::*; import tstate::ann::pre_and_post; import tstate::ann::precond; import tstate::ann::postcond; import tstate::ann::prestate; import tstate::ann::poststate; import tstate::ann::relax_prestate; import tstate::ann::relax_precond; import tstate::ann::relax_poststate; import tstate::ann::pps_len; import tstate::ann::true_precond; import tstate::ann::empty_prestate; import tstate::ann::difference; import tstate::ann::union; import tstate::ann::intersect; import tstate::ann::clone; import tstate::ann::set_in_postcond; import tstate::ann::set_in_poststate; import tstate::ann::set_in_poststate_; import tstate::ann::clear_in_poststate; import tstate::ann::clear_in_prestate; import tstate::ann::clear_in_poststate_; import tritv::*; import util::common::*; fn bit_num(fcx: &fn_ctxt, c: &tsconstr) -> uint { let d = tsconstr_to_def_id(c); assert (fcx.enclosing.constrs.contains_key(d)); let rslt = fcx.enclosing.constrs.get(d); alt c { ninit(_, _) { alt rslt { cinit(n, _, _) { ret n; } _ { fcx.ccx.tcx.sess.bug("bit_num: asked for init constraint," + " found a pred constraint"); } } } npred(_, _, args) { alt rslt { cpred(_, descs) { ret match_args(fcx, descs, args); } _ { fcx.ccx.tcx.sess.bug("bit_num: asked for pred constraint," + " found an init constraint"); } } } } } fn promises(fcx: &fn_ctxt, p: &poststate, c: &tsconstr) -> bool { ret promises_(bit_num(fcx, c), p); } fn promises_(n: uint, p: &poststate) -> bool { ret tritv_get(p, n) == ttrue; } // v "happens after" u fn seq_trit(u: trit, v: trit) -> trit { alt v { ttrue. { ttrue } tfalse. { tfalse } dont_care. { u } } } // idea: q "happens after" p -- so if something is // 1 in q and 0 in p, it's 1 in the result; however, // if it's 0 in q and 1 in p, it's 0 in the result fn seq_tritv(p: &postcond, q: &postcond) { let i = 0u; assert (p.nbits == q.nbits); while i < p.nbits { tritv_set(i, p, seq_trit(tritv_get(p, i), tritv_get(q, i))); i += 1u; } } fn seq_postconds(fcx: &fn_ctxt, ps: &postcond[]) -> postcond { let sz = ivec::len(ps); if sz >= 1u { let prev = tritv_clone(ps.(0)); for p: postcond in ivec::slice(ps, 1u, sz) { seq_tritv(prev, p); } ret prev; } else { ret ann::empty_poststate(num_constraints(fcx.enclosing)); } } // Given a list of pres and posts for exprs e0 ... en, // return the precondition for evaluating each expr in order. // So, if e0's post is {x} and e1's pre is {x, y, z}, the entire // precondition shouldn't include x. fn seq_preconds(fcx: &fn_ctxt, pps: &pre_and_post[]) -> precond { let sz: uint = ivec::len(pps); let num_vars: uint = num_constraints(fcx.enclosing); fn seq_preconds_go(fcx: &fn_ctxt, pps: &pre_and_post[], first: &pre_and_post) -> precond { let sz: uint = ivec::len(pps); if sz >= 1u { let second = pps.(0); assert (pps_len(second) == num_constraints(fcx.enclosing)); let second_pre = clone(second.precondition); difference(second_pre, first.postcondition); let next_first = clone(first.precondition); union(next_first, second_pre); let next_first_post = clone(first.postcondition); seq_tritv(next_first_post, second.postcondition); ret seq_preconds_go(fcx, ivec::slice(pps, 1u, sz), @{precondition: next_first, postcondition: next_first_post}); } else { ret first.precondition; } } if sz >= 1u { let first = pps.(0); assert (pps_len(first) == num_vars); ret seq_preconds_go(fcx, ivec::slice(pps, 1u, sz), first); } else { ret true_precond(num_vars); } } fn intersect_states(p: &prestate, q: &prestate) -> prestate { let rslt = tritv_clone(p); tritv_intersect(rslt, q); ret rslt; } fn gen(fcx: &fn_ctxt, id: node_id, c: &tsconstr) -> bool { ret set_in_postcond(bit_num(fcx, c), node_id_to_ts_ann(fcx.ccx, id).conditions); } fn declare_var(fcx: &fn_ctxt, c: &tsconstr, pre: prestate) -> prestate { let rslt = clone(pre); relax_prestate(bit_num(fcx, c), rslt); // idea is this is scoped relax_poststate(bit_num(fcx, c), rslt); ret rslt; } fn relax_precond_expr(e: &@expr, cx: &relax_ctxt, vt: &visit::vt[relax_ctxt]) { relax_precond(cx.i as uint, expr_precond(cx.fcx.ccx, e)); visit::visit_expr(e, cx, vt); } fn relax_precond_stmt(s: &@stmt, cx: &relax_ctxt, vt: &visit::vt[relax_ctxt]) { relax_precond(cx.i as uint, stmt_precond(cx.fcx.ccx, *s)); visit::visit_stmt(s, cx, vt); } type relax_ctxt = {fcx:fn_ctxt, i:node_id}; fn relax_precond_block_inner(b: &blk, cx: &relax_ctxt, vt: &visit::vt[relax_ctxt]) { relax_precond(cx.i as uint, block_precond(cx.fcx.ccx, b)); visit::visit_block(b, cx, vt); } fn relax_precond_block(fcx: &fn_ctxt, i: node_id, b:&blk) { let cx = {fcx: fcx, i: i}; let visitor = visit::default_visitor[relax_ctxt](); visitor = @{visit_block: relax_precond_block_inner, visit_expr: relax_precond_expr, visit_stmt: relax_precond_stmt, visit_item: (fn (i: &@item, cx: &relax_ctxt, vt: &visit::vt[relax_ctxt]) {}) with *visitor}; let v1 = visit::mk_vt(visitor); v1.visit_block(b, cx, v1); } fn gen_poststate(fcx: &fn_ctxt, id: node_id, c: &tsconstr) -> bool { log "gen_poststate"; ret set_in_poststate(bit_num(fcx, c), node_id_to_ts_ann(fcx.ccx, id).states); } fn kill_prestate(fcx: &fn_ctxt, id: node_id, c: &tsconstr) -> bool { ret clear_in_prestate(bit_num(fcx, c), node_id_to_ts_ann(fcx.ccx, id).states); } fn kill_poststate(fcx: &fn_ctxt, id: node_id, c: &tsconstr) -> bool { log "kill_poststate"; ret clear_in_poststate(bit_num(fcx, c), node_id_to_ts_ann(fcx.ccx, id).states); } fn clear_in_poststate_expr(fcx: &fn_ctxt, e: &@expr, t: &poststate) { alt e.node { expr_path(p) { alt ivec::last(p.node.idents) { some(i) { alt local_node_id_to_def(fcx, e.id) { some(def_local(d_id)) { clear_in_poststate_(bit_num(fcx, ninit(d_id.node, i)), t); } some(_) {/* ignore args (for now...) */ } _ { fcx.ccx.tcx.sess.bug("clear_in_poststate_expr: \ unbound var"); } } } _ { fcx.ccx.tcx.sess.bug("clear_in_poststate_expr"); } } } _ {/* do nothing */ } } } fn kill_poststate_(fcx : &fn_ctxt, c : &tsconstr, post : &poststate) -> bool { log "kill_poststate_"; ret clear_in_poststate_(bit_num(fcx, c), post); } fn set_in_poststate_ident(fcx: &fn_ctxt, id: &node_id, ident: &ident, t: &poststate) -> bool { ret set_in_poststate_(bit_num(fcx, ninit(id, ident)), t); } fn set_in_prestate_constr(fcx: &fn_ctxt, c: &tsconstr, t: &prestate) -> bool { ret set_in_poststate_(bit_num(fcx, c), t); } fn clear_in_poststate_ident(fcx: &fn_ctxt, id: &node_id, ident: &ident, parent: &node_id) -> bool { ret kill_poststate(fcx, parent, ninit(id, ident)); } fn clear_in_prestate_ident(fcx: &fn_ctxt, id: &node_id, ident: &ident, parent: &node_id) -> bool { ret kill_prestate(fcx, parent, ninit(id, ident)); } fn clear_in_poststate_ident_(fcx : &fn_ctxt, id : &node_id, ident : &ident, post : &poststate) -> bool { ret kill_poststate_(fcx, ninit(id, ident), post); } // // Local Variables: // mode: rust // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: //
use async_std::{io::{Read,Write},fs}; use std::path::PathBuf; pub trait RW: Read+Write+Send+Sync+Unpin {} impl RW for fs::File {} type Error = Box<dyn std::error::Error+Send+Sync>; #[async_trait::async_trait] pub trait Storage<S>: Send+Sync+Unpin where S: RW { async fn open(&mut self, name: &str) -> Result<S,Error>; //async fn remove(&mut self, name: &str) -> Result<Self,Error>; } pub struct FileStorage { path: PathBuf, } impl FileStorage { pub async fn open_from_path<P>(path: P) -> Result<Self,Error> where PathBuf: From<P> { Ok(Self { path: path.into() }) } } #[async_trait::async_trait] impl Storage<fs::File> for FileStorage { async fn open(&mut self, name: &str) -> Result<fs::File,Error> { let p = self.path.join(name); fs::create_dir_all(p.parent().unwrap()).await?; Ok(fs::OpenOptions::new().read(true).write(true).create(true).open(p).await?) } }
extern crate gfx_hal as hal; extern crate rendy; extern crate winit; use hal::{Adapter, Backend, Instance}; use rendy::{ command::{CapabilityFlags, Families, Family, FamilyId}, Config, Device, Factory, QueuesPicker, RenderBuilder, }; use winit::{EventsLoop, WindowBuilder}; use std::marker::PhantomData; fn main() -> Result<(), ()> { // Create a window with winit. let mut events_loop = EventsLoop::new(); let window = WindowBuilder::new() .with_title("Part 00: Triangle") .with_dimensions((848, 480).into()) .build(&events_loop) .unwrap(); let render_config = RenderBuilder::new().with_window(window).build(); let config = Config::new(vec![render_config]); // TODO: migrate example to `ash` // let instance = backend::Instance::create("Rendy basic example", 1); // let adapter = instance.enumerate_adapters().remove(0); // type HalDevice = ( // <backend::Backend as Backend>::Device, // PhantomData<backend::Backend>, // ); //let _factory = rendy::init::<HalDevice, PickFirst, backend::Backend>(config); Ok(()) } struct PickFirst; impl QueuesPicker for PickFirst { fn pick_queues<Q>( &self, families: Vec<Families<Q>>, ) -> Result<(Family<Q, CapabilityFlags>, u32), ()> { unimplemented!() } }