text
stringlengths
8
4.13M
//! Generic implementation of Cipher-based Message Authentication Code (CMAC), //! otherwise known as OMAC1. //! //! # Usage //! We will use AES-128 block cipher from [aes](https://docs.rs/aes) crate. //! //! To get the authentication code: //! //! ```rust //! extern crate cmac; //! extern crate aes; //! //! use aes::Aes128; //! use cmac::{Cmac, Mac}; //! //! # fn main() { //! // Create `Mac` trait implementation, namely CMAC-AES128 //! let mut mac = Cmac::<Aes128>::new_varkey(b"very secret key.").unwrap(); //! mac.input(b"input message"); //! //! // `result` has type `MacResult` which is a thin wrapper around array of //! // bytes for providing constant time equality check //! let result = mac.result(); //! // To get underlying array use `code` method, but be carefull, since //! // incorrect use of the code value may permit timing attacks which defeat //! // the security provided by the `MacResult` //! let code_bytes = result.code(); //! # } //! ``` //! //! To verify the message: //! //! ```rust //! # extern crate cmac; //! # extern crate aes; //! # use aes::Aes128; //! # use cmac::{Cmac, Mac}; //! # fn main() { //! let mut mac = Cmac::<Aes128>::new_varkey(b"very secret key.").unwrap(); //! //! mac.input(b"input message"); //! //! # let code_bytes = mac.clone().result().code(); //! // `verify` will return `Ok(())` if code is correct, `Err(MacError)` otherwise //! mac.verify(&code_bytes).unwrap(); //! # } //! ``` #![no_std] #![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")] extern crate block_cipher_trait; pub extern crate crypto_mac; extern crate dbl; use block_cipher_trait::generic_array::typenum::Unsigned; use block_cipher_trait::generic_array::{ArrayLength, GenericArray}; use block_cipher_trait::BlockCipher; pub use crypto_mac::Mac; use crypto_mac::{InvalidKeyLength, MacResult}; use dbl::Dbl; use core::fmt; type Block<N> = GenericArray<u8, N>; /// Generic CMAC instance #[derive(Clone)] pub struct Cmac<C> where C: BlockCipher + Clone, Block<C::BlockSize>: Dbl, { cipher: C, key1: Block<C::BlockSize>, key2: Block<C::BlockSize>, buffer: Block<C::BlockSize>, pos: usize, } impl<C> Cmac<C> where C: BlockCipher + Clone, Block<C::BlockSize>: Dbl, { fn from_cipher(cipher: C) -> Self { let mut subkey = GenericArray::default(); cipher.encrypt_block(&mut subkey); let key1 = subkey.dbl(); let key2 = key1.clone().dbl(); Cmac { cipher, key1, key2, buffer: Default::default(), pos: 0, } } } #[inline(always)] fn xor<L: ArrayLength<u8>>(buf: &mut Block<L>, data: &Block<L>) { for i in 0..L::to_usize() { buf[i] ^= data[i]; } } impl<C> Mac for Cmac<C> where C: BlockCipher + Clone, Block<C::BlockSize>: Dbl, C::BlockSize: Clone, { type OutputSize = C::BlockSize; type KeySize = C::KeySize; fn new(key: &GenericArray<u8, Self::KeySize>) -> Self { Self::from_cipher(C::new(key)) } fn new_varkey(key: &[u8]) -> Result<Self, InvalidKeyLength> { let cipher = C::new_varkey(key).map_err(|_| InvalidKeyLength)?; Ok(Self::from_cipher(cipher)) } #[inline] fn input(&mut self, mut data: &[u8]) { let n = C::BlockSize::to_usize(); let rem = n - self.pos; if data.len() >= rem { let (l, r) = data.split_at(rem); data = r; for (a, b) in self.buffer[self.pos..].iter_mut().zip(l) { *a ^= *b; } self.pos = n; } else { for (a, b) in self.buffer[self.pos..].iter_mut().zip(data) { *a ^= *b; } self.pos += data.len(); return; } while data.len() >= n { self.cipher.encrypt_block(&mut self.buffer); let (l, r) = data.split_at(n); let block = unsafe { &*(l.as_ptr() as *const Block<C::BlockSize>) }; data = r; xor(&mut self.buffer, block); } if data.len() != 0 { self.cipher.encrypt_block(&mut self.buffer); for (a, b) in self.buffer.iter_mut().zip(data) { *a ^= *b; } self.pos = data.len(); } } #[inline] fn result(mut self) -> MacResult<Self::OutputSize> { let n = C::BlockSize::to_usize(); let mut buf = self.buffer.clone(); if self.pos == n { xor(&mut buf, &self.key1); } else { xor(&mut buf, &self.key2); buf[self.pos] ^= 0x80; } self.cipher.encrypt_block(&mut buf); MacResult::new(buf) } fn reset(&mut self) { self.buffer = Default::default(); self.pos = 0; } } impl<C> fmt::Debug for Cmac<C> where C: BlockCipher + fmt::Debug + Clone, Block<C::BlockSize>: Dbl, { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Cmac-{:?}", self.cipher) } }
//https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/submissions/ impl Solution { pub fn replace_elements(mut arr: Vec<i32>) -> Vec<i32> { let mut max_right = -1; for i in (0..arr.len()).rev() { let tmp = arr[i]; arr[i] = max_right; max_right = max_right.max(tmp); } return arr } }
pub(crate) mod systems; mod action; mod config; mod cursor; mod plugin; pub use action::*; pub use config::*; pub use cursor::*; pub use plugin::*; game_lib::fix_bevy_derive!(game_lib::bevy);
//! Contains the ffi-safe equivalent of `std::cmp::Ordering`. use std::cmp::Ordering; /// Ffi-safe equivalent of `std::cmp::Ordering`. /// /// # Example /// /// This defines an extern function, which compares a slice to another. /// /// ```rust /// /// use abi_stable::{ /// sabi_extern_fn, /// std_types::{RCmpOrdering, RSlice}, /// }; /// use std::cmp::Ord; /// /// #[sabi_extern_fn] /// pub fn compare_slices<T>(l: RSlice<'_, T>, r: RSlice<'_, T>) -> RCmpOrdering /// where /// T: Ord, /// { /// l.cmp(&r).into() /// } /// /// ``` #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[repr(u8)] #[derive(StableAbi)] pub enum RCmpOrdering { /// Less, /// Equal, /// Greater, } impl RCmpOrdering { /// Converts this `RCmpOrdering` into a `std::cmp::Ordering`; /// /// # Example /// /// ``` /// use abi_stable::std_types::RCmpOrdering; /// use std::cmp::Ordering; /// /// assert_eq!(RCmpOrdering::Less.to_ordering(), Ordering::Less); /// assert_eq!(RCmpOrdering::Equal.to_ordering(), Ordering::Equal); /// assert_eq!(RCmpOrdering::Greater.to_ordering(), Ordering::Greater); /// /// ``` #[inline] pub const fn to_ordering(self) -> Ordering { match self { RCmpOrdering::Less => Ordering::Less, RCmpOrdering::Equal => Ordering::Equal, RCmpOrdering::Greater => Ordering::Greater, } } /// Converts a [`std::cmp::Ordering`] to [`RCmpOrdering`]; /// /// # Example /// /// ``` /// use abi_stable::std_types::RCmpOrdering; /// use std::cmp::Ordering; /// /// assert_eq!(RCmpOrdering::from_ordering(Ordering::Less), RCmpOrdering::Less); /// assert_eq!(RCmpOrdering::from_ordering(Ordering::Equal), RCmpOrdering::Equal); /// assert_eq!(RCmpOrdering::from_ordering(Ordering::Greater), RCmpOrdering::Greater); /// /// ``` #[inline] pub const fn from_ordering(ordering: Ordering) -> RCmpOrdering { match ordering { Ordering::Less => RCmpOrdering::Less, Ordering::Equal => RCmpOrdering::Equal, Ordering::Greater => RCmpOrdering::Greater, } } } impl_from_rust_repr! { impl From<Ordering> for RCmpOrdering { fn(this){ RCmpOrdering::from_ordering(this) } } } impl_into_rust_repr! { impl Into<Ordering> for RCmpOrdering { fn(this){ this.to_ordering() } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use spin::Mutex; use alloc::string::ToString; use core::sync::atomic::Ordering; use alloc::vec::Vec; use super::super::super::super::qlib::common::*; use super::super::super::super::qlib::linux_def::*; use super::super::super::super::qlib::auth::*; use super::super::super::super::qlib::usage::io::*; use super::super::super::fsutil::file::readonly_file::*; use super::super::super::fsutil::inode::simple_file_inode::*; use super::super::super::super::task::*; use super::super::super::attr::*; use super::super::super::file::*; use super::super::super::flags::*; use super::super::super::dirent::*; use super::super::super::mount::*; use super::super::super::inode::*; use super::super::super::super::threadmgr::thread::*; use super::super::super::super::threadmgr::thread_group::*; use super::super::super::super::threadmgr::task_acct::*; use super::super::inode::*; pub fn NewIO(task: &Task, thread: &Thread, msrc: &Arc<Mutex<MountSource>>) -> Inode { let v = NewIOSimpleFileInode(task, thread, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o400)), FSMagic::PROC_SUPER_MAGIC); return NewProcInode(&Arc::new(v), msrc, InodeType::SpecialFile, Some(thread.clone())) } pub fn NewIOSimpleFileInode(task: &Task, thread: &Thread, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> SimpleFileInode<IOData> { let tg = thread.ThreadGroup(); let io = IOData{tg: tg}; return SimpleFileInode::New(task, owner, perms, typ, false, io) } pub struct IOData { tg: ThreadGroup, } impl IOData { pub fn GenSnapshot(&self) -> Vec<u8> { let io = IO::default(); io.Accumulate(&self.tg.IOUsage()); let mut buf = "".to_string(); buf += &format!("char: {}\n", io.CharsRead.load(Ordering::SeqCst)); buf += &format!("wchar: {}\n", io.CharsWritten.load(Ordering::SeqCst)); buf += &format!("syscr: {}\n", io.ReadSyscalls.load(Ordering::SeqCst)); buf += &format!("syscw: {}\n", io.WriteSyscalls.load(Ordering::SeqCst)); buf += &format!("read_bytes: {}\n", io.BytesRead.load(Ordering::SeqCst)); buf += &format!("write_bytes: {}\n", io.BytesWritten.load(Ordering::SeqCst)); buf += &format!("cancelled_write_bytes: {}\n", io.BytesWriteCancelled.load(Ordering::SeqCst)); return buf.as_bytes().to_vec(); } } impl SimpleFileTrait for IOData { fn GetFile(&self, _task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { let fops = NewSnapshotReadonlyFileOperations(self.GenSnapshot()); let file = File::New(dirent, &flags, fops); return Ok(file); } } /*use alloc::sync::Arc; use spin::Mutex; use alloc::vec::Vec; use core::sync::atomic::Ordering; use alloc::string::ToString; use super::super::super::super::qlib::usage::io::*; use super::super::super::super::task::*; use super::super::super::attr::*; use super::super::super::mount::*; use super::super::super::inode::*; use super::super::super::super::threadmgr::thread_group::*; use super::super::super::super::threadmgr::task_acct::*; use super::super::inode::*; use super::super::seqfile::*; pub fn NewIO(task: &Task, msrc: &Arc<Mutex<MountSource>>) -> Inode { let tg = task.Thread().ThreadGroup(); let seqFile = SeqFile::New(task, Arc::new(Mutex::new(IOData{tg: tg}))); return NewProcInode(&Arc::new(seqFile), msrc, InodeType::SpecialFile, Some(task)) } pub struct IOData { tg: ThreadGroup, } impl SeqSource for IOData { fn NeedsUpdate(&mut self, generation: i64) -> bool { return generation == 0; } fn ReadSeqFileData(&mut self, _task: &Task, handle: SeqHandle) -> (Vec<SeqData>, i64) { info!("IOData ReadSeqFileData..."); match handle { SeqHandle::None => (), _ => return (Vec::new(), 0), } let io = IO::default(); io.Accumulate(&self.tg.IOUsage()); let mut buf = "".to_string(); buf += &format!("char: {}\n", io.CharsRead.load(Ordering::SeqCst)); buf += &format!("wchar: {}\n", io.CharsWritten.load(Ordering::SeqCst)); buf += &format!("syscr: {}\n", io.ReadSyscalls.load(Ordering::SeqCst)); buf += &format!("syscw: {}\n", io.WriteSyscalls.load(Ordering::SeqCst)); buf += &format!("read_bytes: {}\n", io.BytesRead.load(Ordering::SeqCst)); buf += &format!("write_bytes: {}\n", io.BytesWritten.load(Ordering::SeqCst)); buf += &format!("cancelled_write_bytes: {}\n", io.BytesWriteCancelled.load(Ordering::SeqCst)); info!("IOData ReadSeqFileData... buf is {}", &buf); return (vec!(SeqData { Buf: buf.as_bytes().to_vec(), Handle: SeqHandle::None, }), 0) } }*/
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_expression::TableSchema; use common_meta_app::schema::TableInfo; #[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq, Debug)] pub struct ResultScanTableInfo { pub table_info: TableInfo, pub query_id: String, pub block_raw_data: Vec<u8>, } impl ResultScanTableInfo { pub fn schema(&self) -> Arc<TableSchema> { self.table_info.schema() } pub fn desc(&self) -> String { "RESULT_SCAN table function".to_string() } }
use std::fmt; use crate::utils::get_timestamp; use chrono::{prelude::*, Local}; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct TimeStamp(i64); impl TimeStamp { pub fn now() -> Self { Self(get_timestamp()) } pub fn touch(&mut self) { self.0 = get_timestamp(); } pub fn get_timestamp(&self) -> i64 { self.0 } } impl From<i64> for TimeStamp { fn from(time: i64) -> Self { Self(time) } } impl fmt::Display for TimeStamp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", Local.timestamp(self.0, 0).to_rfc2822()) } }
//! Asynchronous ARDOP TNC backend //! //! This module contains the "meat" of the ARDOP TNC //! interface. This object is asynchronous and returns //! futures for all blocking operations. It also includes //! management of ARQ connections. //! //! Higher-level objects will separate control functions //! and ARQ connections into separate objects. //! use std::fmt; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::string::String; use std::time::{Duration, Instant}; use futures::io::{AsyncRead, AsyncWrite}; use futures::sink::{Sink, SinkExt}; use futures::stream::{Stream, StreamExt}; use futures::task::{noop_waker_ref, Context, Poll}; use futures_codec::Framed; use async_std::net::TcpStream; use async_std::prelude::*; use super::controlstream; use super::controlstream::{ControlSink, ControlStreamEvents, ControlStreamResults}; use super::data::{DataIn, DataOut}; use super::dataevent::{DataEvent, DataEventStream}; use crate::arq::{ConnectionFailedReason, ConnectionInfo}; use crate::framing::data::TncDataFraming; use crate::protocol::command; use crate::protocol::command::Command; use crate::protocol::constants::{CommandID, ProtocolMode}; use crate::protocol::response::{CommandOk, CommandResult, ConnectionStateChange}; use crate::tnc::{DiscoveredPeer, PingAck, PingFailedReason, TncError, TncResult}; // Offset between control port and data port const DATA_PORT_OFFSET: u16 = 1; // Default timeout for local TNC commands const DEFAULT_TIMEOUT_COMMAND: Duration = Duration::from_millis(20000); // Timeout for async disconnect const TIMEOUT_DISCONNECT: Duration = Duration::from_secs(60); // Ping timeout, per ping sent const TIMEOUT_PING: Duration = Duration::from_secs(5); /// The output of `listen_monitor()` pub enum ConnectionInfoOrPeerDiscovery { Connection(ConnectionInfo), PeerDiscovery(DiscoveredPeer), } /// Asynchronous ARDOP TNC /// /// This object communicates with the ARDOP program /// via TCP, and it holds all I/O resources for this /// task. pub struct AsyncTnc<I> where I: AsyncRead + AsyncWrite + Unpin + Send, { data_stream: DataEventStream<Framed<I, TncDataFraming>, ControlStreamEvents<I>>, control_in_res: ControlStreamResults<I>, control_out: ControlSink<I>, control_timeout: Duration, disconnect_progress: DisconnectProgress, } /// Type specialization for public API pub type AsyncTncTcp = AsyncTnc<TcpStream>; impl<I: 'static> AsyncTnc<I> where I: AsyncRead + AsyncWrite + Unpin + Send, { /// Connect to an ARDOP TNC /// /// Returns a future which will connect to an ARDOP TNC /// and initialize it. /// /// # Parameters /// - `control_addr`: Network address of the ARDOP TNC's /// control port. /// - `mycall`: The formally-assigned callsign for your station. /// Legitimate call signs include from 3 to 7 ASCII characters /// (A-Z, 0-9) followed by an optional "`-`" and an SSID of /// `-0` to `-15` or `-A` to `-Z`. An SSID of `-0` is treated /// as no SSID. /// /// # Returns /// A new `AsyncTnc`, or an error if the connection or /// initialization step fails. pub async fn new<S>(control_addr: &SocketAddr, mycall: S) -> TncResult<AsyncTnc<TcpStream>> where S: Into<String>, { let data_addr = SocketAddr::new(control_addr.ip(), control_addr.port() + DATA_PORT_OFFSET); // connect let stream_control: TcpStream = TcpStream::connect(control_addr).await?; let stream_data: TcpStream = TcpStream::connect(&data_addr).await?; let mut out = AsyncTnc::new_from_streams(stream_control, stream_data, mycall); // Try to initialize the TNC. If we fail here, we will bail // with an error instead. match out.initialize().await { Ok(()) => { info!("Initialized ARDOP TNC at {}", &control_addr); Ok(out) } Err(e) => { error!( "Unable to initialize ARDOP TNC at {}: {}", &control_addr, &e ); Err(e) } } } /// New from raw I/O types /// /// # Parameters /// - `stream_control`: I/O stream to the TNC's control port /// - `stream_data`: I/O stream to the TNC's data port /// - `mycall`: The formally-assigned callsign for your station. /// Legitimate call signs include from 3 to 7 ASCII characters /// (A-Z, 0-9) followed by an optional "`-`" and an SSID of /// `-0` to `-15` or `-A` to `-Z`. An SSID of `-0` is treated /// as no SSID. /// /// # Returns /// A new `AsyncTnc`. pub(crate) fn new_from_streams<S>(stream_control: I, stream_data: I, mycall: S) -> AsyncTnc<I> where S: Into<String>, { // create receiver streams for the control port let (control_in_evt, control_in_res, control_out) = controlstream::controlstream(stream_control); // create data port input/output framer let data_inout = Framed::new(stream_data, TncDataFraming::new()); AsyncTnc { data_stream: DataEventStream::new(mycall, data_inout, control_in_evt), control_in_res, control_out, control_timeout: DEFAULT_TIMEOUT_COMMAND, disconnect_progress: DisconnectProgress::NoProgress, } } /// Get this station's callsign /// /// # Returns /// The formally assigned callsign for this station. pub fn mycall(&self) -> &String { self.data_stream.state().mycall() } /// Gets the control connection timeout value /// /// Commands sent via the `command()` method will /// timeout if either the send or receive takes /// longer than `timeout`. /// /// Command timeouts cause an `TncError::IoError` /// of type `io::ErrorKind::TimedOut`. This error /// indicates that the socket connection is likely dead. /// /// # Returns /// Current timeout value pub fn control_timeout(&self) -> &Duration { &self.control_timeout } /// Sets timeout for the control connection /// /// Commands sent via the `command()` method will /// timeout if either the send or receive takes /// longer than `timeout`. /// /// Command timeouts cause an `TncError::IoError` /// of type `io::ErrorKind::TimedOut`. This error /// indicates that the socket connection is likely dead. /// /// # Parameters /// - `timeout`: New command timeout value pub fn set_control_timeout(&mut self, timeout: Duration) { self.control_timeout = timeout; } /// Events and data stream, for both incoming and outgoing data /// /// The stream emits both connection-relevant events and /// data received from remote peers. /// /// The sink accepts data for transmission over the air. /// Each FEC transmission must be sent in one call. ARQ /// data may be sent in a streaming manner. /// /// # Return /// Stream + Sink reference pub fn data_stream_sink( &mut self, ) -> &mut (impl Stream<Item = DataEvent> + Sink<DataOut, Error = io::Error> + Unpin) { &mut self.data_stream } /// Send a command to the TNC and await the response /// /// A future which will send the given command and wait /// for a success or failure response. The waiting time /// is upper-bounded by AsyncTnc's `control_timeout()` /// value. /// /// # Parameters /// - `cmd`: The Command to send /// /// # Returns /// An empty on success or a `TncError`. pub async fn command<F>(&mut self, cmd: Command<F>) -> TncResult<()> where F: fmt::Display, { match execute_command( &mut self.control_out, &mut self.control_in_res, &self.control_timeout, cmd, ) .await { Ok(cmdok) => { debug!("Command {} OK", cmdok.0); Ok(()) } Err(e) => { warn!("Command failed: {}", &e); Err(e) } } } /// Wait for a clear channel /// /// Waits for the RF channel to become clear, according /// to the TNC's busy-channel detection logic. This method /// will await for at most `max_wait` for the RF channel to /// be clear for at least `clear_time`. /// /// # Parameters /// - `clear_time`: Time that the channel must be clear. If /// zero, busy-detection logic is disabled. /// - `max_wait`: Wait no longer than this time for a clear /// channel. /// /// # Returns /// If `max_wait` elapses before the channel becomes clear, /// returns `TncError::TimedOut`. If the channel has become /// clear, and has remained clear for `clear_time`, then /// returns `Ok`. pub async fn await_clear(&mut self, clear_time: Duration, max_wait: Duration) -> TncResult<()> { if clear_time == Duration::from_secs(0) { warn!("Busy detector is DISABLED. Assuming channel is clear."); return Ok(()); } // Consume all events which are available, but don't // actually wait. let mut ctx = Context::from_waker(noop_waker_ref()); loop { match Pin::new(&mut self.data_stream).poll_next(&mut ctx) { Poll::Pending => break, Poll::Ready(None) => return Err(connection_reset_err().into()), Poll::Ready(Some(_evt)) => continue, } } // Determine if we have been clear for long enough. // If so, we're done. if self.data_stream.state().clear_time() > clear_time { info!("Channel is CLEAR and READY for use at +0.0 seconds"); return Ok(()); } info!( "Waiting for a clear channel: {:0.1} seconds within {:0.1} seconds...", clear_time.as_millis() as f32 / 1000.0f32, max_wait.as_millis() as f32 / 1000.0f32 ); // Until we time out... let wait_start = Instant::now(); loop { // how much longer can we wait? let wait_elapsed = wait_start.elapsed(); if wait_elapsed >= max_wait { info!("Timed out while waiting for clear channel."); return Err(TncError::TimedOut); } let mut wait_remaining = max_wait - wait_elapsed; // if we are clear, we only need to wait until our clear_time if !self.data_stream.state().busy() { let clear_elapsed = self.data_stream.state().clear_time(); if clear_elapsed >= clear_time { info!( "Channel is CLEAR and READY for use at +{:0.1} seconds", wait_elapsed.as_millis() as f32 / 1000.0f32 ); break; } let clear_remaining = clear_time - clear_elapsed; wait_remaining = wait_remaining.min(clear_remaining) } // wait for next state transition match self.next_state_change_timeout(wait_remaining).await { Err(TncError::TimedOut) => continue, Err(_e) => return Err(_e), Ok(ConnectionStateChange::Busy(busy)) => { if busy { info!( "Channel is BUSY at +{:0.1} seconds", wait_start.elapsed().as_millis() as f32 / 1000.0f32 ); } else { info!( "Channel is CLEAR at +{:0.1} seconds", wait_start.elapsed().as_millis() as f32 / 1000.0f32 ); } } _ => continue, } } Ok(()) } /// Ping a remote `target` peer /// /// When run, this future will /// /// 1. Wait for a clear channel /// 2. Send an outgoing `PING` request /// 3. Wait for a reply or for the ping timeout to elapse /// /// # Parameters /// - `target`: Peer callsign, with optional `-SSID` portion /// - `attempts`: Number of ping packets to send before /// giving up /// - `clear_time`: Minimum time channel must be clear. If zero, /// busy channel detection is disabled. /// - `clear_max_wait`: Maximum time user is willing to wait for /// a clear channel. /// /// # Return /// The outer result contains failures related to the local /// TNC connection. /// /// The inner result is the success or failure of the ping /// operation. If the ping succeeds, returns an `Ok(PingAck)` /// with the response from the remote peer. If the ping fails, /// returns `Err(PingFailedReason)`. Errors include: /// /// * `Busy`: The RF channel was busy during the ping attempt, /// and no ping was sent. /// * `NoAnswer`: The remote peer did not answer. pub async fn ping<S>( &mut self, target: S, attempts: u16, clear_time: Duration, clear_max_wait: Duration, ) -> TncResult<Result<PingAck, PingFailedReason>> where S: Into<String>, { if attempts <= 0 { return Ok(Err(PingFailedReason::NoAnswer)); } // Wait for clear channel match self.await_clear(clear_time, clear_max_wait).await { Ok(_ok) => {} Err(TncError::TimedOut) => return Ok(Err(PingFailedReason::Busy)), Err(e) => return Err(e), } // Send the ping let target_string = target.into(); info!("Pinging {} ({} attempts)...", &target_string, attempts); self.command(command::ping(target_string.clone(), attempts)) .await?; // The ping will expire at timeout_seconds in the future let timeout_seconds = attempts as u64 * TIMEOUT_PING.as_secs(); let start = Instant::now(); loop { match self.next_state_change_timeout(TIMEOUT_PING.clone()).await { Err(TncError::TimedOut) => { /* ignore */ } Ok(ConnectionStateChange::PingAck(snr, quality)) => { let ack = PingAck::new(target_string, snr, quality); info!("{}", &ack); return Ok(Ok(ack)); } Err(e) => return Err(e), _ => { /* ignore */ } } if start.elapsed().as_secs() >= timeout_seconds { // ping timeout break; } } info!("Ping {}: ping timeout", &target_string); Ok(Err(PingFailedReason::NoAnswer)) } /// Dial a remote `target` peer /// /// When run, this future will /// /// 1. Wait for a clear channel /// 2. Make an outgoing `ARQCALL` to the designated callsign /// 3. Wait for a connection to either complete or fail /// /// # Parameters /// - `target`: Peer callsign, with optional `-SSID` portion /// - `bw`: ARQ bandwidth to use /// - `bw_forced`: If false, will potentially negotiate for a /// *lower* bandwidth than `bw` with the remote peer. If /// true, the connection will be made at `bw` rate---or not /// at all. /// - `attempts`: Number of connection attempts to make /// before giving up /// - `clear_time`: Minimum time channel must be clear If zero, /// busy channel detection is disabled. /// - `clear_max_wait`: Maximum time user is willing to wait for /// a clear channel. /// /// # Return /// The outer result contains failures related to the local /// TNC connection. /// /// The inner result contains failures related to the RF /// connection. If the connection attempt succeeds, returns /// information about the connection. If the attempt fails, /// returns the failure reason. pub async fn connect<S>( &mut self, target: S, bw: u16, bw_forced: bool, attempts: u16, clear_time: Duration, clear_max_wait: Duration, ) -> TncResult<Result<ConnectionInfo, ConnectionFailedReason>> where S: Into<String>, { let target_string = target.into(); // wait for clear channel match self.await_clear(clear_time, clear_max_wait).await { Ok(_clear) => { /* no-op*/ } Err(TncError::TimedOut) => return Ok(Err(ConnectionFailedReason::Busy)), Err(e) => return Err(e), } // configure the ARQ mode self.command(command::listen(false)).await?; self.command(command::protocolmode(ProtocolMode::ARQ)) .await?; self.command(command::arqbw(bw, bw_forced)).await?; // dial // // success here merely indicates that a connect request is // in-flight info!( "Connecting to {}: dialing at {} Hz BW...", &target_string, bw ); match self .command(command::arqcall(target_string.clone(), attempts)) .await { Ok(()) => { /* no-op */ } Err(e) => { error!( "Connection to {} failed: TNC rejected request: {}.", &target_string, &e ); return Err(e); } } // wait for success or failure of the connection loop { match self.next_state_change().await? { ConnectionStateChange::Connected(info) => { info!("CONNECTED {}", &info); return Ok(Ok(info)); } ConnectionStateChange::Failed(fail) => { info!("Connection to {} failed: {}", &target_string, &fail); return Ok(Err(fail)); } ConnectionStateChange::Closed => { info!("Connection to {} failed: not connected", &target_string); return Ok(Err(ConnectionFailedReason::NoAnswer)); } _ => { /* ignore */ } } } } /// Listen for incoming connections /// /// When run, this future will wait for the TNC to accept /// an incoming connection to `MYCALL` or one of `MYAUX`. /// When a connection is accepted, the future will resolve /// to a `ConnectionInfo`. /// /// # Parameters /// - `bw`: ARQ bandwidth to use /// - `bw_forced`: If false, will potentially negotiate for a /// *lower* bandwidth than `bw` with the remote peer. If /// true, the connection will be made at `bw` rate---or not /// at all. /// /// # Return /// The outer result contains failures related to the local /// TNC connection. /// /// This method will await forever for an inbound connection /// to complete. Unless the local TNC fails, this method will /// not fail. pub async fn listen(&mut self, bw: u16, bw_forced: bool) -> TncResult<ConnectionInfo> { loop { match self.listen_monitor(bw, bw_forced).await? { ConnectionInfoOrPeerDiscovery::Connection(conn_info) => return Ok(conn_info), _ => continue, } } } /// Passively monitor for peers /// /// When run, the TNC will listen passively for peers which /// announce themselves via: /// /// * ID Frames (`IDF`) /// * Pings /// /// If such an announcement is heard, the future will return /// a DiscoveredPeer. /// /// # Return /// The outer result contains failures related to the local /// TNC connection. /// /// This method will await forever for a peer broadcast. Unless /// the local TNC fails, this method will not fail. pub async fn monitor(&mut self) -> TncResult<DiscoveredPeer> { // disable listening self.command(command::protocolmode(ProtocolMode::ARQ)) .await?; self.command(command::listen(true)).await?; info!("Monitoring for available peers..."); // wait for peer transmission loop { match self.next_state_change().await? { ConnectionStateChange::IdentityFrame(call, grid) => { let peer = DiscoveredPeer::new(call, None, grid); info!("ID frame: {}", peer); return Ok(peer); } ConnectionStateChange::Ping(src, _dst, snr, _quality) => { let peer = DiscoveredPeer::new(src, Some(snr), None); info!("Ping: {}", peer); return Ok(peer); } _ => continue, } } } /// Listen for incoming connections and peer identities /// /// When run, this future will wait for the TNC to accept /// an incoming connection to `MYCALL` or one of `MYAUX`. /// When a connection is accepted, the future will resolve /// to a `ConnectionInfo`. This method will also listen for /// beacons (ID frames) and pings and return information /// about discovered peers. /// /// # Parameters /// - `bw`: ARQ bandwidth to use /// - `bw_forced`: If false, will potentially negotiate for a /// *lower* bandwidth than `bw` with the remote peer. If /// true, the connection will be made at `bw` rate---or not /// at all. /// /// # Return /// The outer result contains failures related to the local /// TNC connection. /// /// This method will await forever for an inbound connection /// to complete or for a peer identity to be received. Unless /// the local TNC fails, this method will not fail. pub async fn listen_monitor( &mut self, bw: u16, bw_forced: bool, ) -> TncResult<ConnectionInfoOrPeerDiscovery> { // configure the ARQ mode and start listening self.command(command::protocolmode(ProtocolMode::ARQ)) .await?; self.command(command::arqbw(bw, bw_forced)).await?; self.command(command::listen(true)).await?; info!("Listening for {} at {} Hz...", self.mycall(), bw); // wait until we connect loop { match self.next_state_change().await? { ConnectionStateChange::Connected(info) => { info!("CONNECTED {}", &info); self.command(command::listen(false)).await?; return Ok(ConnectionInfoOrPeerDiscovery::Connection(info)); } ConnectionStateChange::Failed(fail) => { info!("Incoming connection failed: {}", fail); } ConnectionStateChange::IdentityFrame(call, grid) => { let peer = DiscoveredPeer::new(call, None, grid); info!("ID frame: {}", peer); return Ok(ConnectionInfoOrPeerDiscovery::PeerDiscovery(peer)); } ConnectionStateChange::Ping(src, _dst, snr, _quality) => { let peer = DiscoveredPeer::new(src, Some(snr), None); info!("Ping: {}", peer); return Ok(ConnectionInfoOrPeerDiscovery::PeerDiscovery(peer)); } ConnectionStateChange::Closed => { info!("Incoming connection failed: not connected"); } _ => continue, } } } /// Disconnect any in-progress ARQ connection /// /// When this future has returned, the ARDOP TNC has /// disconnected from any in-progress ARQ session. /// This method is safe to call even when no /// connection is in progress. Any errors which /// result from the disconnection process are ignored. pub async fn disconnect(&mut self) { match self.command(command::disconnect()).await { Ok(()) => { /* no-op */ } Err(_e) => return, }; for _i in 0..2 { match self .next_state_change_timeout(TIMEOUT_DISCONNECT.clone()) .await { Err(_timeout) => { // disconnect timeout; try to abort warn!("Disconnect timed out. Trying to abort."); let _ = self.command(command::abort()).await; continue; } Ok(ConnectionStateChange::Closed) => { break; } _ => { /* no-op */ } } } } /// Perform disconnect by polling /// /// A polling method for disconnecting ARQ sessions. Call /// this method until it returns `Ready` `Ok` to disconnect /// any in-progress ARQ connection. /// /// If a task execution context is available, the async /// method `AsyncTnc::disconnect()` may be a better /// alternative to this method. /// /// # Parameters /// - `cx`: Polling context /// /// # Return /// * `Poll::Pending` if this method is waiting on I/O and /// needs to be re-polled /// * `Poll::Ready(Ok(()))` if any in-progress ARQ connection /// is now disconnected /// * `Poll::Ready(Err(e))` if the connection to the local /// ARDOP TNC has been interrupted. pub fn poll_disconnect(&mut self, cx: &mut Context) -> Poll<io::Result<()>> { match ready!(execute_disconnect( &mut self.disconnect_progress, cx, &mut self.control_out, &mut self.control_in_res, &mut self.data_stream, )) { Ok(()) => Poll::Ready(Ok(())), Err(TncError::IoError(e)) => Poll::Ready(Err(e)), Err(_tnc_err) => Poll::Ready(Err(connection_reset_err())), } } /// Query TNC version /// /// Queries the ARDOP TNC software for its version number. /// The format of the version number is unspecified and may /// be empty. /// /// # Return /// Version string, or an error if the version string could /// not be retrieved. pub async fn version(&mut self) -> TncResult<String> { let cmd = command::version(); let vers = execute_command( &mut self.control_out, &mut self.control_in_res, &self.control_timeout, cmd, ) .await?; match vers.1 { None => Ok("".to_owned()), Some(v) => Ok(v), } } // Initialize the ARDOP TNC async fn initialize(&mut self) -> TncResult<()> { self.data_stream.state_mut().reset(); self.command(command::initialize()).await?; self.command(command::listen(false)).await?; self.command(command::protocolmode(ProtocolMode::FEC)) .await?; self.command(command::mycall(self.mycall().clone())).await?; self.command(command::busyblock(true)).await?; Ok(()) } // wait for a connection state change async fn next_state_change(&mut self) -> TncResult<ConnectionStateChange> { self.next_state_change_timeout(Duration::from_secs(0)).await } // wait for a connection state change (specified timeout, zero for infinite) async fn next_state_change_timeout( &mut self, timeout: Duration, ) -> TncResult<ConnectionStateChange> { loop { let res = if timeout == Duration::from_secs(0) { self.data_stream.next().await } else { self.data_stream.next().timeout(timeout.clone()).await? }; match res { None => return Err(TncError::IoError(connection_reset_err())), Some(DataEvent::Event(event)) => return Ok(event), Some(DataEvent::Data(DataIn::IDF(peer_call, peer_grid))) => { return Ok(ConnectionStateChange::IdentityFrame(peer_call, peer_grid)) } Some(_data) => { /* consume it */ } } } } } impl<I> Unpin for AsyncTnc<I> where I: AsyncRead + AsyncWrite + Unpin + Send {} // Future which executes a command on the TNC // // Sends a command to the TNC and awaits the result. // The caller will wait no longer than `timeout`. async fn execute_command<'d, W, R, F>( outp: &'d mut W, inp: &'d mut R, timeout: &'d Duration, cmd: Command<F>, ) -> TncResult<CommandOk> where W: Sink<String> + Unpin, R: Stream<Item = CommandResult> + Unpin, F: fmt::Display, { let send_raw = cmd.to_string(); debug!("Sending TNC command: {}", &send_raw); // send let _ = outp.send(send_raw).timeout(timeout.clone()).await?; match inp.next().timeout(timeout.clone()).await { // timeout elapsed Err(_timeout) => Err(TncError::IoError(connection_timeout_err())), // lost connection Ok(None) => Err(TncError::IoError(connection_reset_err())), // TNC FAULT means our command has failed Ok(Some(Err(badcmd))) => Err(TncError::CommandFailed(badcmd)), Ok(Some(Ok((in_id, msg)))) => { if in_id == *cmd.command_id() { // success Ok((in_id, msg)) } else { // success, but this isn't the command we are looking for Err(TncError::IoError(command_response_invalid_err())) } } } } #[derive(Debug, Eq, PartialEq, Clone)] enum DisconnectProgress { NoProgress, SentDisconnect, AckDisconnect, } // A polling function which drives the TNC to disconnection // // The AsyncWrite trait requires a polling disconnect. We can't // just run a future and be done with it. Rather than using all // of our fancy async methods, we have to write all the polling // logic to do disconnects "by hand." // // This method will return Pending while a disconnect is waiting // on I/O. When it returns Ready(Ok(())), the disconnect is // finished. fn execute_disconnect<K, S, E, Z>( state: &mut DisconnectProgress, cx: &mut Context<'_>, ctrl_out: &mut K, ctrl_in: &mut S, evt_in: &mut E, ) -> Poll<TncResult<()>> where K: Sink<String, Error = Z> + Unpin, S: Stream<Item = CommandResult> + Unpin, E: Stream<Item = DataEvent> + Unpin, crate::tnc::TncError: std::convert::From<Z>, { loop { match state { DisconnectProgress::NoProgress => { // ready to send command? ready!(Pin::new(&mut *ctrl_out).poll_ready(cx))?; // send it *state = DisconnectProgress::SentDisconnect; Pin::new(&mut *ctrl_out).start_send(format!("{}", command::disconnect()))?; } DisconnectProgress::SentDisconnect => { // try to flush the outgoing command ready!(Pin::new(&mut *ctrl_out).poll_flush(cx))?; // read the next command response match ready!(Pin::new(&mut *ctrl_in).poll_next(cx)) { None => { // I/O error *state = DisconnectProgress::NoProgress; return Poll::Ready(Err(TncError::IoError(connection_reset_err()))); } Some(Err(_e)) => { // probably already disconnected *state = DisconnectProgress::NoProgress; return Poll::Ready(Ok(())); } Some(Ok((CommandID::DISCONNECT, _msg))) => { // Command execution in progress. *state = DisconnectProgress::AckDisconnect; } Some(_ok) => { // not the right command response -- keep looking } } } DisconnectProgress::AckDisconnect => { match ready!(Pin::new(&mut *evt_in).poll_next(cx)) { None => { *state = DisconnectProgress::NoProgress; return Poll::Ready(Err(TncError::IoError(connection_reset_err()))); } Some(DataEvent::Event(ConnectionStateChange::Closed)) => { *state = DisconnectProgress::NoProgress; return Poll::Ready(Ok(())); } Some(_dataevt) => { /* no-op; keep waiting */ } } } } } } fn connection_reset_err() -> io::Error { io::Error::new( io::ErrorKind::ConnectionReset, "Lost connection to ARDOP TNC", ) } fn connection_timeout_err() -> io::Error { io::Error::new( io::ErrorKind::TimedOut, "Lost connection to ARDOP TNC: command timed out", ) } fn command_response_invalid_err() -> io::Error { io::Error::new( io::ErrorKind::InvalidData, "TNC sent an unsolicited or invalid command response", ) } #[cfg(test)] mod test { use super::*; use futures::channel::mpsc; use futures::io::Cursor; use futures::sink; use futures::stream; use futures::task; use crate::protocol::constants::CommandID; #[test] fn test_execute_command_good_response() { async_std::task::block_on(async { let cmd_out = command::listen(true); let res_in: Vec<CommandResult> = vec![Ok((CommandID::LISTEN, None))]; let mut sink_out = sink::drain(); let mut stream_in = stream::iter(res_in.into_iter()); let timeout = Duration::from_secs(10); let res = execute_command(&mut sink_out, &mut stream_in, &timeout, cmd_out).await; match res { Ok((CommandID::LISTEN, None)) => assert!(true), _ => assert!(false), } }) } #[test] fn test_execute_command_bad_response() { async_std::task::block_on(async { let cmd_out = command::listen(true); let res_in: Vec<CommandResult> = vec![Ok((CommandID::VERSION, None))]; let mut sink_out = sink::drain(); let mut stream_in = stream::iter(res_in.into_iter()); let timeout = Duration::from_secs(10); let res = execute_command(&mut sink_out, &mut stream_in, &timeout, cmd_out).await; match res { Err(TncError::IoError(e)) => assert_eq!(io::ErrorKind::InvalidData, e.kind()), _ => assert!(false), } }) } #[test] fn test_execute_command_eof() { async_std::task::block_on(async { let cmd_out = command::listen(true); let res_in: Vec<CommandResult> = vec![]; let mut sink_out = sink::drain(); let mut stream_in = stream::iter(res_in.into_iter()); let timeout = Duration::from_secs(10); let res = execute_command(&mut sink_out, &mut stream_in, &timeout, cmd_out).await; match res { Err(TncError::IoError(e)) => assert_eq!(e.kind(), io::ErrorKind::ConnectionReset), _ => assert!(false), } }) } #[test] fn test_execute_command_timeout() { async_std::task::block_on(async { let cmd_out = command::listen(true); let mut sink_out = sink::drain(); let mut stream_in = stream::once(futures::future::pending()); let timeout = Duration::from_micros(2); let res = execute_command(&mut sink_out, &mut stream_in, &timeout, cmd_out).await; match res { Err(TncError::IoError(e)) => assert_eq!(io::ErrorKind::TimedOut, e.kind()), _ => assert!(false), } }) } #[test] fn test_streams() { async_std::task::block_on(async { let stream_ctrl = Cursor::new(b"BUSY FALSE\rINPUTPEAKS BLAH\rREJECTEDBW\r".to_vec()); let stream_data = Cursor::new(b"\x00\x08ARQHELLO\x00\x0BIDFID: W1AW".to_vec()); let mut tnc = AsyncTnc::new_from_streams(stream_ctrl, stream_data, "W1AW"); futures::executor::block_on(async { match tnc.data_stream_sink().next().await { Some(DataEvent::Data(_d)) => assert!(true), _ => assert!(false), } match tnc.data_stream_sink().next().await { Some(DataEvent::Data(DataIn::IDF(_i0, _i1))) => assert!(true), _ => assert!(false), } match tnc.data_stream_sink().next().await { Some(DataEvent::Event(ConnectionStateChange::Busy(false))) => assert!(true), _ => assert!(false), } match tnc.data_stream_sink().next().await { Some(DataEvent::Event(ConnectionStateChange::Failed( ConnectionFailedReason::IncompatibleBandwidth, ))) => assert!(true), _ => assert!(false), } assert!(tnc.data_stream_sink().next().await.is_none()); }); }) } #[test] fn test_execute_disconnect() { async_std::task::block_on(async { let mut cx = Context::from_waker(task::noop_waker_ref()); let (mut ctrl_out_snd, mut ctrl_out_rx) = mpsc::unbounded(); let (ctrl_in_snd, mut ctrl_in_rx) = mpsc::unbounded(); let (evt_in_snd, mut evt_in_rx) = mpsc::unbounded(); // starts disconnection, but no connection in progress let mut state = DisconnectProgress::NoProgress; ctrl_in_snd .unbounded_send(Err("not from state".to_owned())) .unwrap(); match execute_disconnect( &mut state, &mut cx, &mut ctrl_out_snd, &mut ctrl_in_rx, &mut evt_in_rx, ) { Poll::Ready(Ok(())) => assert!(true), _ => assert!(false), } assert_eq!(DisconnectProgress::NoProgress, state); // starts disconnection state = DisconnectProgress::NoProgress; match execute_disconnect( &mut state, &mut cx, &mut ctrl_out_snd, &mut ctrl_in_rx, &mut evt_in_rx, ) { Poll::Pending => assert!(true), _ => assert!(false), } assert_eq!(DisconnectProgress::SentDisconnect, state); let _ = ctrl_out_rx.try_next().unwrap(); // make progress towards disconnection ctrl_in_snd .unbounded_send(Ok((CommandID::DISCONNECT, None))) .unwrap(); match execute_disconnect( &mut state, &mut cx, &mut ctrl_out_snd, &mut ctrl_in_rx, &mut evt_in_rx, ) { Poll::Pending => assert!(true), _ => assert!(false), } assert_eq!(DisconnectProgress::AckDisconnect, state); // finish disconnect evt_in_snd .unbounded_send(DataEvent::Event(ConnectionStateChange::SendBuffer(0))) .unwrap(); evt_in_snd .unbounded_send(DataEvent::Event(ConnectionStateChange::Closed)) .unwrap(); match execute_disconnect( &mut state, &mut cx, &mut ctrl_out_snd, &mut ctrl_in_rx, &mut evt_in_rx, ) { Poll::Ready(Ok(())) => assert!(true), _ => assert!(false), } assert_eq!(DisconnectProgress::NoProgress, state); }) } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![warn(missing_docs)] use failure::{bail, format_err, Error, ResultExt}; use fidl::endpoints::{create_proxy, ServerEnd}; use fidl_fuchsia_io::{DirectoryProxy, FileMarker, NodeMarker}; use fidl_fuchsia_sys::{FlatNamespace, RunnerRequest, RunnerRequestStream}; use fuchsia_async as fasync; use fuchsia_component::server::ServiceFs; use fuchsia_syslog::fx_log_info; use fuchsia_url::pkg_url::PkgUrl; use fuchsia_zircon as zx; use futures::prelude::*; use std::mem; fn manifest_path_from_url(url: &str) -> Result<String, Error> { match PkgUrl::parse(url) { Ok(url) => match url.resource() { Some(r) => Ok(r.to_string()), None => bail!("no resource"), }, Err(e) => Err(e), } .map_err(|e| format_err!("parse error {}", e)) } fn extract_directory_with_name(ns: &mut FlatNamespace, name: &str) -> Result<zx::Channel, Error> { let handle_ref = ns .paths .iter() .zip(ns.directories.iter_mut()) .find(|(n, _)| n.as_str() == name) .ok_or_else(|| format_err!("could not find entry matching {}", name)) .map(|x| x.1)?; Ok(mem::replace(handle_ref, zx::Channel::from(zx::Handle::invalid()))) } async fn file_contents_at_path(dir: zx::Channel, path: &str) -> Result<Vec<u8>, Error> { let dir_proxy = DirectoryProxy::new(fasync::Channel::from_channel(dir)?); let (file, server) = create_proxy::<FileMarker>()?; dir_proxy.open(0, 0, path, ServerEnd::<NodeMarker>::new(server.into_channel()))?; let attr = file.get_attr().await?.1; let (_, vec) = file.read(attr.content_size).await?; Ok(vec) } #[derive(Default)] #[allow(unused)] struct TestFacet { component_under_test: String, injected_services: Vec<String>, system_services: Vec<String>, } // TODO(jamesr): Use serde to validate and deserialize the facet directly. // See //garnet/bin/cmc/src/validate.rs for reference. fn test_facet(meta: &serde_json::Value) -> Result<TestFacet, Error> { let facets = meta.get("facets").ok_or_else(|| format_err!("no facets"))?; if !facets.is_object() { bail!("facet not an object"); } let fuchsia_test_facet = match facets.get("fuchsia.test") { Some(v) => v, None => bail!("no fuchsia.test facet"), }; if !fuchsia_test_facet.is_object() { bail!("fuchsia.test facet not an object"); } let component_under_test = match fuchsia_test_facet.get("component_under_test") { Some(v) => v, None => bail!("no component_under_test definition in fuchsia.test facet"), }; let component_under_test = component_under_test .as_str() .ok_or_else(|| format_err!("component_under_test in fuchsia.test facet not a string"))? .to_string(); Ok(TestFacet { component_under_test: component_under_test, injected_services: Vec::new(), system_services: Vec::new(), }) } async fn run_runner_server(mut stream: RunnerRequestStream) -> Result<(), Error> { while let Some(RunnerRequest::StartComponent { package, mut startup_info, controller: _, control_handle, }) = stream.try_next().await.context("error running server")? { fx_log_info!("Received runner request for component {}", package.resolved_url); let manifest_path = manifest_path_from_url(&package.resolved_url)?; fx_log_info!("Component manifest path {}", manifest_path); let pkg_directory_channel = extract_directory_with_name(&mut startup_info.flat_namespace, "/pkg")?; fx_log_info!("Found package directory handle"); let meta_contents = file_contents_at_path(pkg_directory_channel, &manifest_path).await?; fx_log_info!("Meta contents: {:#?}", std::str::from_utf8(&meta_contents)?); let meta = serde_json::from_slice::<serde_json::Value>(&meta_contents)?; fx_log_info!("Found metadata: {:#?}", meta); let _f = test_facet(&meta)?; //TODO(jamesr): Configure realm based on |f| then instantiate and watch //|f.component_under_test| within that realm. control_handle.shutdown(); } Ok(()) } enum IncomingServices { Runner(RunnerRequestStream), // ... more services here } #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { fuchsia_syslog::init_with_tags(&["component_test_runner"])?; let mut fs = ServiceFs::new_local(); fs.dir("svc").add_fidl_service(IncomingServices::Runner); fs.take_and_serve_directory_handle()?; const MAX_CONCURRENT: usize = 10_000; let fut = fs.for_each_concurrent(MAX_CONCURRENT, |IncomingServices::Runner(stream)| { run_runner_server(stream).unwrap_or_else(|e| println!("{:?}", e)) }); fut.await; Ok(()) } #[cfg(test)] mod tests { use super::*; use fuchsia_zircon::HandleBased; use serde_json::json; /// Makes a manifest_path_from_url test /// Arguments: /// name: name of the test case /// url: url to parse /// path: expected path component /// err: true if an error is expected macro_rules! manifest_path_from_url_test { ( $name:ident, $url:literal, $path:literal, $err:literal ) => { #[test] fn $name() { match manifest_path_from_url($url) { Ok(path) => { assert!(!$err); assert_eq!(path, $path) } Err(_) => assert!($err), } } }; } manifest_path_from_url_test!(empty_string, "", "", true); manifest_path_from_url_test!(no_hash, "fuchsia-pkg://foo/abcdef", "", true); manifest_path_from_url_test!(one_hash, "fuchsia-pkg://foo/abc#def", "def", false); manifest_path_from_url_test!(multiple_hash, "fuchsia-pkg://foo/abc#def#ghi", "def#ghi", false); manifest_path_from_url_test!(last_position_hash, "fuchsia-pkg://foo/abc#", "", true); #[test] fn directory_with_name_tests() -> Result<(), Error> { let (a_ch_0, _) = zx::Channel::create()?; let (b_ch_0, _) = zx::Channel::create()?; let mut ns = FlatNamespace { paths: vec![String::from("/a"), String::from("/b")], directories: vec![a_ch_0, b_ch_0], }; assert!(extract_directory_with_name(&mut ns, "/c/").is_err()); assert!(extract_directory_with_name(&mut ns, "/b").is_ok()); assert!(ns.directories[1].is_invalid_handle()); Ok(()) } #[test] fn test_facet_missing_facet() -> Result<(), Error> { let meta = json!({}); let f = test_facet(&meta); assert!(f.is_err()); Ok(()) } #[test] fn test_facet_missing_fuchsia_test_facet() -> Result<(), Error> { let meta = json!({ "facets": [] }); let f = test_facet(&meta); assert!(f.is_err()); Ok(()) } #[test] fn test_facet_facets_wrong_type() -> Result<(), Error> { let meta = json!({ "facets": [] }); let f = test_facet(&meta); assert!(f.is_err()); Ok(()) } #[test] fn test_facet_fuchsia_test_facet_wrong_type() -> Result<(), Error> { let meta = json!({ "facets": { "fuchsia.test": [] } }); let f = test_facet(&meta); assert!(f.is_err()); Ok(()) } #[test] fn test_facet_component_under_test() -> Result<(), Error> { let meta = json!({ "facets": { "fuchsia.test": { "component_under_test": "fuchsia-pkg://fuchsia.com/test#meta/test.cmx" } } }); let f = test_facet(&meta); assert!(!f.is_err()); assert_eq!(f?.component_under_test, "fuchsia-pkg://fuchsia.com/test#meta/test.cmx"); Ok(()) } #[test] fn test_facet_component_under_test_not_string() -> Result<(), Error> { let meta = json!({ "facets": { "fuchsia.test": { "component_under_test": 42 } } }); let f = test_facet(&meta); assert!(f.is_err()); Ok(()) } }
#![allow(nonstandard_style)] use libc::{c_int, c_void, uintptr_t}; #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq)] pub enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_FOREIGN_EXCEPTION_CAUGHT = 1, _URC_FATAL_PHASE2_ERROR = 2, _URC_FATAL_PHASE1_ERROR = 3, _URC_NORMAL_STOP = 4, _URC_END_OF_STACK = 5, _URC_HANDLER_FOUND = 6, _URC_INSTALL_CONTEXT = 7, _URC_CONTINUE_UNWIND = 8, _URC_FAILURE = 9, // used only by ARM EHABI } pub use _Unwind_Reason_Code::*; pub type _Unwind_Exception_Class = u64; pub type _Unwind_Word = uintptr_t; pub type _Unwind_Ptr = uintptr_t; pub type _Unwind_Trace_Fn = extern "C" fn(ctx: *mut _Unwind_Context, arg: *mut c_void) -> _Unwind_Reason_Code; #[cfg(target_arch = "x86")] pub const unwinder_private_data_size: usize = 5; #[cfg(target_arch = "x86_64")] pub const unwinder_private_data_size: usize = 6; #[cfg(all(target_arch = "arm", not(target_os = "ios")))] pub const unwinder_private_data_size: usize = 20; #[cfg(all(target_arch = "arm", target_os = "ios"))] pub const unwinder_private_data_size: usize = 5; #[cfg(target_arch = "aarch64")] pub const unwinder_private_data_size: usize = 2; #[cfg(target_arch = "mips")] pub const unwinder_private_data_size: usize = 2; #[cfg(target_arch = "mips64")] pub const unwinder_private_data_size: usize = 2; #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))] pub const unwinder_private_data_size: usize = 2; #[cfg(target_arch = "s390x")] pub const unwinder_private_data_size: usize = 2; #[cfg(target_arch = "sparc64")] pub const unwinder_private_data_size: usize = 2; #[cfg(target_arch = "riscv64")] pub const unwinder_private_data_size: usize = 2; #[cfg(target_os = "emscripten")] pub const unwinder_private_data_size: usize = 20; #[cfg(all(target_arch = "hexagon", target_os = "linux"))] pub const unwinder_private_data_size: usize = 35; #[repr(C)] pub struct _Unwind_Exception { pub exception_class: _Unwind_Exception_Class, pub exception_cleanup: _Unwind_Exception_Cleanup_Fn, pub private: [_Unwind_Word; unwinder_private_data_size], } impl _Unwind_Exception { cfg_if::cfg_if! { if #[cfg(all(target_arch = "arm", not(target_os = "ios"), not(target_os = "netbsd")))] { pub fn is_forced(&self) -> bool { // _Unwind_RaiseException on EHABI will always set the reserved1 field to 0, // which is in the same position as private_1 below. false } } else { pub fn is_forced(&self) -> bool { self.private[0] != 0 } } } } pub enum _Unwind_Context {} pub type _Unwind_Exception_Cleanup_Fn = extern "C" fn(unwind_code: _Unwind_Reason_Code, exception: *mut _Unwind_Exception); #[cfg_attr( all( feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux") ), link(name = "unwind", kind = "static") )] extern "C-unwind" { pub fn _Unwind_Resume(exception: *mut _Unwind_Exception) -> !; pub fn _Unwind_DeleteException(exception: *mut _Unwind_Exception); pub fn _Unwind_GetLanguageSpecificData(ctx: *mut _Unwind_Context) -> *mut c_void; pub fn _Unwind_GetRegionStart(ctx: *mut _Unwind_Context) -> _Unwind_Ptr; pub fn _Unwind_GetTextRelBase(ctx: *mut _Unwind_Context) -> _Unwind_Ptr; pub fn _Unwind_GetDataRelBase(ctx: *mut _Unwind_Context) -> _Unwind_Ptr; } cfg_if::cfg_if! { if #[cfg(all(any(target_os = "ios", target_os = "netbsd", not(target_arch = "arm"))))] { // Not ARM EHABI #[repr(C)] #[derive(Copy, Clone, PartialEq)] pub enum _Unwind_Action { _UA_SEARCH_PHASE = 1, _UA_CLEANUP_PHASE = 2, _UA_HANDLER_FRAME = 4, _UA_FORCE_UNWIND = 8, _UA_END_OF_STACK = 16, } pub use _Unwind_Action::*; #[cfg_attr(all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux")), link(name = "unwind", kind = "static"))] extern "C" { pub fn _Unwind_GetGR(ctx: *mut _Unwind_Context, reg_index: c_int) -> _Unwind_Word; pub fn _Unwind_SetGR(ctx: *mut _Unwind_Context, reg_index: c_int, value: _Unwind_Word); pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> _Unwind_Word; pub fn _Unwind_SetIP(ctx: *mut _Unwind_Context, value: _Unwind_Word); pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, ip_before_insn: *mut c_int) -> _Unwind_Word; pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void; } } else { // ARM EHABI #[repr(C)] #[derive(Copy, Clone, PartialEq)] pub enum _Unwind_State { _US_VIRTUAL_UNWIND_FRAME = 0, _US_UNWIND_FRAME_STARTING = 1, _US_UNWIND_FRAME_RESUME = 2, _US_ACTION_MASK = 3, _US_FORCE_UNWIND = 8, _US_END_OF_STACK = 16, } pub use _Unwind_State::*; #[repr(C)] enum _Unwind_VRS_Result { _UVRSR_OK = 0, _UVRSR_NOT_IMPLEMENTED = 1, _UVRSR_FAILED = 2, } #[repr(C)] enum _Unwind_VRS_RegClass { _UVRSC_CORE = 0, _UVRSC_VFP = 1, _UVRSC_FPA = 2, _UVRSC_WMMXD = 3, _UVRSC_WMMXC = 4, } use _Unwind_VRS_RegClass::*; #[repr(C)] enum _Unwind_VRS_DataRepresentation { _UVRSD_UINT32 = 0, _UVRSD_VFPX = 1, _UVRSD_FPAX = 2, _UVRSD_UINT64 = 3, _UVRSD_FLOAT = 4, _UVRSD_DOUBLE = 5, } use _Unwind_VRS_DataRepresentation::*; pub const UNWIND_POINTER_REG: c_int = 12; pub const UNWIND_SP_REG: c_int = 13; pub const UNWIND_IP_REG: c_int = 15; #[cfg_attr(all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux")), link(name = "unwind", kind = "static"))] extern "C" { fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context, regclass: _Unwind_VRS_RegClass, regno: _Unwind_Word, repr: _Unwind_VRS_DataRepresentation, data: *mut c_void) -> _Unwind_VRS_Result; fn _Unwind_VRS_Set(ctx: *mut _Unwind_Context, regclass: _Unwind_VRS_RegClass, regno: _Unwind_Word, repr: _Unwind_VRS_DataRepresentation, data: *mut c_void) -> _Unwind_VRS_Result; } // On Android or ARM/Linux, these are implemented as macros: pub unsafe fn _Unwind_GetGR(ctx: *mut _Unwind_Context, reg_index: c_int) -> _Unwind_Word { let mut val: _Unwind_Word = 0; _Unwind_VRS_Get(ctx, _UVRSC_CORE, reg_index as _Unwind_Word, _UVRSD_UINT32, &mut val as *mut _ as *mut c_void); val } pub unsafe fn _Unwind_SetGR(ctx: *mut _Unwind_Context, reg_index: c_int, value: _Unwind_Word) { let mut value = value; _Unwind_VRS_Set(ctx, _UVRSC_CORE, reg_index as _Unwind_Word, _UVRSD_UINT32, &mut value as *mut _ as *mut c_void); } pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> _Unwind_Word { let val = _Unwind_GetGR(ctx, UNWIND_IP_REG); (val & !1) as _Unwind_Word } pub unsafe fn _Unwind_SetIP(ctx: *mut _Unwind_Context, value: _Unwind_Word) { // Propagate thumb bit to instruction pointer let thumb_state = _Unwind_GetGR(ctx, UNWIND_IP_REG) & 1; let value = value | thumb_state; _Unwind_SetGR(ctx, UNWIND_IP_REG, value); } pub unsafe fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, ip_before_insn: *mut c_int) -> _Unwind_Word { *ip_before_insn = 0; _Unwind_GetIP(ctx) } // This function also doesn't exist on Android or ARM/Linux, so make it a no-op pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void { pc } } } // cfg_if! cfg_if::cfg_if! { if #[cfg(not(all(target_os = "ios", target_arch = "arm")))] { // Not 32-bit iOS #[cfg_attr(all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux")), link(name = "unwind", kind = "static"))] extern "C-unwind" { pub fn _Unwind_RaiseException(exception: *mut _Unwind_Exception) -> _Unwind_Reason_Code; pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn, trace_argument: *mut c_void) -> _Unwind_Reason_Code; } } else { // 32-bit iOS uses SjLj and does not provide _Unwind_Backtrace() #[cfg_attr(all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux")), link(name = "unwind", kind = "static"))] extern "C-unwind" { pub fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception) -> _Unwind_Reason_Code; } #[inline] pub unsafe fn _Unwind_RaiseException(exc: *mut _Unwind_Exception) -> _Unwind_Reason_Code { _Unwind_SjLj_RaiseException(exc) } } } // cfg_if! cfg_if::cfg_if! { if #[cfg(all(windows, target_arch = "x86_64", target_env = "gnu"))] { // We declare these as opaque types. This is fine since you just need to // pass them to _GCC_specific_handler and forget about them. pub enum EXCEPTION_RECORD {} pub type LPVOID = *mut c_void; pub enum CONTEXT {} pub enum DISPATCHER_CONTEXT {} pub type EXCEPTION_DISPOSITION = c_int; type PersonalityFn = unsafe extern "C" fn(version: c_int, actions: _Unwind_Action, exception_class: _Unwind_Exception_Class, exception_object: *mut _Unwind_Exception, context: *mut _Unwind_Context) -> _Unwind_Reason_Code; extern "C" { pub fn _GCC_specific_handler(exceptionRecord: *mut EXCEPTION_RECORD, establisherFrame: LPVOID, contextRecord: *mut CONTEXT, dispatcherContext: *mut DISPATCHER_CONTEXT, personality: PersonalityFn) -> EXCEPTION_DISPOSITION; } } } // cfg_if!
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type CastingConnection = *mut ::core::ffi::c_void; pub type CastingConnectionErrorOccurredEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct CastingConnectionErrorStatus(pub i32); impl CastingConnectionErrorStatus { pub const Succeeded: Self = Self(0i32); pub const DeviceDidNotRespond: Self = Self(1i32); pub const DeviceError: Self = Self(2i32); pub const DeviceLocked: Self = Self(3i32); pub const ProtectedPlaybackFailed: Self = Self(4i32); pub const InvalidCastingSource: Self = Self(5i32); pub const Unknown: Self = Self(6i32); } impl ::core::marker::Copy for CastingConnectionErrorStatus {} impl ::core::clone::Clone for CastingConnectionErrorStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct CastingConnectionState(pub i32); impl CastingConnectionState { pub const Disconnected: Self = Self(0i32); pub const Connected: Self = Self(1i32); pub const Rendering: Self = Self(2i32); pub const Disconnecting: Self = Self(3i32); pub const Connecting: Self = Self(4i32); } impl ::core::marker::Copy for CastingConnectionState {} impl ::core::clone::Clone for CastingConnectionState { fn clone(&self) -> Self { *self } } pub type CastingDevice = *mut ::core::ffi::c_void; pub type CastingDevicePicker = *mut ::core::ffi::c_void; pub type CastingDevicePickerFilter = *mut ::core::ffi::c_void; pub type CastingDeviceSelectedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct CastingPlaybackTypes(pub u32); impl CastingPlaybackTypes { pub const None: Self = Self(0u32); pub const Audio: Self = Self(1u32); pub const Video: Self = Self(2u32); pub const Picture: Self = Self(4u32); } impl ::core::marker::Copy for CastingPlaybackTypes {} impl ::core::clone::Clone for CastingPlaybackTypes { fn clone(&self) -> Self { *self } } pub type CastingSource = *mut ::core::ffi::c_void;
pub mod fields; pub mod subfield; use std::{fmt, str}; use self::subfield::{subfields::Subfields, Subfield}; use crate::{errors::*, Identifier, Indicator, Tag, MAX_FIELD_LEN, SUBFIELD_DELIMITER}; /// View into a field of a MARC record #[derive(Eq, PartialEq, Clone, Debug)] pub struct Field<'a> { tag: Tag, data: &'a [u8], } impl<'a> Field<'a> { #[doc(hidden)] pub fn new(tag: Tag, data: &[u8]) -> Field<'_> { Field { tag, data } } /// Will find all subfields with identifier `ident`. pub fn subfield<Ident: Into<Identifier>>(&self, ident: Ident) -> Vec<Subfield<'_>> { Subfield::find(self, ident) } /// Will return iterator over subfields of the field. pub fn subfields(&self) -> Subfields<'a> { Subfields::new(self.clone()) } /// Will return view into a `FieldRepr`. pub fn from_repr(repr: &'a FieldRepr) -> Field<'a> { Field { tag: repr.tag, data: &repr.data, } } /// Returns tag of the field. pub fn get_tag(&self) -> Tag { self.tag } /// Returns a field indicator. /// /// Makes sence only for variable data fields. /// /// # Panic /// /// Will panic if `self.data.len() < 2`. pub fn get_indicator(&self) -> Indicator { let first_two_bytes = self.data.get(..2).expect("field contains no indicator"); Indicator::from_slice(first_two_bytes) } /// Returns data of the field. /// /// Data will not include field terminator. pub fn get_data<O: FromFieldData + ?Sized>(&self) -> &O { FromFieldData::from_data(self.data) } } impl fmt::Display for Field<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let tag = self.get_tag(); let field_data = match tag.0 { [b'0', b'0', ..] => { // variable control field self.get_data::<str>().replace(' ', "\\") } _ => { // variable data field String::from_utf8_lossy( &self .get_data::<[u8]>() .iter() .map(|b| if *b == SUBFIELD_DELIMITER { 36 } else { *b }) .collect::<Vec<u8>>(), ) .to_string() } }; write!(f, "{} {}", tag, field_data) } } /// MARC field representation #[derive(Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct FieldRepr { tag: Tag, data: Vec<u8>, } impl FieldRepr { /// Will return new `FieldRepr` with specified subfield included. /// /// ### Errors /// Will return Error if resuling field length (with field terminator) is greater than /// 9.999 bytes. pub fn add_subfield<Ident, D>(&self, identifier: Ident, f_data: D) -> Result<FieldRepr> where Ident: Into<Identifier>, D: AsRef<[u8]>, { let mut new_data = self.data.clone(); new_data.push(SUBFIELD_DELIMITER); new_data.push(identifier.into().into()); new_data.extend_from_slice(f_data.as_ref()); if new_data.len() + 1 > MAX_FIELD_LEN { return Err(Error::FieldTooLarge(self.tag)); } Ok(FieldRepr { tag: self.tag, data: new_data, }) } /// Will return new `FieldRepr` filtered by `fun`. /// /// Subfield will be removed if `fun` returns `false` on it. pub fn filter_subfields<F>(&self, mut fun: F) -> FieldRepr where F: FnMut(&subfield::Subfield<'_>) -> bool, { if let Some(&SUBFIELD_DELIMITER) = self.data.get(2) { let mut new_data = vec![]; new_data.extend_from_slice(&self.data[0..2]); let f = Field::from_repr(self); let sfs = f .subfields() .filter(|sf| fun(sf)) .collect::<Vec<subfield::Subfield<'_>>>(); for sf in sfs { new_data.push(SUBFIELD_DELIMITER); new_data.push(sf.get_identifier().0); new_data.extend_from_slice(sf.get_data()); } FieldRepr { tag: self.tag, data: new_data, } } else { self.clone() } } /// Returns tag of a field. pub fn get_tag(&self) -> Tag { self.tag } /// Returns data of a field (no field terminator). pub fn get_data(&self) -> &[u8] { &self.data } } impl fmt::Debug for FieldRepr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } impl fmt::Display for FieldRepr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Field({} Data({}))", self.tag, str::from_utf8(&self.data).unwrap() ) } } impl<T, Ind, Ident, D> From<(T, Ind, Vec<(Ident, D)>)> for FieldRepr where T: Into<Tag>, Ind: Into<Indicator>, Ident: Into<Identifier>, D: Into<Vec<u8>>, { fn from((tag, indicator, subfields): (T, Ind, Vec<(Ident, D)>)) -> FieldRepr { let mut repr = FieldRepr::from((tag, indicator.into().as_ref())); for (identifier, data) in subfields { repr = repr.add_subfield(identifier, data.into()).unwrap(); } repr } } impl<T: Into<Tag>, D: Into<Vec<u8>>> From<(T, D)> for FieldRepr { fn from((tag, data): (T, D)) -> FieldRepr { FieldRepr { tag: tag.into(), data: data.into(), } } } impl<'a> From<Field<'a>> for FieldRepr { fn from(f: Field<'a>) -> FieldRepr { FieldRepr::from((f.get_tag(), f.get_data::<[u8]>().to_vec())) } } pub trait FromFieldData { fn from_data(data: &[u8]) -> &Self; } impl FromFieldData for [u8] { fn from_data(data: &[u8]) -> &[u8] { data } } impl FromFieldData for str { fn from_data(data: &[u8]) -> &str { str::from_utf8(data).unwrap() } } #[cfg(test)] mod test { use crate::field::FieldRepr; #[test] fn should_filter_subfields() { let repr: FieldRepr = FieldRepr::from((b"979", " \x1fbautoreg\x1fbautoreh")); let f1 = repr.filter_subfields(|_| false); let mut i = 0; let f2 = repr.filter_subfields(|_| { i += 1; i == 1 }); let f3 = repr.filter_subfields(|_| true); assert_eq!(f1, FieldRepr::from((b"979", " "))); assert_eq!(f2, FieldRepr::from((b"979", " \x1fbautoreg"))); assert_eq!(f3, FieldRepr::from((b"979", " \x1fbautoreg\x1fbautoreh"))); } #[test] fn should_add_subfield() { let repr: FieldRepr = FieldRepr::from((b"979", " \x1fbautoreg")); let repr2 = repr.add_subfield(b'b', "autoreh").unwrap(); assert_eq!( repr2, FieldRepr::from((b"979", " \x1fbautoreg\x1fbautoreh")) ); } #[test] #[should_panic] fn should_panic_if_field_is_too_large() { let repr: FieldRepr = FieldRepr::from((b"979", " ")); repr.add_subfield(b'a', vec![b'x'; 9995]).unwrap(); } }
/// A type that can be treated as a pixel. /// /// Types implementing `Pixel` are able to be used /// as a pixel in [`source`](crate::source)s and [`surface`](crate::surface)s. pub trait Pixel: Sized { /// Blend two pixels at a specified opacity /// The `self` pixel should be under the `other` pixel. /// In other words, `other` overlaps `self`, whatever that means for the type of pixel you /// implement. fn blend(&self, other: &Self) -> Self; }
extern crate rustc_serialize as serialize; use serialize::base64::{self, ToBase64}; use serialize::hex::FromHex; fn main() { let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let result = input.from_hex().unwrap().to_base64(base64::STANDARD); println!("{}", result); }
pub(crate) mod shader;
use hyper::{Body, Method, Request, StatusCode}; use hyper::Client; use hyper_tls::HttpsConnector; use isahc::prelude::*; use isahc::prelude::Request as SyncRequest; #[derive(Clone)] pub struct LocalHttpClient { target_uri: String, local_uri: String } impl LocalHttpClient { pub fn new(target_uri: String, local_uri: String) -> LocalHttpClient { LocalHttpClient{ target_uri: target_uri, local_uri: local_uri, } } /** * TODO: Ho god so much wrong stuff here but it works so... * Request use isahc client instead of the hyper one because I can't figure out how to async this properly * (See https://github.com/snapview/tokio-tungstenite/issues/98) */ pub fn on_connect(&self, id: String, auth_header: String) -> bool { let uri = format!("{}/websocket/{}", self.target_uri, id); let body = format!("{{\"code\": \"NEW_CONNECTION\",\"url\":\"{}/{}\"}}", self.local_uri, id); let response = SyncRequest::post(uri) .header("content-type", "application/json") .header("Authorization", auth_header) .body(body).unwrap() .send().unwrap(); match response.status() { StatusCode::OK => true, _ => false, } } pub async fn on_message(self, id: String, msg: String) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let https = HttpsConnector::new(); let client = Client::builder().build::<_, hyper::Body>(https); let req = Request::builder() .method(Method::PUT) .uri(format!("{}/{}", self.target_uri, id)) .header("Content-Type", "application/json") .body(Body::from(msg)) .unwrap(); let resp = client.request(req).await?; println!("{}", resp.status()); Ok(()) } pub async fn on_disconnect(self, id: String) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let https = HttpsConnector::new(); let client = Client::builder().build::<_, hyper::Body>(https); let req = Request::builder() .method(Method::DELETE) .uri(format!("{}/{}", self.target_uri, id)) .body(Body::from("")) .unwrap(); let resp = client.request(req).await?; println!("{}", resp.status()); Ok(()) } }
use std::{io, fmt}; use super::{ Serialize, Deserialize, Error, Uint8, VarUint32, CountedList, BlockType, Uint32, Uint64, CountedListWriter, VarInt32, VarInt64, }; /// Collection of opcodes (usually inside a block section). #[derive(Debug, PartialEq, Clone)] pub struct Opcodes(Vec<Opcode>); impl Opcodes { /// New list of opcodes from vector of opcodes. pub fn new(elements: Vec<Opcode>) -> Self { Opcodes(elements) } /// Empty expression with only `Opcode::End` opcode. pub fn empty() -> Self { Opcodes(vec![Opcode::End]) } /// List of individual opcodes. pub fn elements(&self) -> &[Opcode] { &self.0 } /// Individual opcodes, mutable. pub fn elements_mut(&mut self) -> &mut Vec<Opcode> { &mut self.0 } } impl Deserialize for Opcodes { type Error = Error; fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> { let mut opcodes = Vec::new(); let mut block_count = 1usize; loop { let opcode = Opcode::deserialize(reader)?; if opcode.is_terminal() { block_count -= 1; } else if opcode.is_block() { block_count = block_count.checked_add(1).ok_or(Error::Other("too many opcodes"))?; } opcodes.push(opcode); if block_count == 0 { break; } } Ok(Opcodes(opcodes)) } } /// Initialization expression. #[derive(Debug, Clone)] pub struct InitExpr(Vec<Opcode>); impl InitExpr { /// New initialization expression from list of opcodes. /// `code` must end with the `Opcode::End` opcode! pub fn new(code: Vec<Opcode>) -> Self { InitExpr(code) } /// Empty expression with only `Opcode::End` opcode pub fn empty() -> Self { InitExpr(vec![Opcode::End]) } /// List of opcodes used in the expression. pub fn code(&self) -> &[Opcode] { &self.0 } /// List of opcodes used in the expression. pub fn code_mut(&mut self) -> &mut Vec<Opcode> { &mut self.0 } } // todo: check if kind of opcode sequence is valid as an expression impl Deserialize for InitExpr { type Error = Error; fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> { let mut opcodes = Vec::new(); loop { let opcode = Opcode::deserialize(reader)?; let is_terminal = opcode.is_terminal(); opcodes.push(opcode); if is_terminal { break; } } Ok(InitExpr(opcodes)) } } /// Opcode #[derive(Clone, Debug, PartialEq)] #[allow(missing_docs)] pub enum Opcode { Unreachable, Nop, Block(BlockType), Loop(BlockType), If(BlockType), Else, End, Br(u32), BrIf(u32), BrTable(Box<[u32]>, u32), Return, Call(u32), CallIndirect(u32, u8), Drop, Select, GetLocal(u32), SetLocal(u32), TeeLocal(u32), GetGlobal(u32), SetGlobal(u32), // All store/load opcodes operate with 'memory immediates' // which represented here as (flag, offset) tuple I32Load(u32, u32), I64Load(u32, u32), F32Load(u32, u32), F64Load(u32, u32), I32Load8S(u32, u32), I32Load8U(u32, u32), I32Load16S(u32, u32), I32Load16U(u32, u32), I64Load8S(u32, u32), I64Load8U(u32, u32), I64Load16S(u32, u32), I64Load16U(u32, u32), I64Load32S(u32, u32), I64Load32U(u32, u32), I32Store(u32, u32), I64Store(u32, u32), F32Store(u32, u32), F64Store(u32, u32), I32Store8(u32, u32), I32Store16(u32, u32), I64Store8(u32, u32), I64Store16(u32, u32), I64Store32(u32, u32), CurrentMemory(u8), GrowMemory(u8), I32Const(i32), I64Const(i64), F32Const(u32), F64Const(u64), I32Eqz, I32Eq, I32Ne, I32LtS, I32LtU, I32GtS, I32GtU, I32LeS, I32LeU, I32GeS, I32GeU, I64Eqz, I64Eq, I64Ne, I64LtS, I64LtU, I64GtS, I64GtU, I64LeS, I64LeU, I64GeS, I64GeU, F32Eq, F32Ne, F32Lt, F32Gt, F32Le, F32Ge, F64Eq, F64Ne, F64Lt, F64Gt, F64Le, F64Ge, I32Clz, I32Ctz, I32Popcnt, I32Add, I32Sub, I32Mul, I32DivS, I32DivU, I32RemS, I32RemU, I32And, I32Or, I32Xor, I32Shl, I32ShrS, I32ShrU, I32Rotl, I32Rotr, I64Clz, I64Ctz, I64Popcnt, I64Add, I64Sub, I64Mul, I64DivS, I64DivU, I64RemS, I64RemU, I64And, I64Or, I64Xor, I64Shl, I64ShrS, I64ShrU, I64Rotl, I64Rotr, F32Abs, F32Neg, F32Ceil, F32Floor, F32Trunc, F32Nearest, F32Sqrt, F32Add, F32Sub, F32Mul, F32Div, F32Min, F32Max, F32Copysign, F64Abs, F64Neg, F64Ceil, F64Floor, F64Trunc, F64Nearest, F64Sqrt, F64Add, F64Sub, F64Mul, F64Div, F64Min, F64Max, F64Copysign, I32WrapI64, I32TruncSF32, I32TruncUF32, I32TruncSF64, I32TruncUF64, I64ExtendSI32, I64ExtendUI32, I64TruncSF32, I64TruncUF32, I64TruncSF64, I64TruncUF64, F32ConvertSI32, F32ConvertUI32, F32ConvertSI64, F32ConvertUI64, F32DemoteF64, F64ConvertSI32, F64ConvertUI32, F64ConvertSI64, F64ConvertUI64, F64PromoteF32, I32ReinterpretF32, I64ReinterpretF64, F32ReinterpretI32, F64ReinterpretI64, } impl Opcode { /// Is this opcode starts the new block (which should end with terminal opcode). pub fn is_block(&self) -> bool { match self { &Opcode::Block(_) | &Opcode::Loop(_) | &Opcode::If(_) => true, _ => false, } } /// Is this opcode determines the termination of opcode sequence /// `true` for `Opcode::End` pub fn is_terminal(&self) -> bool { match self { &Opcode::End => true, _ => false, } } } impl Deserialize for Opcode { type Error = Error; fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> { use self::Opcode::*; let val: u8 = Uint8::deserialize(reader)?.into(); Ok( match val { 0x00 => Unreachable, 0x01 => Nop, 0x02 => Block(BlockType::deserialize(reader)?), 0x03 => Loop(BlockType::deserialize(reader)?), 0x04 => If(BlockType::deserialize(reader)?), 0x05 => Else, 0x0b => End, 0x0c => Br(VarUint32::deserialize(reader)?.into()), 0x0d => BrIf(VarUint32::deserialize(reader)?.into()), 0x0e => { let t1: Vec<u32> = CountedList::<VarUint32>::deserialize(reader)? .into_inner() .into_iter() .map(Into::into) .collect(); BrTable(t1.into_boxed_slice(), VarUint32::deserialize(reader)?.into()) }, 0x0f => Return, 0x10 => Call(VarUint32::deserialize(reader)?.into()), 0x11 => { let signature: u32 = VarUint32::deserialize(reader)?.into(); let table_ref: u8 = Uint8::deserialize(reader)?.into(); if table_ref != 0 { return Err(Error::InvalidTableReference(table_ref)); } CallIndirect( signature, table_ref, ) }, 0x1a => Drop, 0x1b => Select, 0x20 => GetLocal(VarUint32::deserialize(reader)?.into()), 0x21 => SetLocal(VarUint32::deserialize(reader)?.into()), 0x22 => TeeLocal(VarUint32::deserialize(reader)?.into()), 0x23 => GetGlobal(VarUint32::deserialize(reader)?.into()), 0x24 => SetGlobal(VarUint32::deserialize(reader)?.into()), 0x28 => I32Load( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x29 => I64Load( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x2a => F32Load( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x2b => F64Load( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x2c => I32Load8S( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x2d => I32Load8U( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x2e => I32Load16S( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x2f => I32Load16U( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x30 => I64Load8S( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x31 => I64Load8U( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x32 => I64Load16S( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x33 => I64Load16U( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x34 => I64Load32S( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x35 => I64Load32U( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x36 => I32Store( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x37 => I64Store( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x38 => F32Store( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x39 => F64Store( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x3a => I32Store8( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x3b => I32Store16( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x3c => I64Store8( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x3d => I64Store16( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x3e => I64Store32( VarUint32::deserialize(reader)?.into(), VarUint32::deserialize(reader)?.into()), 0x3f => { let mem_ref: u8 = Uint8::deserialize(reader)?.into(); if mem_ref != 0 { return Err(Error::InvalidMemoryReference(mem_ref)); } CurrentMemory(mem_ref) }, 0x40 => { let mem_ref: u8 = Uint8::deserialize(reader)?.into(); if mem_ref != 0 { return Err(Error::InvalidMemoryReference(mem_ref)); } GrowMemory(mem_ref) } 0x41 => I32Const(VarInt32::deserialize(reader)?.into()), 0x42 => I64Const(VarInt64::deserialize(reader)?.into()), 0x43 => F32Const(Uint32::deserialize(reader)?.into()), 0x44 => F64Const(Uint64::deserialize(reader)?.into()), 0x45 => I32Eqz, 0x46 => I32Eq, 0x47 => I32Ne, 0x48 => I32LtS, 0x49 => I32LtU, 0x4a => I32GtS, 0x4b => I32GtU, 0x4c => I32LeS, 0x4d => I32LeU, 0x4e => I32GeS, 0x4f => I32GeU, 0x50 => I64Eqz, 0x51 => I64Eq, 0x52 => I64Ne, 0x53 => I64LtS, 0x54 => I64LtU, 0x55 => I64GtS, 0x56 => I64GtU, 0x57 => I64LeS, 0x58 => I64LeU, 0x59 => I64GeS, 0x5a => I64GeU, 0x5b => F32Eq, 0x5c => F32Ne, 0x5d => F32Lt, 0x5e => F32Gt, 0x5f => F32Le, 0x60 => F32Ge, 0x61 => F64Eq, 0x62 => F64Ne, 0x63 => F64Lt, 0x64 => F64Gt, 0x65 => F64Le, 0x66 => F64Ge, 0x67 => I32Clz, 0x68 => I32Ctz, 0x69 => I32Popcnt, 0x6a => I32Add, 0x6b => I32Sub, 0x6c => I32Mul, 0x6d => I32DivS, 0x6e => I32DivU, 0x6f => I32RemS, 0x70 => I32RemU, 0x71 => I32And, 0x72 => I32Or, 0x73 => I32Xor, 0x74 => I32Shl, 0x75 => I32ShrS, 0x76 => I32ShrU, 0x77 => I32Rotl, 0x78 => I32Rotr, 0x79 => I64Clz, 0x7a => I64Ctz, 0x7b => I64Popcnt, 0x7c => I64Add, 0x7d => I64Sub, 0x7e => I64Mul, 0x7f => I64DivS, 0x80 => I64DivU, 0x81 => I64RemS, 0x82 => I64RemU, 0x83 => I64And, 0x84 => I64Or, 0x85 => I64Xor, 0x86 => I64Shl, 0x87 => I64ShrS, 0x88 => I64ShrU, 0x89 => I64Rotl, 0x8a => I64Rotr, 0x8b => F32Abs, 0x8c => F32Neg, 0x8d => F32Ceil, 0x8e => F32Floor, 0x8f => F32Trunc, 0x90 => F32Nearest, 0x91 => F32Sqrt, 0x92 => F32Add, 0x93 => F32Sub, 0x94 => F32Mul, 0x95 => F32Div, 0x96 => F32Min, 0x97 => F32Max, 0x98 => F32Copysign, 0x99 => F64Abs, 0x9a => F64Neg, 0x9b => F64Ceil, 0x9c => F64Floor, 0x9d => F64Trunc, 0x9e => F64Nearest, 0x9f => F64Sqrt, 0xa0 => F64Add, 0xa1 => F64Sub, 0xa2 => F64Mul, 0xa3 => F64Div, 0xa4 => F64Min, 0xa5 => F64Max, 0xa6 => F64Copysign, 0xa7 => I32WrapI64, 0xa8 => I32TruncSF32, 0xa9 => I32TruncUF32, 0xaa => I32TruncSF64, 0xab => I32TruncUF64, 0xac => I64ExtendSI32, 0xad => I64ExtendUI32, 0xae => I64TruncSF32, 0xaf => I64TruncUF32, 0xb0 => I64TruncSF64, 0xb1 => I64TruncUF64, 0xb2 => F32ConvertSI32, 0xb3 => F32ConvertUI32, 0xb4 => F32ConvertSI64, 0xb5 => F32ConvertUI64, 0xb6 => F32DemoteF64, 0xb7 => F64ConvertSI32, 0xb8 => F64ConvertUI32, 0xb9 => F64ConvertSI64, 0xba => F64ConvertUI64, 0xbb => F64PromoteF32, 0xbc => I32ReinterpretF32, 0xbd => I64ReinterpretF64, 0xbe => F32ReinterpretI32, 0xbf => F64ReinterpretI64, _ => { return Err(Error::UnknownOpcode(val)); } } ) } } macro_rules! op { ($writer: expr, $byte: expr) => ({ let b: u8 = $byte; $writer.write_all(&[b])?; }); ($writer: expr, $byte: expr, $s: block) => ({ op!($writer, $byte); $s; }); } impl Serialize for Opcode { type Error = Error; fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> { use self::Opcode::*; match self { Unreachable => op!(writer, 0x00), Nop => op!(writer, 0x01), Block(block_type) => op!(writer, 0x02, { block_type.serialize(writer)?; }), Loop(block_type) => op!(writer, 0x03, { block_type.serialize(writer)?; }), If(block_type) => op!(writer, 0x04, { block_type.serialize(writer)?; }), Else => op!(writer, 0x05), End => op!(writer, 0x0b), Br(idx) => op!(writer, 0x0c, { VarUint32::from(idx).serialize(writer)?; }), BrIf(idx) => op!(writer, 0x0d, { VarUint32::from(idx).serialize(writer)?; }), BrTable(table, default) => op!(writer, 0x0e, { let list_writer = CountedListWriter::<VarUint32, _>( table.len(), table.into_iter().map(|x| VarUint32::from(*x)), ); list_writer.serialize(writer)?; VarUint32::from(default).serialize(writer)?; }), Return => op!(writer, 0x0f), Call(index) => op!(writer, 0x10, { VarUint32::from(index).serialize(writer)?; }), CallIndirect(index, reserved) => op!(writer, 0x11, { VarUint32::from(index).serialize(writer)?; Uint8::from(reserved).serialize(writer)?; }), Drop => op!(writer, 0x1a), Select => op!(writer, 0x1b), GetLocal(index) => op!(writer, 0x20, { VarUint32::from(index).serialize(writer)?; }), SetLocal(index) => op!(writer, 0x21, { VarUint32::from(index).serialize(writer)?; }), TeeLocal(index) => op!(writer, 0x22, { VarUint32::from(index).serialize(writer)?; }), GetGlobal(index) => op!(writer, 0x23, { VarUint32::from(index).serialize(writer)?; }), SetGlobal(index) => op!(writer, 0x24, { VarUint32::from(index).serialize(writer)?; }), I32Load(flags, offset) => op!(writer, 0x28, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load(flags, offset) => op!(writer, 0x29, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), F32Load(flags, offset) => op!(writer, 0x2a, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), F64Load(flags, offset) => op!(writer, 0x2b, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Load8S(flags, offset) => op!(writer, 0x2c, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Load8U(flags, offset) => op!(writer, 0x2d, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Load16S(flags, offset) => op!(writer, 0x2e, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Load16U(flags, offset) => op!(writer, 0x2f, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load8S(flags, offset) => op!(writer, 0x30, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load8U(flags, offset) => op!(writer, 0x31, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load16S(flags, offset) => op!(writer, 0x32, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load16U(flags, offset) => op!(writer, 0x33, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load32S(flags, offset) => op!(writer, 0x34, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Load32U(flags, offset) => op!(writer, 0x35, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Store(flags, offset) => op!(writer, 0x36, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Store(flags, offset) => op!(writer, 0x37, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), F32Store(flags, offset) => op!(writer, 0x38, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), F64Store(flags, offset) => op!(writer, 0x39, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Store8(flags, offset) => op!(writer, 0x3a, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I32Store16(flags, offset) => op!(writer, 0x3b, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Store8(flags, offset) => op!(writer, 0x3c, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Store16(flags, offset) => op!(writer, 0x3d, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), I64Store32(flags, offset) => op!(writer, 0x3e, { VarUint32::from(flags).serialize(writer)?; VarUint32::from(offset).serialize(writer)?; }), CurrentMemory(flag) => op!(writer, 0x3f, { Uint8::from(flag).serialize(writer)?; }), GrowMemory(flag) => op!(writer, 0x40, { Uint8::from(flag).serialize(writer)?; }), I32Const(def) => op!(writer, 0x41, { VarInt32::from(def).serialize(writer)?; }), I64Const(def) => op!(writer, 0x42, { VarInt64::from(def).serialize(writer)?; }), F32Const(def) => op!(writer, 0x43, { Uint32::from(def).serialize(writer)?; }), F64Const(def) => op!(writer, 0x44, { Uint64::from(def).serialize(writer)?; }), I32Eqz => op!(writer, 0x45), I32Eq => op!(writer, 0x46), I32Ne => op!(writer, 0x47), I32LtS => op!(writer, 0x48), I32LtU => op!(writer, 0x49), I32GtS => op!(writer, 0x4a), I32GtU => op!(writer, 0x4b), I32LeS => op!(writer, 0x4c), I32LeU => op!(writer, 0x4d), I32GeS => op!(writer, 0x4e), I32GeU => op!(writer, 0x4f), I64Eqz => op!(writer, 0x50), I64Eq => op!(writer, 0x51), I64Ne => op!(writer, 0x52), I64LtS => op!(writer, 0x53), I64LtU => op!(writer, 0x54), I64GtS => op!(writer, 0x55), I64GtU => op!(writer, 0x56), I64LeS => op!(writer, 0x57), I64LeU => op!(writer, 0x58), I64GeS => op!(writer, 0x59), I64GeU => op!(writer, 0x5a), F32Eq => op!(writer, 0x5b), F32Ne => op!(writer, 0x5c), F32Lt => op!(writer, 0x5d), F32Gt => op!(writer, 0x5e), F32Le => op!(writer, 0x5f), F32Ge => op!(writer, 0x60), F64Eq => op!(writer, 0x61), F64Ne => op!(writer, 0x62), F64Lt => op!(writer, 0x63), F64Gt => op!(writer, 0x64), F64Le => op!(writer, 0x65), F64Ge => op!(writer, 0x66), I32Clz => op!(writer, 0x67), I32Ctz => op!(writer, 0x68), I32Popcnt => op!(writer, 0x69), I32Add => op!(writer, 0x6a), I32Sub => op!(writer, 0x6b), I32Mul => op!(writer, 0x6c), I32DivS => op!(writer, 0x6d), I32DivU => op!(writer, 0x6e), I32RemS => op!(writer, 0x6f), I32RemU => op!(writer, 0x70), I32And => op!(writer, 0x71), I32Or => op!(writer, 0x72), I32Xor => op!(writer, 0x73), I32Shl => op!(writer, 0x74), I32ShrS => op!(writer, 0x75), I32ShrU => op!(writer, 0x76), I32Rotl => op!(writer, 0x77), I32Rotr => op!(writer, 0x78), I64Clz => op!(writer, 0x79), I64Ctz => op!(writer, 0x7a), I64Popcnt => op!(writer, 0x7b), I64Add => op!(writer, 0x7c), I64Sub => op!(writer, 0x7d), I64Mul => op!(writer, 0x7e), I64DivS => op!(writer, 0x7f), I64DivU => op!(writer, 0x80), I64RemS => op!(writer, 0x81), I64RemU => op!(writer, 0x82), I64And => op!(writer, 0x83), I64Or => op!(writer, 0x84), I64Xor => op!(writer, 0x85), I64Shl => op!(writer, 0x86), I64ShrS => op!(writer, 0x87), I64ShrU => op!(writer, 0x88), I64Rotl => op!(writer, 0x89), I64Rotr => op!(writer, 0x8a), F32Abs => op!(writer, 0x8b), F32Neg => op!(writer, 0x8c), F32Ceil => op!(writer, 0x8d), F32Floor => op!(writer, 0x8e), F32Trunc => op!(writer, 0x8f), F32Nearest => op!(writer, 0x90), F32Sqrt => op!(writer, 0x91), F32Add => op!(writer, 0x92), F32Sub => op!(writer, 0x93), F32Mul => op!(writer, 0x94), F32Div => op!(writer, 0x95), F32Min => op!(writer, 0x96), F32Max => op!(writer, 0x97), F32Copysign => op!(writer, 0x98), F64Abs => op!(writer, 0x99), F64Neg => op!(writer, 0x9a), F64Ceil => op!(writer, 0x9b), F64Floor => op!(writer, 0x9c), F64Trunc => op!(writer, 0x9d), F64Nearest => op!(writer, 0x9e), F64Sqrt => op!(writer, 0x9f), F64Add => op!(writer, 0xa0), F64Sub => op!(writer, 0xa1), F64Mul => op!(writer, 0xa2), F64Div => op!(writer, 0xa3), F64Min => op!(writer, 0xa4), F64Max => op!(writer, 0xa5), F64Copysign => op!(writer, 0xa6), I32WrapI64 => op!(writer, 0xa7), I32TruncSF32 => op!(writer, 0xa8), I32TruncUF32 => op!(writer, 0xa9), I32TruncSF64 => op!(writer, 0xaa), I32TruncUF64 => op!(writer, 0xab), I64ExtendSI32 => op!(writer, 0xac), I64ExtendUI32 => op!(writer, 0xad), I64TruncSF32 => op!(writer, 0xae), I64TruncUF32 => op!(writer, 0xaf), I64TruncSF64 => op!(writer, 0xb0), I64TruncUF64 => op!(writer, 0xb1), F32ConvertSI32 => op!(writer, 0xb2), F32ConvertUI32 => op!(writer, 0xb3), F32ConvertSI64 => op!(writer, 0xb4), F32ConvertUI64 => op!(writer, 0xb5), F32DemoteF64 => op!(writer, 0xb6), F64ConvertSI32 => op!(writer, 0xb7), F64ConvertUI32 => op!(writer, 0xb8), F64ConvertSI64 => op!(writer, 0xb9), F64ConvertUI64 => op!(writer, 0xba), F64PromoteF32 => op!(writer, 0xbb), I32ReinterpretF32 => op!(writer, 0xbc), I64ReinterpretF64 => op!(writer, 0xbd), F32ReinterpretI32 => op!(writer, 0xbe), F64ReinterpretI64 => op!(writer, 0xbf), } Ok(()) } } macro_rules! fmt_op { ($f: expr, $mnemonic: expr) => ({ write!($f, "{}", $mnemonic) }); ($f: expr, $mnemonic: expr, $immediate: expr) => ({ write!($f, "{} {}", $mnemonic, $immediate) }); ($f: expr, $mnemonic: expr, $immediate1: expr, $immediate2: expr) => ({ write!($f, "{} {} {}", $mnemonic, $immediate1, $immediate2) }); } impl fmt::Display for Opcode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Opcode::*; use super::BlockType; match *self { Unreachable => fmt_op!(f, "unreachable"), Nop => fmt_op!(f, "nop"), Block(BlockType::NoResult) => fmt_op!(f, "block"), Block(BlockType::Value(value_type)) => fmt_op!(f, "block", value_type), Loop(BlockType::NoResult) => fmt_op!(f, "loop"), Loop(BlockType::Value(value_type)) => fmt_op!(f, "loop", value_type), If(BlockType::NoResult) => fmt_op!(f, "if"), If(BlockType::Value(value_type)) => fmt_op!(f, "if", value_type), Else => fmt_op!(f, "else"), End => fmt_op!(f, "end"), Br(idx) => fmt_op!(f, "br", idx), BrIf(idx) => fmt_op!(f, "br_if", idx), BrTable(_, default) => fmt_op!(f, "br_table", default), Return => fmt_op!(f, "return"), Call(index) => fmt_op!(f, "call", index), CallIndirect(index, _) => fmt_op!(f, "call_indirect", index), Drop => fmt_op!(f, "drop"), Select => fmt_op!(f, "select"), GetLocal(index) => fmt_op!(f, "get_local", index), SetLocal(index) => fmt_op!(f, "set_local", index), TeeLocal(index) => fmt_op!(f, "tee_local", index), GetGlobal(index) => fmt_op!(f, "get_global", index), SetGlobal(index) => fmt_op!(f, "set_global", index), I32Load(_, 0) => write!(f, "i32.load"), I32Load(_, offset) => write!(f, "i32.load offset={}", offset), I64Load(_, 0) => write!(f, "i64.load"), I64Load(_, offset) => write!(f, "i64.load offset={}", offset), F32Load(_, 0) => write!(f, "f32.load"), F32Load(_, offset) => write!(f, "f32.load offset={}", offset), F64Load(_, 0) => write!(f, "f64.load"), F64Load(_, offset) => write!(f, "f64.load offset={}", offset), I32Load8S(_, 0) => write!(f, "i32.load8_s"), I32Load8S(_, offset) => write!(f, "i32.load8_s offset={}", offset), I32Load8U(_, 0) => write!(f, "i32.load8_u"), I32Load8U(_, offset) => write!(f, "i32.load8_u offset={}", offset), I32Load16S(_, 0) => write!(f, "i32.load16_s"), I32Load16S(_, offset) => write!(f, "i32.load16_s offset={}", offset), I32Load16U(_, 0) => write!(f, "i32.load16_u"), I32Load16U(_, offset) => write!(f, "i32.load16_u offset={}", offset), I64Load8S(_, 0) => write!(f, "i64.load8_s"), I64Load8S(_, offset) => write!(f, "i64.load8_s offset={}", offset), I64Load8U(_, 0) => write!(f, "i64.load8_u"), I64Load8U(_, offset) => write!(f, "i64.load8_u offset={}", offset), I64Load16S(_, 0) => write!(f, "i64.load16_s"), I64Load16S(_, offset) => write!(f, "i64.load16_s offset={}", offset), I64Load16U(_, 0) => write!(f, "i64.load16_u"), I64Load16U(_, offset) => write!(f, "i64.load16_u offset={}", offset), I64Load32S(_, 0) => write!(f, "i64.load32_s"), I64Load32S(_, offset) => write!(f, "i64.load32_s offset={}", offset), I64Load32U(_, 0) => write!(f, "i64.load32_u"), I64Load32U(_, offset) => write!(f, "i64.load32_u offset={}", offset), I32Store(_, 0) => write!(f, "i32.store"), I32Store(_, offset) => write!(f, "i32.store offset={}", offset), I64Store(_, 0) => write!(f, "i64.store"), I64Store(_, offset) => write!(f, "i64.store offset={}", offset), F32Store(_, 0) => write!(f, "f32.store"), F32Store(_, offset) => write!(f, "f32.store offset={}", offset), F64Store(_, 0) => write!(f, "f64.store"), F64Store(_, offset) => write!(f, "f64.store offset={}", offset), I32Store8(_, 0) => write!(f, "i32.store8"), I32Store8(_, offset) => write!(f, "i32.store8 offset={}", offset), I32Store16(_, 0) => write!(f, "i32.store16"), I32Store16(_, offset) => write!(f, "i32.store16 offset={}", offset), I64Store8(_, 0) => write!(f, "i64.store8"), I64Store8(_, offset) => write!(f, "i64.store8 offset={}", offset), I64Store16(_, 0) => write!(f, "i64.store16"), I64Store16(_, offset) => write!(f, "i64.store16 offset={}", offset), I64Store32(_, 0) => write!(f, "i64.store32"), I64Store32(_, offset) => write!(f, "i64.store32 offset={}", offset), CurrentMemory(_) => fmt_op!(f, "current_memory"), GrowMemory(_) => fmt_op!(f, "grow_memory"), I32Const(def) => fmt_op!(f, "i32.const", def), I64Const(def) => fmt_op!(f, "i64.const", def), F32Const(def) => fmt_op!(f, "f32.const", def), F64Const(def) => fmt_op!(f, "f64.const", def), I32Eq => write!(f, "i32.eq"), I32Eqz => write!(f, "i32.eqz"), I32Ne => write!(f, "i32.ne"), I32LtS => write!(f, "i32.lt_s"), I32LtU => write!(f, "i32.lt_u"), I32GtS => write!(f, "i32.gt_s"), I32GtU => write!(f, "i32.gt_u"), I32LeS => write!(f, "i32.le_s"), I32LeU => write!(f, "i32.le_u"), I32GeS => write!(f, "i32.ge_s"), I32GeU => write!(f, "i32.ge_u"), I64Eq => write!(f, "i64.eq"), I64Eqz => write!(f, "i64.eqz"), I64Ne => write!(f, "i64.ne"), I64LtS => write!(f, "i64.lt_s"), I64LtU => write!(f, "i64.lt_u"), I64GtS => write!(f, "i64.gt_s"), I64GtU => write!(f, "i64.gt_u"), I64LeS => write!(f, "i64.le_s"), I64LeU => write!(f, "i64.le_u"), I64GeS => write!(f, "i64.ge_s"), I64GeU => write!(f, "i64.ge_u"), F32Eq => write!(f, "f32.eq"), F32Ne => write!(f, "f32.ne"), F32Lt => write!(f, "f32.lt"), F32Gt => write!(f, "f32.gt"), F32Le => write!(f, "f32.le"), F32Ge => write!(f, "f32.ge"), F64Eq => write!(f, "f64.eq"), F64Ne => write!(f, "f64.ne"), F64Lt => write!(f, "f64.lt"), F64Gt => write!(f, "f64.gt"), F64Le => write!(f, "f64.le"), F64Ge => write!(f, "f64.ge"), I32Clz => write!(f, "i32.clz"), I32Ctz => write!(f, "i32.ctz"), I32Popcnt => write!(f, "i32.popcnt"), I32Add => write!(f, "i32.add"), I32Sub => write!(f, "i32.sub"), I32Mul => write!(f, "i32.mul"), I32DivS => write!(f, "i32.div_s"), I32DivU => write!(f, "i32.div_u"), I32RemS => write!(f, "i32.rem_s"), I32RemU => write!(f, "i32.rem_u"), I32And => write!(f, "i32.and"), I32Or => write!(f, "i32.or"), I32Xor => write!(f, "i32.xor"), I32Shl => write!(f, "i32.shl"), I32ShrS => write!(f, "i32.shr_s"), I32ShrU => write!(f, "i32.shr_u"), I32Rotl => write!(f, "i32.rotl"), I32Rotr => write!(f, "i32.rotr"), I64Clz => write!(f, "i64.clz"), I64Ctz => write!(f, "i64.ctz"), I64Popcnt => write!(f, "i64.popcnt"), I64Add => write!(f, "i64.add"), I64Sub => write!(f, "i64.sub"), I64Mul => write!(f, "i64.mul"), I64DivS => write!(f, "i64.div_s"), I64DivU => write!(f, "i64.div_u"), I64RemS => write!(f, "i64.rem_s"), I64RemU => write!(f, "i64.rem_u"), I64And => write!(f, "i64.and"), I64Or => write!(f, "i64.or"), I64Xor => write!(f, "i64.xor"), I64Shl => write!(f, "i64.shl"), I64ShrS => write!(f, "i64.shr_s"), I64ShrU => write!(f, "i64.shr_u"), I64Rotl => write!(f, "i64.rotl"), I64Rotr => write!(f, "i64.rotr"), F32Abs => write!(f, "f32.abs"), F32Neg => write!(f, "f32.neg"), F32Ceil => write!(f, "f32.ceil"), F32Floor => write!(f, "f32.floor"), F32Trunc => write!(f, "f32.trunc"), F32Nearest => write!(f, "f32.nearest"), F32Sqrt => write!(f, "f32.sqrt"), F32Add => write!(f, "f32.add"), F32Sub => write!(f, "f32.sub"), F32Mul => write!(f, "f32.mul"), F32Div => write!(f, "f32.div"), F32Min => write!(f, "f32.min"), F32Max => write!(f, "f32.max"), F32Copysign => write!(f, "f32.copysign"), F64Abs => write!(f, "f64.abs"), F64Neg => write!(f, "f64.neg"), F64Ceil => write!(f, "f64.ceil"), F64Floor => write!(f, "f64.floor"), F64Trunc => write!(f, "f64.trunc"), F64Nearest => write!(f, "f64.nearest"), F64Sqrt => write!(f, "f64.sqrt"), F64Add => write!(f, "f64.add"), F64Sub => write!(f, "f64.sub"), F64Mul => write!(f, "f64.mul"), F64Div => write!(f, "f64.div"), F64Min => write!(f, "f64.min"), F64Max => write!(f, "f64.max"), F64Copysign => write!(f, "f64.copysign"), I32WrapI64 => write!(f, "i32.wrap/i64"), I32TruncSF32 => write!(f, "i32.trunc_s/f32"), I32TruncUF32 => write!(f, "i32.trunc_u/f32"), I32TruncSF64 => write!(f, "i32.trunc_s/f64"), I32TruncUF64 => write!(f, "i32.trunc_u/f64"), I64ExtendSI32 => write!(f, "i64.extend_s/i32"), I64ExtendUI32 => write!(f, "i64.extend_u/i32"), I64TruncSF32 => write!(f, "i64.trunc_s/f32"), I64TruncUF32 => write!(f, "i64.trunc_u/f32"), I64TruncSF64 => write!(f, "i64.trunc_s/f64"), I64TruncUF64 => write!(f, "i64.trunc_u/f64"), F32ConvertSI32 => write!(f, "f32.convert_s/i32"), F32ConvertUI32 => write!(f, "f32.convert_u/i32"), F32ConvertSI64 => write!(f, "f32.convert_s/i64"), F32ConvertUI64 => write!(f, "f32.convert_u/i64"), F32DemoteF64 => write!(f, "f32.demote/f64"), F64ConvertSI32 => write!(f, "f64.convert_s/i32"), F64ConvertUI32 => write!(f, "f64.convert_u/i32"), F64ConvertSI64 => write!(f, "f64.convert_s/i64"), F64ConvertUI64 => write!(f, "f64.convert_u/i64"), F64PromoteF32 => write!(f, "f64.promote/f32"), I32ReinterpretF32 => write!(f, "i32.reinterpret/f32"), I64ReinterpretF64 => write!(f, "i64.reinterpret/f64"), F32ReinterpretI32 => write!(f, "f32.reinterpret/i32"), F64ReinterpretI64 => write!(f, "f64.reinterpret/i64"), } } } impl Serialize for Opcodes { type Error = Error; fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> { for op in self.0.into_iter() { op.serialize(writer)?; } Ok(()) } } impl Serialize for InitExpr { type Error = Error; fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> { for op in self.0.into_iter() { op.serialize(writer)?; } Ok(()) } } #[test] fn ifelse() { // see if-else.wast/if-else.wasm let opcode = super::deserialize_buffer::<Opcodes>(&[0x04, 0x7F, 0x41, 0x05, 0x05, 0x41, 0x07, 0x0B, 0x0B]) .expect("valid hex of if instruction"); let opcodes = opcode.elements(); match &opcodes[0] { &Opcode::If(_) => (), _ => panic!("Should be deserialized as if opcode"), } let before_else = opcodes.iter().skip(1) .take_while(|op| match **op { Opcode::Else => false, _ => true }).count(); let after_else = opcodes.iter().skip(1) .skip_while(|op| match **op { Opcode::Else => false, _ => true }) .take_while(|op| match **op { Opcode::End => false, _ => true }) .count() - 1; // minus Opcode::Else itself assert_eq!(before_else, after_else); } #[test] fn display() { let opcode = Opcode::GetLocal(0); assert_eq!("get_local 0", format!("{}", opcode)); let opcode = Opcode::F64Store(0, 24); assert_eq!("f64.store offset=24", format!("{}", opcode)); let opcode = Opcode::I64Store(0, 0); assert_eq!("i64.store", format!("{}", opcode)); } #[test] fn size_off() { assert!(::std::mem::size_of::<Opcode>() <= 24); }
use super::VarResult; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType}; use crate::helper::err_msgs::*; use crate::helper::str_replace; use crate::helper::{ move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_f64, pine_ref_to_i64, pine_ref_to_string, }; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::output::{OutputData, OutputInfo, PlotInfo, StrOptionsData}; use crate::types::{ Bool, Callable, CallableObject, Color, DataType, Float, Int, ParamCollectCall, PineClass, PineFrom, PineRef, PineType, RefData, RuntimeErr, SecondType, Series, SeriesCall, NA, }; use std::collections::BTreeMap; use std::rc::Rc; fn resize_offset<'a, T>(data: &mut Vec<Option<T>>, offset: i64) { match offset { 0 => {} i if i > 0 => { let mut fillv: Vec<Option<T>> = Vec::with_capacity(offset as usize); fillv.resize_with(offset as usize, || None); data.splice(..0, fillv); } _ => { data.splice(0..offset.abs() as usize, vec![]); } }; } fn plot_val<'a>( item_val: PineRef<'a>, // offset: i64, _context: &mut dyn Ctx<'a>, ) -> Result<Vec<Option<f64>>, RuntimeErr> { let mut items: RefData<Series<Float>> = Series::implicity_from(item_val).unwrap(); let mut data = items.move_history(); // resize_offset(&mut data, offset); Ok(data) } pub fn plot_color<'a>( item_val: PineRef<'a>, // offset: i64, _context: &mut dyn Ctx<'a>, ) -> Result<StrOptionsData, RuntimeErr> { // let item_data: RefData<Series<Float>> = Series::implicity_from(item_val).unwrap(); // plot_series(item_data.into_pf(), context) let mut items: RefData<Series<Color<'a>>> = Series::implicity_from(item_val).unwrap(); let colors: Vec<Color<'a>> = items.move_history(); let mut options: Vec<&'a str> = vec![]; let mut values: Vec<Option<i32>> = vec![]; for color in colors.iter() { match options.iter().position(|&x| x == color.0) { None => { options.push(color.0); values.push(Some((options.len() - 1) as i32)); } Some(i) => { values.push(Some(i as i32)); } } } let options = options.iter().map(|&x| String::from(x)).collect(); // resize_offset(&mut values, offset); Ok(StrOptionsData { options, values }) } fn pine_plot<'a>( context: &mut dyn Ctx<'a>, mut param: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<(), RuntimeErr> { // move_tuplet!((series, _title, color) = param); let series = move_element(&mut param, 0); let color = move_element(&mut param, 2); match _func_type.get_type(2) { Some(SyntaxType::Series(_)) => match (series, color) { (Some(item_val), Some(color)) => { let data = plot_val(item_val, context)?; let color = plot_color(color, context)?; downcast_ctx(context) .push_output_data(Some(OutputData::new_with_sc(vec![data], vec![color]))); Ok(()) } _ => Err(RuntimeErr::NotSupportOperator), }, Some(SyntaxType::Simple(_)) => match series { Some(item_val) => { let data = plot_val(item_val, context)?; downcast_ctx(context).push_output_data(Some(OutputData::new(vec![data]))); Ok(()) } _ => Err(RuntimeErr::NotSupportOperator), }, _ => unreachable!(), } } #[derive(Debug, Clone)] struct PlotVal { output_id: i32, } impl PlotVal { fn new() -> PlotVal { PlotVal { output_id: -1 } } } impl<'a> SeriesCall<'a> for PlotVal { fn step( &mut self, context: &mut dyn Ctx<'a>, mut p: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { if self.output_id < 0 && !downcast_ctx(context).check_is_output_info_ready() { move_tuplet!( ( _series, title, color, linewidth, style, trackprice, opacity, histbase, offset, join, editable, show_last, display ) = p ); let plot_info = PlotInfo { title: pine_ref_to_string(title), color: match _func_type.get_type(2) { Some(SyntaxType::Simple(_)) => pine_ref_to_color(color), _ => Some(String::from("")), }, linewidth: pine_ref_to_i64(linewidth), style: pine_ref_to_string(style), opacity: pine_ref_to_i64(opacity), trackprice: pine_ref_to_bool(trackprice), histbase: pine_ref_to_f64(histbase), offset: pine_ref_to_i64(offset), join: pine_ref_to_bool(join), editable: pine_ref_to_bool(editable), show_last: pine_ref_to_i64(show_last), display: pine_ref_to_i64(display), }; self.output_id = downcast_ctx(context).push_output_info_retindex(OutputInfo::Plot(plot_info)); } Ok(PineRef::Box(Box::new(Some(self.output_id as i64)))) } fn run_with_cd( &mut self, _context: &mut dyn Ctx<'a>, params: Vec<Option<PineRef<'a>>>, func_type: FunctionType<'a>, ) -> Result<(), RuntimeErr> { pine_plot(_context, params, func_type) } fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> { Box::new(self.clone()) } } struct PlotProps; impl<'a> PineClass<'a> for PlotProps { fn custom_type(&self) -> &str { "plot" } fn get(&self, _ctx: &mut dyn Ctx<'a>, name: &str) -> Result<PineRef<'a>, RuntimeErr> { match name { "style_area" => Ok(PineRef::new_rc(String::from("area"))), "style_areabr" => Ok(PineRef::new_rc(String::from("areabr"))), "style_circles" => Ok(PineRef::new_rc(String::from("circles"))), "style_columns" => Ok(PineRef::new_rc(String::from("columns"))), "style_cross" => Ok(PineRef::new_rc(String::from("cross"))), "style_histogram" => Ok(PineRef::new_rc(String::from("histogram"))), "style_line" => Ok(PineRef::new_rc(String::from("line"))), "style_linebr" => Ok(PineRef::new_rc(String::from("linebr"))), "style_stepline" => Ok(PineRef::new_rc(String::from("stepline"))), _ => Err(RuntimeErr::NotImplement(str_replace( NO_FIELD_IN_OBJECT, vec![String::from(name), String::from("plot")], ))), } } fn copy(&self) -> Box<dyn PineClass<'a> + 'a> { Box::new(PlotProps) } } pub const VAR_NAME: &'static str = "plot"; pub fn declare_var<'a>() -> VarResult<'a> { let value = PineRef::new(CallableObject::new(Box::new(PlotProps), || { Callable::new( None, Some(Box::new(ParamCollectCall::new_with_caller(Box::new( PlotVal::new(), )))), ) })); // plot(series, title, color, linewidth, style, trackprice, opacity, histbase, offset, join, editable, show_last) → plot let func_type = FunctionTypes(vec![ FunctionType::new(( vec![ ("series", SyntaxType::Series(SimpleSyntaxType::Float)), ("title", SyntaxType::string()), ("color", SyntaxType::color()), ("linewidth", SyntaxType::int()), ("style", SyntaxType::string()), ("trackprice", SyntaxType::bool()), ("opacity", SyntaxType::int()), ("histbase", SyntaxType::float()), ("offset", SyntaxType::int()), ("join", SyntaxType::bool()), ("editable", SyntaxType::bool()), ("show_last", SyntaxType::int()), ("display", SyntaxType::int()), ], SyntaxType::ObjectClass("plot"), )), FunctionType::new(( vec![ ("series", SyntaxType::Series(SimpleSyntaxType::Float)), ("title", SyntaxType::string()), ("color", SyntaxType::Series(SimpleSyntaxType::Color)), ("linewidth", SyntaxType::int()), ("style", SyntaxType::string()), ("trackprice", SyntaxType::bool()), ("opacity", SyntaxType::int()), ("histbase", SyntaxType::float()), ("offset", SyntaxType::int()), ("join", SyntaxType::bool()), ("editable", SyntaxType::bool()), ("show_last", SyntaxType::int()), ("display", SyntaxType::int()), ], SyntaxType::ObjectClass("plot"), )), ]); let mut obj_type = BTreeMap::new(); obj_type.insert("style_area", SyntaxType::string()); // obj_type.insert("style_areabr", SyntaxType::string()); obj_type.insert("style_circles", SyntaxType::string()); obj_type.insert("style_columns", SyntaxType::string()); obj_type.insert("style_cross", SyntaxType::string()); obj_type.insert("style_histogram", SyntaxType::string()); obj_type.insert("style_line", SyntaxType::string()); obj_type.insert("style_linebr", SyntaxType::string()); obj_type.insert("style_stepline", SyntaxType::string()); let syntax_type = SyntaxType::ObjectFunction(Rc::new(obj_type), Rc::new(func_type)); VarResult::new(value, syntax_type, VAR_NAME) } #[cfg(test)] mod tests { use super::*; use crate::runtime::{AnySeries, NoneCallback}; use crate::{LibInfo, PineParser, PineRunner}; #[test] fn plot_const_num() { let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], ); let src = "plot(1000)"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![( "close", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), )], None, ) .unwrap(); assert_eq!( runner.move_output_data(), vec![Some(OutputData::new(vec![vec![ Some(1000f64), Some(1000f64) ]])),] ); } #[test] fn plot_test() { let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], ); let src = "plot(close)\nplot(close + 1)"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![( "close", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), )], None, ) .unwrap(); assert_eq!( runner.move_output_data(), vec![ Some(OutputData::new(vec![vec![Some(1f64), Some(2f64)]])), Some(OutputData::new(vec![vec![Some(2f64), Some(3f64)]])) ] ); assert_eq!(runner.get_io_info().get_outputs().len(), 2); runner .update(&vec![( "close", AnySeries::from_float_vec(vec![Some(10f64), Some(11f64)]), )]) .unwrap(); assert_eq!( runner.move_output_data(), vec![ Some(OutputData::new(vec![vec![Some(10f64), Some(11f64)]])), Some(OutputData::new(vec![vec![Some(11f64), Some(12f64)]])), ] ); assert_eq!(runner.get_io_info().get_outputs().len(), 2); runner .update_from( &vec![( "close", AnySeries::from_float_vec(vec![Some(100f64), Some(101f64), Some(102f64)]), )], 1, ) .unwrap(); assert_eq!( runner.move_output_data(), vec![ Some(OutputData::new(vec![vec![ Some(100f64), Some(101f64), Some(102f64) ]])), Some(OutputData::new(vec![vec![ Some(101f64), Some(102f64), Some(103f64) ]])), ] ); } #[test] fn plot_info_test() { use crate::runtime::OutputInfo; let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], ); let src = r"plot(close, title='Title', color=#00ffaa, linewidth=2, style='area', opacity=70, offset=15, trackprice=true, histbase=0.0, join=true, editable=true, show_last=100, display=1)"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![( "close", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), )], None, ) .unwrap(); assert_eq!( runner.get_io_info().get_outputs(), &vec![OutputInfo::Plot(PlotInfo { title: Some(String::from("Title")), color: Some(String::from("#00ffaa")), linewidth: Some(2), style: Some(String::from("area")), trackprice: Some(true), opacity: Some(70), histbase: Some(0.0f64), offset: Some(15), join: Some(true), editable: Some(true), show_last: Some(100), display: Some(1) })] ) } #[test] fn plot_ret_test() { // use crate::runtime::OutputInfo; use crate::ast::stat_expr_types::VarIndex; use crate::runtime::VarOperate; let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], ); let src = r"p = plot(close)"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); assert!(runner .run( &vec![( "close", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), )], None, ) .is_ok()); assert_eq!( runner.get_context().move_var(VarIndex::new(0, 0)).unwrap(), PineRef::new(Some(0i64)) ); } #[test] fn plot_color_test() { use crate::runtime::OutputInfo; let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], ); let src = r"plot(close, color=close > 1 ? #00ffaa : #ff00aa)"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![( "close", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), )], None, ) .unwrap(); assert_eq!( runner.get_io_info().get_outputs(), &vec![OutputInfo::Plot(PlotInfo { title: None, color: Some(String::from("")), linewidth: None, style: None, trackprice: None, opacity: None, histbase: None, offset: None, join: None, editable: None, show_last: None, display: None, })] ); assert_eq!( runner.move_output_data(), vec![Some(OutputData::new_with_sc( vec![vec![Some(1f64), Some(2f64)]], vec![StrOptionsData { options: vec![String::from("#ff00aa"), String::from("#00ffaa")], values: vec![Some(0), Some(1)] }] )),] ); } #[test] fn plot_fields_test() { use crate::ast::stat_expr_types::VarIndex; use crate::runtime::VarOperate; use crate::types::{downcast_pf, Tuple}; let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::float_series())], ); let src = r"m = [ plot.style_area, plot.style_circles, plot.style_columns, // plot.style_areabr plot.style_cross, plot.style_histogram, plot.style_line, plot.style_linebr, plot.style_stepline ]"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![("close", AnySeries::from_float_vec(vec![Some(1f64)]))], None, ) .unwrap(); let tuple_res = downcast_pf::<Tuple>(runner.get_context().move_var(VarIndex::new(0, 0)).unwrap()); let tuple_vec = tuple_res.unwrap().into_inner().0; assert_eq!( tuple_vec, vec![ PineRef::new_rc(String::from("area")), // PineRef::new_rc(String::from("areabr")), PineRef::new_rc(String::from("circles")), PineRef::new_rc(String::from("columns")), PineRef::new_rc(String::from("cross")), PineRef::new_rc(String::from("histogram")), PineRef::new_rc(String::from("line")), PineRef::new_rc(String::from("linebr")), PineRef::new_rc(String::from("stepline")), ] ); } // #[test] // fn plot_offset_test() { // let lib_info = LibInfo::new( // vec![declare_var()], // vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], // ); // let src = "plot(close, offset = 2)\nplot(close, offset = -1)"; // let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); // let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); // runner // .run( // &vec![( // "close", // AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), // )], // None, // ) // .unwrap(); // assert_eq!( // runner.move_output_data(), // vec![ // Some(OutputData::new(vec![vec![ // None, // None, // Some(1f64), // Some(2f64) // ]])), // Some(OutputData::new(vec![vec![Some(2f64)]])) // ] // ); // } }
//! This file contains all necessary information needed to construct a SMB2 packet. /// Protocol id with fixed value const PROTOCOL_ID: &[u8; 4] = b"\xfe\x53\x4d\x42"; /// SMB head size of 64 bytes const STRUCTURE_SIZE: &[u8; 2] = b"\x40\x00"; /// All commands that could be in the command field. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Commands { Negotiate, SessionSetup, Logoff, TreeConnect, TreeDisconnect, Create, Close, Flush, Read, Write, Lock, Ioctl, Cancel, Echo, QueryDirectory, ChangeNotify, QueryInfo, SetInfo, OplockBreak, } impl Commands { /// Return the corresponding byte code (2 bytes) for each command. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Commands::Negotiate => b"\x00\x00".to_vec(), Commands::SessionSetup => b"\x01\x00".to_vec(), Commands::Logoff => b"\x02\x00".to_vec(), Commands::TreeConnect => b"\x03\x00".to_vec(), Commands::TreeDisconnect => b"\x04\x00".to_vec(), Commands::Create => b"\x05\x00".to_vec(), Commands::Close => b"\x06\x00".to_vec(), Commands::Flush => b"\x07\x00".to_vec(), Commands::Read => b"\x08\x00".to_vec(), Commands::Write => b"\x09\x00".to_vec(), Commands::Lock => b"\x0a\x00".to_vec(), Commands::Ioctl => b"\x0b\x00".to_vec(), Commands::Cancel => b"\x0c\x00".to_vec(), Commands::Echo => b"\x0d\x00".to_vec(), Commands::QueryDirectory => b"\x0e\x00".to_vec(), Commands::ChangeNotify => b"\x0f\x00".to_vec(), Commands::QueryInfo => b"\x10\x00".to_vec(), Commands::SetInfo => b"\x11\x00".to_vec(), Commands::OplockBreak => b"\x12\x00".to_vec(), } } } /// The flags indicate how to process the operation. This field MUST be constructed using the following values: /// /// *Server To Redir*: /// - When set, indicates the message is response rather than a request. /// This MUST be set on responses sent from the server to the client, /// and MUST NOT be set on requests sent from the client to the server. /// /// *Async Command*: /// - When set, indicates that this is an ASYNC SMB2 header. /// /// *Related Operations*: /// - When set in an SMB2 request, indicates that this request is a related operation in a compounded request chain. /// - When set in an SMB2 compound response, indicates that the request corresponding to this response was part of /// a related operation in a compounded request chain. /// /// *Signed*: /// - When set, indicates that this packet has been signed. /// /// *Priority Mask*: /// - This flag is only valid for SMB 3.1.1 dialect. It is a mask for the requested I/O priority request, and /// it MUST be a value in a range of 0 to 7. /// /// *DFS Operations*: /// - When set, indicates that this command is a Distributed File System (DFS) operation. /// /// *Replay Operation*: /// - This flag is only valid for the 3.x dialect family. When set, it indicates that this command is a replay operation. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Flags { ServerToRedir, AsyncCommand, RelatedOperations, Signed, PriorityMask, DfsOperations, ReplayOperation, NoFlags, } impl Flags { /// Return the corresponding byte code (4 bytes) for each flag. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Flags::ServerToRedir => b"\x01\x00\x00\x00".to_vec(), Flags::AsyncCommand => b"\x02\x00\x00\x00".to_vec(), Flags::RelatedOperations => b"\x04\x00\x00\x00".to_vec(), Flags::Signed => b"\x08\x00\x00\x00".to_vec(), Flags::PriorityMask => b"\x70\x00\x00\x00".to_vec(), Flags::DfsOperations => b"\x10\x00\x00\x00".to_vec(), Flags::ReplayOperation => b"\x20\x00\x00\x00".to_vec(), Flags::NoFlags => b"\x00\x00\x00\x00".to_vec(), } } } /// The SMB header struct contains all fields necessary to build a SMB header. #[derive(Debug, PartialEq, Eq, Clone)] pub struct GenericHeader { /// Protcol id (4 bytes) is constant over all SMB packets. It stands for 254 'S', 'M', 'B' pub protocol_id: Vec<u8>, /// Header length (2 bytes) must always be set to 64 bytes. pub structure_size: Vec<u8>, /// CreditCharge (2 bytes): In the SMB 2.0.2 dialect, this field MUST NOT be used and MUST be reserved. /// The sender MUST set this to 0, and the receiver MUST ignore it. /// In all other dialects, this field indicates the number of credits that this request consumes. pub credit_charge: Vec<u8>, /// ChannelSequence (2 bytes): This field is an indication to the server about the client's Channel change. Only for versions 3.x. (2 bytes) pub channel_sequence: Vec<u8>, /// Reserved (2 bytes): This field SHOULD be set to zero and the server MUST ignore it on receipt. /// In the SMB 2.0.2 and SMB 2.1 dialects, this field is interpreted as the Status field in a request. pub reserved: Vec<u8>, /// Status (4 bytes): The client MUST set this field to 0 and the server MUST ignore it on receipt. /// In all SMB dialects for a response this field is interpreted as the Status field. /// This field can be set to any value. Only for versions 2.x. pub status: Vec<u8>, /// Command (2 bytes): The command code of this packet. (2 bytes) pub command: Vec<u8>, /// CreditRequest/CreditResponse (2 bytes): On a request, this field indicates /// the number of credits the client is requesting. /// On a response, it indicates the number of credits granted to the client. pub credit: Vec<u8>, /// A flags field (4 bytes), which indicates how to process the operation. /// MUST be constructed using one of the Flag values. pub flags: Vec<u8>, /// NextCommand (4 bytes): For a compounded request and response, this field /// MUST be set to the offset, in bytes, from the beginning of this SMB2 header /// to the start of the subsequent 8-byte aligned SMB2 header. /// If this is not a compounded request or response, /// or this is the last header in a compounded request or response, this value MUST be 0. pub next_command: Vec<u8>, /// MessageId (8 bytes): A value that identifies a message request and /// response uniquely across all messages that are sent on the same SMB 2 Protocol transport connection. pub message_id: Vec<u8>, } impl GenericHeader { /// Creates a new generic header by setting the protocol id and structure size initially. pub fn default() -> Self { GenericHeader { protocol_id: PROTOCOL_ID.to_vec(), structure_size: STRUCTURE_SIZE.to_vec(), credit_charge: Vec::new(), channel_sequence: Vec::new(), reserved: Vec::new(), status: Vec::new(), command: Vec::new(), credit: Vec::new(), flags: Vec::new(), next_command: Vec::new(), message_id: Vec::new(), } } } impl std::fmt::Display for GenericHeader { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Generic Header:\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}", self.protocol_id, self.structure_size, self.credit_charge, self.channel_sequence, self.reserved, self.status, self.command, self.credit, self.flags, self.next_command, self.message_id, ) } } #[derive(Debug, PartialEq, Eq, Clone)] /// The SMB header for asynchronous messages. pub struct AsyncHeader { /// Generic header fields that are equivalent for both sync and async headers. pub generic: GenericHeader, /// AsyncId (8 bytes): A unique identification number that is created by the server to handle operations asynchronously. pub async_id: Vec<u8>, /// SessionId (8 bytes): Uniquely identifies the established session for the command. ///This field MUST be set to 0 for an SMB2 NEGOTIATE Request and for an SMB2 NEGOTIATE Response. pub session_id: Vec<u8>, /// Signature (16 bytes): The 16-byte signature of the message, /// if SMB2_FLAGS_SIGNED is set in the Flags field of the SMB2 header and the message is not encrypted. /// If the message is not signed, this field MUST be 0. pub signature: Vec<u8>, } impl AsyncHeader { /// Creates a new async header by setting the protocol id and structure size initially. pub fn default() -> Self { AsyncHeader { generic: GenericHeader::default(), async_id: Vec::new(), session_id: Vec::new(), signature: Vec::new(), } } } impl std::fmt::Display for AsyncHeader { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Async Header:\n\t{:?}\n\t{:?}\n\t{:?}\n\t{:?}", self.generic, self.async_id, self.session_id, self.signature, ) } } /// The SMB header for synchronous messages. #[derive(Debug, PartialEq, Eq, Clone)] pub struct SyncHeader { /// Generic header fields that are equivalent for both sync and async headers. pub generic: GenericHeader, /// Reserved (4 bytes): The client SHOULD set this field to 0. /// The server MAY ignore this field on receipt. pub reserved: Vec<u8>, /// TreeId (4 bytes): Uniquely identifies the tree connect for the command. /// This MUST be 0 for the SMB2 TREE_CONNECT Request. The TreeId can be /// any unsigned 32-bit integer that is received from a previous SMB2 TREE_CONNECT Response. /// TreeId SHOULD be set to 0 for the following commands: /// - SMB2 NEGOTIATE Request /// - SMB2 NEGOTIATE Response /// - SMB2 SESSION_SETUP Request /// - SMB2 SESSION_SETUP Response /// - SMB2 LOGOFF Request /// - SMB2 LOGOFF Response /// - SMB2 ECHO Request /// - SMB2 ECHO Response /// - SMB2 CANCEL Request pub tree_id: Vec<u8>, /// SessionId (8 bytes): Uniquely identifies the established session for the command. /// This field MUST be set to 0 for an SMB2 NEGOTIATE Request and for an SMB2 NEGOTIATE Response. pub session_id: Vec<u8>, /// Signature (16 bytes): The 16-byte signature of the message, if SMB2_FLAGS_SIGNED /// is set in the Flags field of the SMB2 header and the message is not encrypted. /// If the message is not signed, this field MUST be 0. pub signature: Vec<u8>, } impl SyncHeader { /// Creates a new sync header by setting the protocol id and structure size initially. pub fn default() -> Self { SyncHeader { generic: GenericHeader::default(), reserved: b"\x00\x00\x00\x00".to_vec(), tree_id: Vec::new(), session_id: Vec::new(), signature: Vec::new(), } } } impl std::fmt::Display for SyncHeader { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Sync Header: \n\t{}\n\t{:?}\n\t{:?}\n\t{:?}\n\t{:?}", self.generic, self.reserved, self.tree_id, self.session_id, self.signature, ) } }
use ggez::graphics; use components::*; use sprite::*; #[derive(Debug)] pub struct Renderable { pub pos: Position, pub render: EntityRender, } impl Renderable { pub fn new(pos: Position, render: EntityRender) -> Self { Renderable { pos, render } } } impl SpriteComponent for Renderable { fn setup_sprite(&self, sprite: &mut Sprite) { if self.render.frame != sprite.frame() { sprite.set_frame(self.render.frame); } sprite.sprite_batch.clear(); let mut params = graphics::DrawParam::default(); params.src = sprite.uvs[sprite.frame()]; sprite.sprite_batch.add(params); } fn draw_sprite_at(&self) -> graphics::Point2 { self.pos.0.clone() } }
use std::collections::HashMap; use rbatis_core::Error; use crate::ast::node::node_type::NodeType; pub trait ToResult<T> { fn to_result<F>(&self, fail_method: F) -> Result<&T, Error> where F: Fn() -> String; } impl<T> ToResult<T> for Option<&T> { #[inline] fn to_result<F>(&self, fail_method: F) -> Result<&T, Error> where F: Fn() -> String { if self.is_none() { return Err(Error::from(fail_method())); } return Ok(self.unwrap()); } } #[test] fn test_to_result() { let i = 1; let v = Option::Some(&i); let r = v.to_result(|| "".to_string()); }
//! Tests for `#[derive(GraphQLInterface)]` macro. pub mod common; use std::marker::PhantomData; use juniper::{ execute, graphql_object, graphql_value, graphql_vars, DefaultScalarValue, FieldError, FieldResult, GraphQLInterface, GraphQLObject, GraphQLUnion, IntoFieldError, ScalarValue, ID, }; use self::common::util::{schema, schema_with_scalar}; mod no_implers { use super::*; #[derive(GraphQLInterface)] struct Character { id: String, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { unimplemented!() } } #[tokio::test] async fn is_graphql_interface() { const DOC: &str = r#"{ __type(name: "Character") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INTERFACE"}}), vec![])), ); } #[tokio::test] async fn uses_struct_name() { const DOC: &str = r#"{ __type(name: "Character") { name } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Character"}}), vec![])), ); } #[tokio::test] async fn has_no_description() { const DOC: &str = r#"{ __type(name: "Character") { description } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"description": null}}), vec![])), ); } } mod trivial { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue)] impl Droid { async fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } #[tokio::test] async fn is_graphql_interface() { const DOC: &str = r#"{ __type(name: "Character") { kind } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INTERFACE"}}), vec![])), ); } #[tokio::test] async fn registers_all_implementers() { const DOC: &str = r#"{ __type(name: "Character") { possibleTypes { kind name } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"possibleTypes": [ {"kind": "OBJECT", "name": "Droid"}, {"kind": "OBJECT", "name": "Human"}, ]}}), vec![], )), ); } #[tokio::test] async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); for object in ["Human", "Droid"] { let doc = format!( r#"{{ __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, ); assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"interfaces": [ {"kind": "INTERFACE", "name": "Character"}, ]}}), vec![], )), ); } } #[tokio::test] async fn uses_struct_name() { const DOC: &str = r#"{ __type(name: "Character") { name } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Character"}}), vec![])), ); } #[tokio::test] async fn has_no_description() { const DOC: &str = r#"{ __type(name: "Character") { description } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"description": null}}), vec![])), ); } } mod explicit_alias { use super::*; #[derive(GraphQLInterface)] #[graphql(enum = CharacterEnum, for = [Human, Droid])] struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterEnum)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterEnum)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterEnum { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } #[tokio::test] async fn is_graphql_interface() { const DOC: &str = r#"{ __type(name: "Character") { kind } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INTERFACE"}}), vec![])), ); } #[tokio::test] async fn uses_struct_name() { const DOC: &str = r#"{ __type(name: "Character") { name } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Character"}}), vec![])), ); } #[tokio::test] async fn has_no_description() { const DOC: &str = r#"{ __type(name: "Character") { description } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"description": null}}), vec![])), ); } } mod trivial_async { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue)] impl Droid { async fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } #[tokio::test] async fn is_graphql_interface() { const DOC: &str = r#"{ __type(name: "Character") { kind } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INTERFACE"}}), vec![])), ); } #[tokio::test] async fn registers_all_implementers() { const DOC: &str = r#"{ __type(name: "Character") { possibleTypes { kind name } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"possibleTypes": [ {"kind": "OBJECT", "name": "Droid"}, {"kind": "OBJECT", "name": "Human"}, ]}}), vec![], )), ); } #[tokio::test] async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); for object in ["Human", "Droid"] { let doc = format!( r#"{{ __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, ); assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"interfaces": [ {"kind": "INTERFACE", "name": "Character"}, ]}}), vec![], )), ); } } #[tokio::test] async fn uses_struct_name() { const DOC: &str = r#"{ __type(name: "Character") { name } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Character"}}), vec![])), ); } #[tokio::test] async fn has_no_description() { const DOC: &str = r#"{ __type(name: "Character") { description } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"description": null}}), vec![])), ); } } mod fallible_field { use super::*; struct CustomError; impl<S: ScalarValue> IntoFieldError<S> for CustomError { fn into_field_error(self) -> FieldError<S> { FieldError::new("Whatever", graphql_value!({"code": "some"})) } } #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character { id: Result<String, CustomError>, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue)] impl Droid { fn id(&self) -> Result<String, CustomError> { Ok(self.id.clone()) } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } #[tokio::test] async fn has_correct_graphql_type() { const DOC: &str = r#"{ __type(name: "Character") { name kind fields { name type { kind ofType { name } } } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "name": "Character", "kind": "INTERFACE", "fields": [{ "name": "id", "type": { "kind": "NON_NULL", "ofType": {"name": "String"}, }, }], }}), vec![], )), ); } } mod generic { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character<A = (), B: ?Sized = ()> { id: String, #[graphql(skip)] _phantom: PhantomData<(A, B)>, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue<(), u8>)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } #[tokio::test] async fn uses_struct_name_without_type_params() { const DOC: &str = r#"{ __type(name: "Character") { name } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Character"}}), vec![])), ); } } mod description_from_doc_comment { use super::*; /// Rust docs. #[derive(GraphQLInterface)] #[graphql(for = Human)] struct Character { /// Rust `id` docs. /// Long. id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { Human { id: "human-32".into(), home_planet: "earth".into(), } .into() } } #[tokio::test] async fn uses_doc_comment_as_description() { const DOC: &str = r#"{ __type(name: "Character") { description fields { description } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "description": "Rust docs.", "fields": [{"description": "Rust `id` docs.\nLong."}], }}), vec![], )), ); } } mod deprecation_from_attr { use super::*; #[derive(GraphQLInterface)] #[graphql(for = Human)] struct Character { id: String, #[deprecated] a: String, #[deprecated(note = "Use `id`.")] b: String, } struct Human { id: String, home_planet: String, } #[graphql_object(impl = CharacterValue)] impl Human { fn id(&self) -> &str { &self.id } fn human_planet(&self) -> &str { &self.home_planet } fn a() -> &'static str { "a" } fn b() -> String { "b".into() } } struct QueryRoot; #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { Human { id: "human-32".into(), home_planet: "earth".into(), } .into() } } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": "human-32"}}), vec![])), ); } #[tokio::test] async fn resolves_deprecated_fields() { const DOC: &str = r#"{ character { a b } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"a": "a", "b": "b"}}), vec![])), ); } #[tokio::test] async fn deprecates_fields() { const DOC: &str = r#"{ __type(name: "Character") { fields(includeDeprecated: true) { name isDeprecated } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"fields": [ {"name": "id", "isDeprecated": false}, {"name": "a", "isDeprecated": true}, {"name": "b", "isDeprecated": true}, ]}}), vec![], )), ); } #[tokio::test] async fn provides_deprecation_reason() { const DOC: &str = r#"{ __type(name: "Character") { fields(includeDeprecated: true) { name deprecationReason } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"fields": [ {"name": "id", "deprecationReason": null}, {"name": "a", "deprecationReason": null}, {"name": "b", "deprecationReason": "Use `id`."}, ]}}), vec![], )), ); } } mod explicit_name_description_and_deprecation { use super::*; /// Rust docs. #[derive(GraphQLInterface)] #[graphql(name = "MyChar", desc = "My character.", for = Human)] struct Character { /// Rust `id` docs. #[graphql(name = "myId", desc = "My character ID.", deprecated = "Not used.")] #[deprecated(note = "Should be omitted.")] id: String, #[graphql(deprecated)] #[deprecated(note = "Should be omitted.")] a: String, b: String, } struct Human { id: String, home_planet: String, } #[graphql_object(impl = CharacterValue)] impl Human { fn my_id(&self, #[graphql(name = "myName")] _: Option<String>) -> &str { &self.id } fn home_planet(&self) -> &str { &self.home_planet } fn a() -> String { "a".into() } fn b() -> &'static str { "b" } } struct QueryRoot; #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { Human { id: "human-32".into(), home_planet: "earth".into(), } .into() } } #[tokio::test] async fn resolves_fields() { const DOC: &str = r#"{ character { myId a b } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "myId": "human-32", "a": "a", "b": "b", }}), vec![], )), ); } #[tokio::test] async fn uses_custom_name() { const DOC: &str = r#"{ __type(name: "MyChar") { name fields(includeDeprecated: true) { name args { name } } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "name": "MyChar", "fields": [ {"name": "myId", "args": []}, {"name": "a", "args": []}, {"name": "b", "args": []}, ], }}), vec![], )), ); } #[tokio::test] async fn uses_custom_description() { const DOC: &str = r#"{ __type(name: "MyChar") { description fields(includeDeprecated: true) { name description args { description } } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "description": "My character.", "fields": [{ "name": "myId", "description": "My character ID.", "args": [], }, { "name": "a", "description": null, "args": [], }, { "name": "b", "description": null, "args": [], }], }}), vec![], )), ); } #[tokio::test] async fn uses_custom_deprecation() { const DOC: &str = r#"{ __type(name: "MyChar") { fields(includeDeprecated: true) { name isDeprecated deprecationReason } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "fields": [{ "name": "myId", "isDeprecated": true, "deprecationReason": "Not used.", }, { "name": "a", "isDeprecated": true, "deprecationReason": null, }, { "name": "b", "isDeprecated": false, "deprecationReason": null, }], }}), vec![], )), ); } } mod renamed_all_fields_and_args { use super::*; #[derive(GraphQLInterface)] #[graphql(rename_all = "none", for = Human)] struct Character { id: String, } struct Human; #[graphql_object(rename_all = "none", impl = CharacterValue)] impl Human { fn id() -> &'static str { "human-32" } } struct QueryRoot; #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { Human.into() } } #[tokio::test] async fn resolves_fields() { const DOC: &str = r#"{ character { id } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "id": "human-32", }}), vec![], )), ); } #[tokio::test] async fn uses_correct_fields_and_args_names() { const DOC: &str = r#"{ __type(name: "Character") { fields { name args { name } } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"fields": [ {"name": "id", "args": []}, ]}}), vec![], )), ); } } mod explicit_scalar { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] #[graphql(scalar = DefaultScalarValue)] struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue, scalar = DefaultScalarValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue, scalar = DefaultScalarValue)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object(scalar = DefaultScalarValue)] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } } mod custom_scalar { use crate::common::MyScalarValue; use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid], scalar = MyScalarValue)] struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue, scalar = MyScalarValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue, scalar = MyScalarValue)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object(scalar = MyScalarValue)] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema_with_scalar::<MyScalarValue, _, _>(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema_with_scalar::<MyScalarValue, _, _>(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema_with_scalar::<MyScalarValue, _, _>(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } } mod explicit_generic_scalar { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid], scalar = S)] struct Character<S: ScalarValue = DefaultScalarValue> { id: FieldResult<String, S>, } #[derive(GraphQLObject)] #[graphql(scalar = S: ScalarValue, impl = CharacterValue<S>)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue<__S>)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object(scalar = S: ScalarValue)] impl QueryRoot { fn character<S: ScalarValue>(&self) -> CharacterValue<S> { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } } mod bounded_generic_scalar { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid], scalar = S: ScalarValue + Clone)] struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue, scalar = S: ScalarValue + Clone)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue, scalar = S: ScalarValue + Clone)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } } mod ignored_method { use super::*; #[derive(GraphQLInterface)] #[graphql(for = Human)] struct Character { id: String, #[graphql(ignore)] ignored: Option<Human>, #[graphql(skip)] skipped: i32, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { Human { id: "human-32".into(), home_planet: "earth".into(), } .into() } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": "human-32"}}), vec![])), ); } #[tokio::test] async fn is_not_field() { const DOC: &str = r#"{ __type(name: "Character") { fields { name } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"fields": [{"name": "id"}]}}), vec![], )), ); } } mod field_return_subtyping { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character { id: Option<String>, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } } mod field_return_union_subtyping { use super::*; #[derive(GraphQLObject)] struct Strength { value: i32, } #[derive(GraphQLObject)] struct Knowledge { value: i32, } #[allow(dead_code)] #[derive(GraphQLUnion)] enum KeyFeature { Strength(Strength), Knowledge(Knowledge), } #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character { id: Option<String>, key_feature: KeyFeature, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, key_feature: Knowledge, } struct Droid { id: String, primary_function: String, strength: i32, } #[graphql_object(impl = CharacterValue)] impl Droid { fn id(&self) -> &str { &self.id } fn primary_function(&self) -> &str { &self.primary_function } fn key_feature(&self) -> Strength { Strength { value: self.strength, } } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), key_feature: Knowledge { value: 10 }, } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), strength: 42, } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet keyFeature { value } } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", "keyFeature": {"value": 10}, }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id primaryFunction keyFeature { value } } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", "keyFeature": {"value": 42}, }}), vec![], )), ); } #[tokio::test] async fn resolves_fields() { const DOC: &str = r#"{ character { id keyFeature { ...on Strength { value } ... on Knowledge { value } } } }"#; for (root, expected_id, expected_val) in [ (QueryRoot::Human, "human-32", 10), (QueryRoot::Droid, "droid-99", 42), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "id": expected_id, "keyFeature": {"value": expected_val}, }}), vec![], )), ); } } } mod nullable_argument_subtyping { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [Human, Droid])] struct Character { id: Option<String>, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { id: String, home_planet: String, } struct Droid { id: String, primary_function: String, } #[graphql_object(impl = CharacterValue)] impl Droid { fn id(&self, is_present: Option<bool>) -> &str { is_present .unwrap_or_default() .then_some(&*self.id) .unwrap_or("missing") } fn primary_function(&self) -> &str { &self.primary_function } } #[derive(Clone, Copy)] enum QueryRoot { Human, Droid, } #[graphql_object] impl QueryRoot { fn character(&self) -> CharacterValue { match self { Self::Human => Human { id: "human-32".into(), home_planet: "earth".into(), } .into(), Self::Droid => Droid { id: "droid-99".into(), primary_function: "run".into(), } .into(), } } } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ character { ... on Human { humanId: id homePlanet } } }"#; let schema = schema(QueryRoot::Human); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "humanId": "human-32", "homePlanet": "earth", }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ character { ... on Droid { droidId: id(isPresent: true) primaryFunction } } }"#; let schema = schema(QueryRoot::Droid); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "droidId": "droid-99", "primaryFunction": "run", }}), vec![], )), ); } #[tokio::test] async fn resolves_id_field() { const DOC: &str = r#"{ character { id } }"#; for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "missing"), ] { let schema = schema(root); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), ); } } } mod simple_subtyping { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [ResourceValue, Endpoint])] struct Node { id: Option<ID>, } #[derive(GraphQLInterface)] #[graphql(impl = NodeValue, for = Endpoint)] struct Resource { id: ID, url: Option<String>, } #[derive(GraphQLObject)] #[graphql(impl = [ResourceValue, NodeValue])] struct Endpoint { id: ID, url: String, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn node() -> NodeValue { Endpoint { id: ID::new("1"), url: "2".into(), } .into() } fn resource() -> ResourceValue { Endpoint { id: ID::new("3"), url: "4".into(), } .into() } } #[tokio::test] async fn is_graphql_interface() { for name in ["Node", "Resource"] { let doc = format!( r#"{{ __type(name: "{name}") {{ kind }} }}"#, ); let schema = schema(QueryRoot); assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INTERFACE"}}), vec![])), ); } } #[tokio::test] async fn resolves_node() { const DOC: &str = r#"{ node { id } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"node": {"id": "1"}}), vec![])), ); } #[tokio::test] async fn resolves_node_on_resource() { const DOC: &str = r#"{ node { ... on Resource { id url } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"node": { "id": "1", "url": "2", }}), vec![], )), ); } #[tokio::test] async fn resolves_node_on_endpoint() { const DOC: &str = r#"{ node { ... on Endpoint { id url } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"node": { "id": "1", "url": "2", }}), vec![], )), ); } #[tokio::test] async fn resolves_resource() { const DOC: &str = r#"{ resource { id url } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"resource": { "id": "3", "url": "4", }}), vec![], )), ); } #[tokio::test] async fn resolves_resource_on_endpoint() { const DOC: &str = r#"{ resource { ... on Endpoint { id url } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"resource": { "id": "3", "url": "4", }}), vec![], )), ); } #[tokio::test] async fn registers_possible_types() { for name in ["Node", "Resource"] { let doc = format!( r#"{{ __type(name: "{name}") {{ possibleTypes {{ kind name }} }} }}"#, ); let schema = schema(QueryRoot); assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"possibleTypes": [ {"kind": "OBJECT", "name": "Endpoint"}, ]}}), vec![], )), ); } } #[tokio::test] async fn registers_interfaces() { let schema = schema(QueryRoot); for (name, interfaces) in [ ("Node", graphql_value!([])), ( "Resource", graphql_value!([{"kind": "INTERFACE", "name": "Node"}]), ), ( "Endpoint", graphql_value!([ {"kind": "INTERFACE", "name": "Node"}, {"kind": "INTERFACE", "name": "Resource"}, ]), ), ] { let doc = format!( r#"{{ __type(name: "{name}") {{ interfaces {{ kind name }} }} }}"#, ); assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"interfaces": interfaces}}), vec![], )), ); } } } mod branching_subtyping { use super::*; #[derive(GraphQLInterface)] #[graphql(for = [HumanValue, DroidValue, Luke, R2D2])] struct Node { id: ID, } #[derive(GraphQLInterface)] #[graphql(for = [HumanConnection, DroidConnection])] struct Connection { nodes: Vec<NodeValue>, } #[derive(GraphQLInterface)] #[graphql(impl = NodeValue, for = Luke)] struct Human { id: ID, home_planet: String, } #[derive(GraphQLObject)] #[graphql(impl = ConnectionValue)] struct HumanConnection { nodes: Vec<HumanValue>, } #[derive(GraphQLInterface)] #[graphql(impl = NodeValue, for = R2D2)] struct Droid { id: ID, primary_function: String, } #[derive(GraphQLObject)] #[graphql(impl = ConnectionValue)] struct DroidConnection { nodes: Vec<DroidValue>, } #[derive(GraphQLObject)] #[graphql(impl = [HumanValue, NodeValue])] struct Luke { id: ID, home_planet: String, father: String, } #[derive(GraphQLObject)] #[graphql(impl = [DroidValue, NodeValue])] struct R2D2 { id: ID, primary_function: String, charge: f64, } enum QueryRoot { Luke, R2D2, } #[graphql_object] impl QueryRoot { fn crew(&self) -> ConnectionValue { match self { Self::Luke => HumanConnection { nodes: vec![Luke { id: ID::new("1"), home_planet: "earth".into(), father: "SPOILER".into(), } .into()], } .into(), Self::R2D2 => DroidConnection { nodes: vec![R2D2 { id: ID::new("2"), primary_function: "roll".into(), charge: 146.0, } .into()], } .into(), } } } #[tokio::test] async fn is_graphql_interface() { for name in ["Node", "Connection", "Human", "Droid"] { let doc = format!( r#"{{ __type(name: "{name}") {{ kind }} }}"#, ); let schema = schema(QueryRoot::Luke); assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INTERFACE"}}), vec![])), ); } } #[tokio::test] async fn resolves_human_connection() { const DOC: &str = r#"{ crew { ... on HumanConnection { nodes { id homePlanet } } } }"#; let schema = schema(QueryRoot::Luke); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"crew": { "nodes": [{ "id": "1", "homePlanet": "earth", }], }}), vec![], )), ); } #[tokio::test] async fn resolves_human() { const DOC: &str = r#"{ crew { nodes { ... on Human { id homePlanet } } } }"#; let schema = schema(QueryRoot::Luke); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"crew": { "nodes": [{ "id": "1", "homePlanet": "earth", }], }}), vec![], )), ); } #[tokio::test] async fn resolves_luke() { const DOC: &str = r#"{ crew { nodes { ... on Luke { id homePlanet father } } } }"#; let schema = schema(QueryRoot::Luke); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"crew": { "nodes": [{ "id": "1", "homePlanet": "earth", "father": "SPOILER", }], }}), vec![], )), ); } #[tokio::test] async fn resolves_droid_connection() { const DOC: &str = r#"{ crew { ... on DroidConnection { nodes { id primaryFunction } } } }"#; let schema = schema(QueryRoot::R2D2); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"crew": { "nodes": [{ "id": "2", "primaryFunction": "roll", }], }}), vec![], )), ); } #[tokio::test] async fn resolves_droid() { const DOC: &str = r#"{ crew { nodes { ... on Droid { id primaryFunction } } } }"#; let schema = schema(QueryRoot::R2D2); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"crew": { "nodes": [{ "id": "2", "primaryFunction": "roll", }], }}), vec![], )), ); } #[tokio::test] async fn resolves_r2d2() { const DOC: &str = r#"{ crew { nodes { ... on R2D2 { id primaryFunction charge } } } }"#; let schema = schema(QueryRoot::R2D2); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"crew": { "nodes": [{ "id": "2", "primaryFunction": "roll", "charge": 146.0, }], }}), vec![], )), ); } } mod preserves_visibility { use super::*; #[allow(dead_code)] type Foo = self::inner::CharacterValue; pub(crate) mod inner { use super::*; #[derive(GraphQLInterface)] #[graphql(for = Human)] pub(crate) struct Character { id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] pub(crate) struct Human { id: String, home_planet: String, } } } mod has_no_missing_docs { #![deny(missing_docs)] use super::*; #[derive(GraphQLInterface)] #[graphql(for = Human)] pub struct Character { pub id: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] pub struct Human { id: String, home_planet: String, } }
//给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? // // 示例: // // 输入: 3 //输出: 5 //解释: //给定 n = 3, 一共有 5 种不同结构的二叉搜索树: // // 1 3 3 2 1 // \ / / / \ \ // 3 2 1 1 3 2 // / / \ \ // 2 1 2 3 // Related Topics 树 动态规划 //leetcode submit region begin(Prohibit modification and deletion) impl Solution { pub fn num_trees(n: i32) -> i32 { let n = n as usize; let mut dp = vec![0; n + 1]; dp[0] = 1; dp[1] = 1; /** * dp[i] =dp[0]*dp[i-1] + dp[1]*dp[i-2] + dp[2]*dp[i-3]+ ... + dp[i-1]*dp[0] */ for i in 1..=n { let mut res = 0; for j in 0..i { res += dp[j] * dp[i - 1 - j]; } dp[i] = res; } return dp[n]; } } //leetcode submit region end(Prohibit modification and deletion) fn main() { let i = Solution::num_trees(3); dbg!(i); } struct Solution {}
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib_sys; use libc; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; use DOMDOMWindow; use DOMDocument; use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; glib_wrapper! { pub struct DOMHTMLFrameElement(Object<webkit2_webextension_sys::WebKitDOMHTMLFrameElement, webkit2_webextension_sys::WebKitDOMHTMLFrameElementClass, DOMHTMLFrameElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { get_type => || webkit2_webextension_sys::webkit_dom_html_frame_element_get_type(), } } pub const NONE_DOMHTML_FRAME_ELEMENT: Option<&DOMHTMLFrameElement> = None; pub trait DOMHTMLFrameElementExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_content_document(&self) -> Option<DOMDocument>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_content_window(&self) -> Option<DOMDOMWindow>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_frame_border(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_height(&self) -> libc::c_long; #[cfg_attr(feature = "v2_22", deprecated)] fn get_long_desc(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_margin_height(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_margin_width(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_name(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_no_resize(&self) -> bool; #[cfg_attr(feature = "v2_22", deprecated)] fn get_scrolling(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_src(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_width(&self) -> libc::c_long; #[cfg_attr(feature = "v2_22", deprecated)] fn set_frame_border(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_long_desc(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_margin_height(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_margin_width(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_name(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_no_resize(&self, value: bool); #[cfg_attr(feature = "v2_22", deprecated)] fn set_scrolling(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_src(&self, value: &str); fn connect_property_content_document_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_content_window_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_frame_border_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_long_desc_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_margin_height_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_margin_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_no_resize_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_scrolling_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_src_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMHTMLFrameElement>> DOMHTMLFrameElementExt for O { fn get_content_document(&self) -> Option<DOMDocument> { unsafe { from_glib_none( webkit2_webextension_sys::webkit_dom_html_frame_element_get_content_document( self.as_ref().to_glib_none().0, ), ) } } fn get_content_window(&self) -> Option<DOMDOMWindow> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_content_window( self.as_ref().to_glib_none().0, ), ) } } fn get_frame_border(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_frame_border( self.as_ref().to_glib_none().0, ), ) } } fn get_height(&self) -> libc::c_long { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_get_height( self.as_ref().to_glib_none().0, ) } } fn get_long_desc(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_long_desc( self.as_ref().to_glib_none().0, ), ) } } fn get_margin_height(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_margin_height( self.as_ref().to_glib_none().0, ), ) } } fn get_margin_width(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_margin_width( self.as_ref().to_glib_none().0, ), ) } } fn get_name(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_name( self.as_ref().to_glib_none().0, ), ) } } fn get_no_resize(&self) -> bool { unsafe { from_glib( webkit2_webextension_sys::webkit_dom_html_frame_element_get_no_resize( self.as_ref().to_glib_none().0, ), ) } } fn get_scrolling(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_scrolling( self.as_ref().to_glib_none().0, ), ) } } fn get_src(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_frame_element_get_src( self.as_ref().to_glib_none().0, ), ) } } fn get_width(&self) -> libc::c_long { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_get_width( self.as_ref().to_glib_none().0, ) } } fn set_frame_border(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_frame_border( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_long_desc(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_long_desc( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_margin_height(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_margin_height( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_margin_width(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_margin_width( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_name(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_name( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_no_resize(&self, value: bool) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_no_resize( self.as_ref().to_glib_none().0, value.to_glib(), ); } } fn set_scrolling(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_scrolling( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_src(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_frame_element_set_src( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn connect_property_content_document_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_content_document_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::content-document\0".as_ptr() as *const _, Some(transmute( notify_content_document_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_content_window_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_content_window_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::content-window\0".as_ptr() as *const _, Some(transmute( notify_content_window_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_frame_border_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_frame_border_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::frame-border\0".as_ptr() as *const _, Some(transmute( notify_frame_border_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_height_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::height\0".as_ptr() as *const _, Some(transmute(notify_height_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_long_desc_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_long_desc_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::long-desc\0".as_ptr() as *const _, Some(transmute(notify_long_desc_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_margin_height_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_margin_height_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::margin-height\0".as_ptr() as *const _, Some(transmute( notify_margin_height_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_margin_width_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_margin_width_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::margin-width\0".as_ptr() as *const _, Some(transmute( notify_margin_width_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_name_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::name\0".as_ptr() as *const _, Some(transmute(notify_name_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_no_resize_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_no_resize_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::no-resize\0".as_ptr() as *const _, Some(transmute(notify_no_resize_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_scrolling_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_scrolling_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::scrolling\0".as_ptr() as *const _, Some(transmute(notify_scrolling_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_src_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_src_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::src\0".as_ptr() as *const _, Some(transmute(notify_src_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_width_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFrameElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFrameElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFrameElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::width\0".as_ptr() as *const _, Some(transmute(notify_width_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for DOMHTMLFrameElement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLFrameElement") } }
use cw::{BLOCK, Crosswords, Dir, Point}; /// An element representing a part of a crosswords grid: an element of the cell's borders, a cell /// and its contents or a line break. It should be converted to a textual or graphical /// representation. /// /// The variants specifying borders contain a boolean value specifying whether the border should be /// displayed as thick or thin, i. e. whether it separates different words or letters of a single /// word. pub enum PrintItem { /// A vertical border. VertBorder(bool), /// A horizontal border. HorizBorder(bool), /// A crossing point of borders. It is considered thick (value `true`) if at least two of the /// four lines crossing here are thick. Cross(bool), /// A solid block that is left empty in the crossword's solution. It does not belong to a word. Block, /// A cell that belongs to one or two words and contains the given character. If one or two /// words begin in this cell, the second value will be `n`, where this is the `n`-th cell /// containing the beginning of a word. CharHint(char, Option<u32>), /// A line break. This follows after every row of borders or cells. LineBreak, } /// An iterator over all `PrintItem`s representing a crosswords grid. pub struct PrintIter<'a> { point: Point, between_lines: bool, between_chars: bool, cw: &'a Crosswords, hint_count: u32, } impl<'a> PrintIter<'a> { pub fn new(cw: &'a Crosswords) -> Self { PrintIter { point: Point::new(-1, -1), between_lines: true, between_chars: true, cw: cw, hint_count: 0, } } } impl<'a> Iterator for PrintIter<'a> { type Item = PrintItem; fn next(&mut self) -> Option<PrintItem> { if self.point.y >= self.cw.height as i32 { return None; } let result; if self.point.x >= self.cw.width as i32 { result = PrintItem::LineBreak; self.point.x = -1; if self.between_lines { self.point.y += 1; } self.between_chars = true; self.between_lines = !self.between_lines; } else if self.between_chars { if self.between_lines { let mut count = 0; if self.cw.get_border(self.point, Dir::Down) { count += 1 } if self.cw.get_border(self.point, Dir::Right) { count += 1 } if self.cw .get_border(self.point + Point::new(1, 0), Dir::Down) { count += 1 } if self.cw .get_border(self.point + Point::new(0, 1), Dir::Right) { count += 1 } result = PrintItem::Cross(count > 1); } else { result = PrintItem::VertBorder(self.cw.get_border(self.point, Dir::Right)); } self.point.x += 1; self.between_chars = false; } else { if self.between_lines { result = PrintItem::HorizBorder(self.cw.get_border(self.point, Dir::Down)); } else { result = match self.cw.get_char(self.point).unwrap() { BLOCK => PrintItem::Block, c => { PrintItem::CharHint(c, if self.cw.has_hint_at(self.point) { self.hint_count += 1; Some(self.hint_count) } else { None }) } }; } self.between_chars = true; } Some(result) } }
// edition:2018 // revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir #![allow(non_snake_case)] use std::pin::Pin; struct Struct { } impl Struct { // Test using `&mut Struct` explicitly: async fn ref_Struct(self: &mut Struct, f: &u32) -> &u32 { f //[base]~^ ERROR lifetime mismatch //[nll]~^^ ERROR lifetime may not live long enough } async fn box_ref_Struct(self: Box<&mut Struct>, f: &u32) -> &u32 { f //[base]~^ ERROR lifetime mismatch //[nll]~^^ ERROR lifetime may not live long enough } async fn pin_ref_Struct(self: Pin<&mut Struct>, f: &u32) -> &u32 { f //[base]~^ ERROR lifetime mismatch //[nll]~^^ ERROR lifetime may not live long enough } async fn box_box_ref_Struct(self: Box<Box<&mut Struct>>, f: &u32) -> &u32 { f //[base]~^ ERROR lifetime mismatch //[nll]~^^ ERROR lifetime may not live long enough } async fn box_pin_ref_Struct(self: Box<Pin<&mut Struct>>, f: &u32) -> &u32 { f //[base]~^ ERROR lifetime mismatch //[nll]~^^ ERROR lifetime may not live long enough } } fn main() { }
use std::{io::{ErrorKind, Read}, str::FromStr}; use mysql::chrono::{NaiveDate, Utc}; use mysql_common::bigdecimal::BigDecimal; use toml::Value; #[derive(Debug)] pub struct Config { pub key: String, pub mysql_url: String, pub img_width: i32, pub img_height: i32, pub stocks: Vec<String>, pub start_date: NaiveDate, pub end_date: NaiveDate, pub start_depot: BigDecimal, pub avg200_range: f32, } impl Config { pub fn read_config() -> Self { let mut config_file = match std::fs::File::open("config.toml") { Ok(config) => config, Err(error) => match error.kind() { ErrorKind::NotFound => match std::fs::File::create("config.toml") { Ok(fc) => fc, Err(e) => panic!("Problem creating the config.toml file: {:?}", e), }, other_error => panic!("Problem opening the config file: {:?}", other_error) } }; let mut contents = String::new(); match config_file.read_to_string(&mut contents) { Ok(_) => {} Err(error) => panic!("Error reading config file: {}", error) } let config_toml = match contents.parse::<Value>() { Ok(toml) => toml, Err(error) => panic!("Please check your config.toml syntax: {}", error) }; let key = match config_toml.get("key") { Some(key) => key.as_str().unwrap(), None => &"asd" }; let mysql_url = match config_toml.get("mysql_url") { Some(url) => url.as_str().unwrap(), None => panic!("You need to specify a url in your config.toml! Example: mysql_url = 'mysql://root:password@localhost:3307/db_name'") }; let img_width = match config_toml.get("img_width") { Some(width) => width.as_integer().unwrap() as i32, None => 1280 as i32, }; let img_height = match config_toml.get("img_height") { Some(height) => height.as_integer().unwrap() as i32, None => 720 as i32, }; let _stocks = match config_toml.get("stocks") { Some(stocks) => stocks.as_array().unwrap(), None => panic!("You need to specify stocks to keep track of in your config.toml! Example: stocks = ['ibm', 'tsla']"), }; let mut stocks: Vec<String> = Vec::new(); for i in 0.._stocks.len() { stocks.push(String::from_str(_stocks[i].as_str().unwrap()).unwrap()); }; let start_date = match config_toml.get("img_start_date") { Some(start_date) => NaiveDate::parse_from_str(start_date.as_str().unwrap(), "%d-%m-%Y").unwrap(), None => NaiveDate::from_ymd(2020, 1, 1), }; let end_date = match config_toml.get("img_end_date") { Some(end_date) => NaiveDate::parse_from_str(end_date.as_str().unwrap(), "%d-%m-%Y").unwrap(), None => Utc::now().date().naive_utc(), }; let start_depot = match config_toml.get("depot") { Some(end_date) => BigDecimal::from_str(end_date.as_str().unwrap()).unwrap(), None => BigDecimal::from(100000), }; let avg200_range = match config_toml.get("avg200_range") { Some(end_date) => f32::from_str(end_date.as_str().unwrap()).unwrap(), None => 0.03, }; Config { key: String::from(key), mysql_url: String::from(mysql_url), img_width, img_height, stocks, start_date, end_date, start_depot, avg200_range } } }
use std::convert::TryFrom; use super::crypto; use super::SessionCrypto; pub const PACKET_MAX_MESSAGE_LEN: usize = 1024; const PACKET_MESSAGE_LEN_LEN: usize = 4; // u32 const PACKET_MESSAGE_ENCRYPTED_LEN: usize = PACKET_MAX_MESSAGE_LEN + PACKET_MESSAGE_LEN_LEN; pub const PACKET_MAC_LEN: usize = 256 / 8; // 32 pub const PACKET_LEN: usize = PACKET_MESSAGE_ENCRYPTED_LEN + PACKET_MAC_LEN; pub(crate) fn enpacket(crypto: &mut SessionCrypto, input: &[u8]) -> [u8; PACKET_LEN] { assert!(input.len() <= PACKET_MAX_MESSAGE_LEN); let mut packet = [0u8; PACKET_LEN]; (&mut packet[..input.len()]).copy_from_slice(input); let input_len = u32::try_from(input.len()).expect("<=1024"); packet[PACKET_MAX_MESSAGE_LEN..PACKET_MESSAGE_ENCRYPTED_LEN] .copy_from_slice(&input_len.to_be_bytes()); let packet_number = crypto::aes_ctr(crypto, &mut packet[..PACKET_MESSAGE_ENCRYPTED_LEN]); let mac = { use crypto_mac::Mac; let mut computer = crypto.mac.begin(); computer.input(&packet[..PACKET_MESSAGE_ENCRYPTED_LEN]); computer.input(&packet_number.to_be_bytes()); computer.result().code() }; (&mut packet[PACKET_MESSAGE_ENCRYPTED_LEN..]).copy_from_slice(&mac); packet } pub(crate) fn unpacket<'s, 'p>( crypto: &'s mut SessionCrypto, packet: &'p mut [u8], ) -> Result<&'p [u8], &'static str> { use std::convert::TryInto as _; assert_eq!(packet.len(), PACKET_LEN); // msg_padded: [ message ] [ padded up to 1024 bytes ] [ length: 4 bytes ] // msg_encrypted: encrypt(msg_padded) // payload: [ msg_encrypted ] [ mac([ msg_encrypted ] [ packet number: 8 bytes ]): // copy the mac out of the read buffer let (msg_encrypted, mac_actual) = packet.as_mut().split_at_mut(PACKET_MESSAGE_ENCRYPTED_LEN); let mac_expected = { use crypto_mac::Mac; let mut computer = crypto.mac.begin(); computer.input(msg_encrypted); computer.input(&crypto.packet_number.to_be_bytes()); computer.result().code() }; use subtle::ConstantTimeEq as _; if 1 != mac_expected.ct_eq(&mac_actual).unwrap_u8() { return Err("packet mac bad"); } crypto::aes_ctr(crypto, msg_encrypted); let actual_len = u32::from_be_bytes( msg_encrypted[PACKET_MAX_MESSAGE_LEN..] .try_into() .expect("fixed size slice"), ); if actual_len == 0 || actual_len > (PACKET_MAX_MESSAGE_LEN as u32) { return Err("invalid len"); } let actual_len = usize::try_from(actual_len).expect("<=1024"); if !msg_encrypted[actual_len..PACKET_MAX_MESSAGE_LEN] .iter() .all(|&x| 0 == x) { return Err("invalid padding"); } Ok(&msg_encrypted[..actual_len]) }
use std::{fmt::Debug, num::NonZeroUsize, sync::Arc}; use client_util::{connection::HttpConnection, namespace_translation::split_namespace}; use futures_util::{future::BoxFuture, FutureExt, Stream, StreamExt, TryStreamExt}; use crate::{ connection::Connection, error::{translate_response, Error}, }; use reqwest::{Body, Method}; /// The default value for the maximum size of each request, in bytes pub const DEFAULT_MAX_REQUEST_PAYLOAD_SIZE_BYTES: Option<usize> = Some(1024 * 1024); /// An IOx Write API client. /// /// ```no_run /// #[tokio::main] /// # async fn main() { /// use influxdb_iox_client::{ /// write::Client, /// connection::Builder, /// }; /// /// let connection = Builder::default() /// .build("http://127.0.0.1:8080") /// .await /// .unwrap(); /// /// let mut client = Client::new(connection); /// /// // write a line of line protocol data /// client /// .write_lp("fruit_bananas", "cpu,region=west user=23.2 100") /// .await /// .expect("failed to write to IOx"); /// # } /// ``` #[derive(Debug, Clone)] pub struct Client { /// The inner client used to actually make requests. /// /// Uses a trait for test mocking. /// /// Does not expose the trait in the `Client` type to avoid /// exposing an internal implementation detail (the trait) in the /// public interface. inner: Arc<dyn RequestMaker>, /// If `Some`, restricts the maximum amount of line protocol /// sent per request to this many bytes. If `None`, does not restrict /// the amount sent per request. Defaults to `Some(1MB)` /// /// Splitting the upload size consumes a non trivial amount of CPU /// to find line protocol boundaries. This can be disabled by /// setting `max_request_payload_size_bytes` to `None`. max_request_payload_size_bytes: Option<usize>, /// Makes this many concurrent requests at a time. Defaults to 1 max_concurrent_uploads: NonZeroUsize, } impl Client { /// Creates a new client with the provided connection pub fn new(connection: Connection) -> Self { Self::new_with_maker(Arc::new(connection.into_http_connection())) } /// Creates a new client with the provided request maker fn new_with_maker(inner: Arc<dyn RequestMaker>) -> Self { Self { inner, max_request_payload_size_bytes: DEFAULT_MAX_REQUEST_PAYLOAD_SIZE_BYTES, max_concurrent_uploads: NonZeroUsize::new(1).unwrap(), } } /// Override the default of sending 1MB of line protocol per request. /// If `Some` is specified, restricts the maximum amount of line protocol /// sent per request to this many bytes. If `None`, does not restrict the amount of /// line protocol sent per request. pub fn with_max_request_payload_size_bytes( self, max_request_payload_size_bytes: Option<usize>, ) -> Self { Self { max_request_payload_size_bytes, ..self } } /// The client makes this many concurrent uploads at a /// time. Defaults to 1. pub fn with_max_concurrent_uploads(self, max_concurrent_uploads: NonZeroUsize) -> Self { Self { max_concurrent_uploads, ..self } } /// Write the [LineProtocol] formatted string in `lp_data` to /// namespace `namespace`. /// /// Returns the number of bytes which were written to the namespace. /// /// [LineProtocol]: https://docs.influxdata.com/influxdb/v2.0/reference/syntax/line-protocol/#data-types-and-format pub async fn write_lp( &mut self, namespace: impl AsRef<str> + Send, lp_data: impl Into<String> + Send, ) -> Result<usize, Error> { let sources = futures_util::stream::iter([lp_data.into()]); self.write_lp_stream(namespace, sources).await } /// Write the stream of [LineProtocol] formatted strings in /// `sources` to namespace `namespace`. It is assumed that /// individual lines (points) do not cross these strings /// /// Returns the number of bytes, in total, which were written to /// the namespace. /// /// [LineProtocol]: https://docs.influxdata.com/influxdb/v2.0/reference/syntax/line-protocol/#data-types-and-format pub async fn write_lp_stream( &mut self, namespace: impl AsRef<str> + Send, sources: impl Stream<Item = String> + Send, ) -> Result<usize, Error> { let (org_id, bucket_id) = split_namespace(namespace.as_ref()).map_err(|e| { Error::invalid_argument( "namespace", format!("Could not find valid org_id and bucket_id: {e}"), ) })?; let max_concurrent_uploads: usize = self.max_concurrent_uploads.into(); let max_request_payload_size_bytes = self.max_request_payload_size_bytes; // make a stream and process in parallel let results = sources // split each input source in parallel, if possible .flat_map(|source| { split_lp( source, max_request_payload_size_bytes, max_concurrent_uploads, ) }) // do the actual write .map(|source| { let org_id = org_id.to_string(); let bucket_id = bucket_id.to_string(); let inner = Arc::clone(&self.inner); tokio::task::spawn( async move { inner.write_source(org_id, bucket_id, source).await }, ) }) // Do the uploads in parallel .buffered(max_concurrent_uploads) .try_collect::<Vec<_>>() // handle panics in tasks .await .map_err(Error::client)? // find / return any errors .into_iter() .collect::<Result<Vec<_>, Error>>()?; Ok(results.into_iter().sum()) } } /// Something that knows how to send http data. Exists so it can be /// mocked out for testing trait RequestMaker: Debug + Send + Sync { /// Write the body data to the specified org, bucket, and /// returning the number of bytes written /// /// (this is implemented manually to avoid `async_trait`) fn write_source( &self, org_id: String, bucket_id: String, body: String, ) -> BoxFuture<'_, Result<usize, Error>>; } impl RequestMaker for HttpConnection { fn write_source( &self, org_id: String, bucket_id: String, body: String, ) -> BoxFuture<'_, Result<usize, Error>> { let write_url = format!("{}api/v2/write", self.uri()); async move { let body: Body = body.into(); let data_len = body.as_bytes().map(|b| b.len()).unwrap_or(0); let response = self .client() .request(Method::POST, &write_url) .query(&[("bucket", bucket_id), ("org", org_id)]) .body(body) .send() .await .map_err(Error::client)?; translate_response(response).await?; Ok(data_len) } .boxed() } } /// splits input line protocol into one or more sizes of at most /// `max_chunk` on line breaks in a separte tokio task fn split_lp( input: String, max_chunk_size: Option<usize>, max_concurrent_uploads: usize, ) -> impl Stream<Item = String> { let (tx, rx) = tokio::sync::mpsc::channel(max_concurrent_uploads); tokio::task::spawn(async move { match max_chunk_size { None => { // ignore errors (means the receiver hung up but nothing to communicate tx.send(input).await.ok(); } Some(max_chunk_size) => { // use the actual line protocol parser to split on valid boundaries let mut acc = LineAccumulator::new(max_chunk_size); for l in influxdb_line_protocol::split_lines(&input) { if let Some(chunk) = acc.push(l) { // abort if receiver has hungup if tx.send(chunk).await.is_err() { return; } } } if let Some(chunk) = acc.flush() { tx.send(chunk).await.ok(); } } } }); tokio_stream::wrappers::ReceiverStream::new(rx) } #[derive(Debug)] struct LineAccumulator { current_chunk: String, max_chunk_size: usize, } impl LineAccumulator { fn new(max_chunk_size: usize) -> Self { Self { current_chunk: String::with_capacity(max_chunk_size), max_chunk_size, } } // Add data `l` to the current chunk being created, returning the // current chunk if complete. fn push(&mut self, l: &str) -> Option<String> { let chunk = if self.current_chunk.len() + l.len() + 1 > self.max_chunk_size { self.flush() } else { None }; if !self.current_chunk.is_empty() { self.current_chunk += "\n"; } self.current_chunk += l; chunk } /// allocate a new chunk with the right size, returning the currently built chunk if it has non zero length /// `self.current_chunk.len()` is zero fn flush(&mut self) -> Option<String> { if !self.current_chunk.is_empty() { let mut new_chunk = String::with_capacity(self.max_chunk_size); std::mem::swap(&mut new_chunk, &mut self.current_chunk); Some(new_chunk) } else { None } } } #[cfg(test)] mod tests { use std::sync::Mutex; use super::*; #[tokio::test] async fn test() { let mock = Arc::new(MockRequestMaker::new()); let namespace = "orgname_bucketname"; let data = "m,t=foo f=4"; let expected = vec![MockRequest { org_id: "orgname".into(), bucket_id: "bucketname".into(), body: data.into(), }]; let num_bytes = Client::new_with_maker(Arc::clone(&mock) as _) .write_lp(namespace, data) .await .unwrap(); assert_eq!(expected, mock.requests()); assert_eq!(num_bytes, 11); } #[tokio::test] async fn test_max_request_payload_size() { let mock = Arc::new(MockRequestMaker::new()); let namespace = "orgname_bucketname"; let data = "m,t=foo f=4\n\ m,t=bar f=3\n\ m,t=fooddddddd f=4"; // expect the data to be broken up into two chunks: let expected = vec![ MockRequest { org_id: "orgname".into(), bucket_id: "bucketname".into(), body: "m,t=foo f=4\nm,t=bar f=3".into(), }, MockRequest { org_id: "orgname".into(), bucket_id: "bucketname".into(), body: "m,t=fooddddddd f=4".into(), }, ]; let num_bytes = Client::new_with_maker(Arc::clone(&mock) as _) // enough to get first two lines, but not last .with_max_request_payload_size_bytes(Some(30)) .write_lp(namespace, data) .await .unwrap(); assert_eq!(expected, mock.requests()); assert_eq!(num_bytes, 41); } #[tokio::test] async fn test_write_lp_stream() { let mock = Arc::new(MockRequestMaker::new()); let namespace = "orgname_bucketname"; let data = futures_util::stream::iter( vec!["m,t=foo f=4", "m,t=bar f=3"] .into_iter() .map(|s| s.to_string()), ); // expect the data to come in two chunks let expected = vec![ MockRequest { org_id: "orgname".into(), bucket_id: "bucketname".into(), body: "m,t=foo f=4".into(), }, MockRequest { org_id: "orgname".into(), bucket_id: "bucketname".into(), body: "m,t=bar f=3".into(), }, ]; let num_bytes = Client::new_with_maker(Arc::clone(&mock) as _) .write_lp_stream(namespace, data) .await .unwrap(); assert_eq!(expected, mock.requests()); assert_eq!(num_bytes, 22); } #[derive(Debug, Clone, PartialEq)] struct MockRequest { org_id: String, bucket_id: String, body: String, } #[derive(Debug)] struct MockRequestMaker { requests: Mutex<Vec<MockRequest>>, } impl MockRequestMaker { fn new() -> Self { Self { requests: Mutex::new(vec![]), } } /// get a copy of the requests that were made using this mock fn requests(&self) -> Vec<MockRequest> { self.requests.lock().unwrap().clone() } } impl RequestMaker for MockRequestMaker { fn write_source( &self, org_id: String, bucket_id: String, body: String, ) -> BoxFuture<'_, Result<usize, Error>> { let sz = body.len(); self.requests.lock().unwrap().push(MockRequest { org_id, bucket_id, body, }); async move { Ok(sz) }.boxed() } } }
use crate::proxy_addr::ProxyAddr; use crate::crawlers::build_headers; use tokio::time::Duration; use reqwest::Proxy; use crate::storages; use serde::Deserialize; const TEST_ANONYMOUS: bool = true; const TEST_TIMEOUT: u64 = 10; const TEST_BATCH: u32 = 20; #[derive(Debug, Deserialize, PartialEq)] struct Ip { origin: String, } async fn test(proxy: ProxyAddr) { let proxy_url = format!("http://{}", proxy); let url = "https://httpbin.org/ip"; let client = reqwest::Client::builder().build().unwrap(); let origin: Option<Ip> = match client.get(url).headers(build_headers()).timeout(Duration::from_secs(TEST_TIMEOUT)) .send().await.and_then(|s| Ok(s.json())) { Ok(f) => f.await.map_or_else(|_| None, |j| Some(j)), Err(_) => None }; let client = reqwest::Client::builder().proxy(Proxy::http(&proxy_url).unwrap()).build().unwrap(); let anonymous: Option<Ip> = match client.get(url).headers(build_headers()).timeout(Duration::from_secs(TEST_TIMEOUT)) .send().await.and_then(|s| Ok(s.json())) { Ok(f) => f.await.map_or_else(|_| None, |j| Some(j)), Err(_) => None }; match (&origin, &anonymous) { (Some(a), Some(b)) => { if a == b { storages::redis::decrease_score(proxy); } else { storages::redis::max_score(proxy); } } _ => storages::redis::decrease_score(proxy), } } pub async fn run() { let mut cursor = 0; loop { let (next_cursor , proxies) = storages::redis::batch(cursor, TEST_BATCH); for proxy in proxies { test(proxy).await; } cursor = next_cursor; if cursor == 0 { break; } } }
use std::cmp::Ordering::*; use rand::prelude::*; use wasm_bindgen::prelude::*; use crate::factor::{any_factor_in, factor_list_in}; use crate::iif; use crate::is_factor; use crate::util::{is_even, sqrt}; const MAX_PRIME: u32 = 4294967291; #[wasm_bindgen] pub struct PrimeNumber; #[wasm_bindgen] impl PrimeNumber { #[wasm_bindgen(js_name = rangeList)] pub fn range_list(begin: u32, end: u32) -> Vec<u32> { match (begin, end) { (b, e) if b == e => iif!(Self::is_prime(b) => vec![b]; Vec::new()), (b, e) if b > e => Vec::new(), (b, e) => (b..=e).filter(Self::is_prime_ref).collect(), } } #[wasm_bindgen] pub fn nth(n: u32) -> Option<u32> { match n.cmp(&199999) { Greater => return None, // Very slow Equal => return Some(1299709), _ => (), } let mut primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23]; if n > 8 { let mut next = 29u32; let search = |_| match (next..).step_by(2).find(Self::is_prime_ref) { Some(prime) => { next = prime + 2; primes.push(prime); Ok(()) } None => Err(()), }; if (9..=n).try_for_each(search).is_err() { return None; } } primes.get(n as usize).cloned() } #[wasm_bindgen(js_name = randomRange)] pub fn random_range(begin: u32, end: u32) -> Option<u32> { match begin.cmp(&end) { Greater => None, Equal => Self::prime(begin), _ => { let orig = thread_rng().gen_range(begin..=end); if Self::is_prime(orig) { return Some(orig); } let res = match Self::closest_prime(orig + 1, true) { Some(n) => match n.cmp(&end) { Greater => None, _ => Some(n), }, None => None, }; match res { Some(n) => Some(n), _ => match Self::closest_prime(orig - 1, false) { Some(n) => match n.cmp(&begin) { Less => None, _ => Some(n), }, None => None, }, } } } } #[wasm_bindgen] pub fn random() -> Option<u32> { let mut generator = thread_rng(); match generator.gen() { n @ 0..=99 => Self::closest_prime(n, true), n if n >= MAX_PRIME => Some(MAX_PRIME), n => iif! { generator.gen() => Self::closest_prime(n, true); Self::closest_prime(n, false) }, } } #[wasm_bindgen(js_name = closestPrime)] pub fn closest_prime(num: u32, asc: bool) -> Option<u32> { let num = match num { 0 | 1 => 1, 2 | 3 | MAX_PRIME => return Some(num), n if is_even(n) => iif! {asc => n + 1; n - 1}, n => n, }; iif! { asc => match num.cmp(&MAX_PRIME) { Less => (num..).step_by(2).find(Self::is_prime_ref), _ => None, }; match num.cmp(&3) { Greater => (3..=num).rev().step_by(2).find(Self::is_prime_ref), _ => None, } } } #[wasm_bindgen(js_name = anyPrimeFactorIn)] pub fn any_prime_factor_in(num: u32, divisors: &[u32]) -> bool { match num { 0 | 1 => false, _ => any_factor_in(num, &Self::prime_list_in(divisors)), } } #[wasm_bindgen(js_name = primeFactorListIn)] pub fn prime_factor_list_in(num: u32, divisors: &[u32]) -> Vec<u32> { match num { 0 | 1 => Vec::new(), _ => factor_list_in(num, &Self::prime_list_in(divisors)), } } #[wasm_bindgen(js_name = primeFactorList)] pub fn prime_factor_list(num: u32) -> Vec<u32> { let mut prime = 2; let mut list = Vec::new(); loop { if prime > sqrt(num) { if Self::is_prime_ref(&num) { list.push(num); } break; } if is_factor!(num, prime) { list.push(prime); } match Self::closest_prime(prime + 1, true) { Some(p) => prime = p, _ => break, } } list } #[wasm_bindgen] pub fn prime(num: u32) -> Option<u32> { iif!(Self::is_prime_ref(&num) => Some(num); None) } #[wasm_bindgen(js_name = filterPrimes)] pub fn prime_list_in(list: &[u32]) -> Vec<u32> { list.iter().cloned().filter(Self::is_prime_ref).collect() } #[wasm_bindgen(js_name = isPrime)] pub fn is_prime(num: u32) -> bool { Self::is_prime_ref(&num) } fn is_prime_ref(num: &u32) -> bool { match num { 0 | 1 => false, 2 | 3 | 5 | 7 | 11 | 13 | 17 | 19 | 23 => true, n if is_factor!(n, &[2, 3, 5, 7, 11, 13, 17, 19, 23]) => false, &n => !(29..=sqrt(n)) .step_by(6) .any(|i| is_factor!(n, &[i, i + 2])), } } } #[cfg(test)] mod tests { use super::*; #[test] fn range_list_900_900() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::range_list(900, 900)); } #[test] fn range_list_999_900() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::range_list(999, 900)); } #[test] fn range_list_953_953() { assert_eq!(vec![953], PrimeNumber::range_list(953, 953)); } #[test] fn range_list_900_999() { assert_eq!( vec![907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997], PrimeNumber::range_list(900, 999) ); } #[test] fn range_list_900_953() { assert_eq!( vec![907, 911, 919, 929, 937, 941, 947, 953], PrimeNumber::range_list(900, 953) ); } #[test] fn range_list_953_999() { assert_eq!( vec![953, 967, 971, 977, 983, 991, 997], PrimeNumber::range_list(953, 999) ); } #[test] fn nth_0() { assert_eq!(Some(2), PrimeNumber::nth(0)); } #[test] fn nth_199999() { assert_eq!(Some(1299709), PrimeNumber::nth(199999)); } #[test] fn nth_14() { assert_eq!(Some(47), PrimeNumber::nth(14)); } #[test] fn random_range_953_999() { (0..9).for_each(|_| { assert!(PrimeNumber::random_range(953, 999).is_some()); }); } #[test] fn random_range_0_999() { (0..9).for_each(|_| { assert!(PrimeNumber::random_range(0, 999).is_some()); }); } #[test] fn random_range_0_0() { assert!(PrimeNumber::random_range(0, 0).is_none()); } #[test] fn random_range_972_976() { assert!(PrimeNumber::random_range(972, 976).is_none()); } #[test] fn random_range_976_972() { assert!(PrimeNumber::random_range(976, 972).is_none()); } #[test] fn random_range_953_953() { assert!(PrimeNumber::random_range(953, 953).is_some()); } #[test] fn random_ok() { (0..99).for_each(|_| { assert!(PrimeNumber::random().is_some()); }); } #[test] fn closest_prime_7_asc() { assert_eq!(Some(7), PrimeNumber::closest_prime(7, true)); } #[test] fn closest_prime_8_asc() { assert_eq!(Some(11), PrimeNumber::closest_prime(8, true)); } #[test] fn closest_prime_0_desc() { assert_eq!(None, PrimeNumber::closest_prime(0, false)); } #[test] fn closest_prime_1_desc() { assert_eq!(None, PrimeNumber::closest_prime(1, false)); } #[test] fn closest_prime_6_desc() { assert_eq!(Some(5), PrimeNumber::closest_prime(6, false)); } #[test] fn closest_prime_2() { assert_eq!(Some(2), PrimeNumber::closest_prime(2, false)); } #[test] fn closest_prime_3() { assert_eq!(Some(3), PrimeNumber::closest_prime(3, false)); } #[test] fn closest_prime_max() { assert_eq!( Some(MAX_PRIME), PrimeNumber::closest_prime(MAX_PRIME, false) ); } #[test] fn closest_prime_max_plus_1_desc() { assert_eq!( Some(MAX_PRIME), PrimeNumber::closest_prime(MAX_PRIME + 1, false) ); } #[test] fn closest_prime_max_plus_1_asc() { assert_eq!(None, PrimeNumber::closest_prime(MAX_PRIME + 1, true)); } #[test] fn any_prime_factor_in_0_range() { assert_eq!( false, PrimeNumber::any_prime_factor_in(0, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn any_prime_factor_in_1_range() { assert_eq!( false, PrimeNumber::any_prime_factor_in(1, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn any_prime_factor_in_4_range() { assert_eq!( true, PrimeNumber::any_prime_factor_in(4, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn any_prime_factor_in_11_range() { assert_eq!( false, PrimeNumber::any_prime_factor_in(11, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn any_prime_factor_in_4_empty() { assert_eq!(false, PrimeNumber::any_prime_factor_in(4, &[])); } #[test] fn any_prime_factor_in_4_nok() { assert_eq!(false, PrimeNumber::any_prime_factor_in(4, &[3])); } #[test] fn any_prime_factor_in_4_ok() { assert_eq!(true, PrimeNumber::any_prime_factor_in(4, &[2])); } #[test] fn any_prime_factor_in_6_ok() { assert_eq!(true, PrimeNumber::any_prime_factor_in(6, &[2, 3, 4])); } #[test] fn prime_factor_list_in_1_range() { let empty: Vec<u32> = Vec::new(); assert_eq!( empty, PrimeNumber::prime_factor_list_in(1, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn prime_factor_list_in_4_range() { assert_eq!( vec![2], PrimeNumber::prime_factor_list_in(4, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn prime_factor_list_in_11_range() { let empty: Vec<u32> = Vec::new(); assert_eq!( empty, PrimeNumber::prime_factor_list_in(11, &(0..9).collect::<Vec<u32>>()) ); } #[test] fn prime_factor_list_in_4_empty() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::prime_factor_list_in(4, &[])); } #[test] fn prime_factor_list_in_4_nok() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::prime_factor_list_in(4, &[3])); } #[test] fn prime_factor_list_in_4_ok() { assert_eq!(vec![2], PrimeNumber::prime_factor_list_in(4, &[2])); } #[test] fn prime_factor_list_in_6_ok() { assert_eq!(vec![2, 3], PrimeNumber::prime_factor_list_in(6, &[2, 3, 4])); } #[test] fn prime_factor_list_0() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::prime_factor_list(0)); } #[test] fn prime_factor_list_1() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::prime_factor_list(1)); } #[test] fn prime_factor_list_7() { assert_eq!(vec![7], PrimeNumber::prime_factor_list(7)); } #[test] fn prime_factor_list_210() { assert_eq!(vec![2, 3, 5, 7], PrimeNumber::prime_factor_list(210)); } #[test] fn prime_0() { assert_eq!(None, PrimeNumber::prime(0)); } #[test] fn prime_1() { assert_eq!(None, PrimeNumber::prime(1)); } #[test] fn prime_2() { assert_eq!(Some(2), PrimeNumber::prime(2)); } #[test] fn prime_4() { assert_eq!(None, PrimeNumber::prime(4)); } #[test] fn prime_31() { assert_eq!(Some(31), PrimeNumber::prime(31)); } #[test] fn prime_899() { assert_eq!(None, PrimeNumber::prime(899)); } #[test] fn prime_max() { assert_eq!(Some(MAX_PRIME), PrimeNumber::prime(MAX_PRIME)); } #[test] fn prime_list_in_range() { assert_eq!( vec![2, 3, 5, 7, 11, 13, 17, 19, 23], PrimeNumber::prime_list_in(&(0..29).collect::<Vec<u32>>()) ); } #[test] fn prime_list_in_empty() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::prime_list_in(&[])); } #[test] fn prime_list_in_nok() { let empty: Vec<u32> = Vec::new(); assert_eq!(empty, PrimeNumber::prime_list_in(&[0, 1])); } #[test] fn is_prime_0() { assert_eq!(false, PrimeNumber::is_prime(0)); } #[test] fn is_prime_1() { assert_eq!(false, PrimeNumber::is_prime(1)); } #[test] fn is_prime_2() { assert_eq!(true, PrimeNumber::is_prime(2)); } #[test] fn is_prime_4() { assert_eq!(false, PrimeNumber::is_prime(4)); } #[test] fn is_prime_31() { assert_eq!(true, PrimeNumber::is_prime(31)); } #[test] fn is_prime_899() { assert_eq!(false, PrimeNumber::is_prime(899)); } #[test] fn is_prime_max() { assert_eq!(true, PrimeNumber::is_prime(MAX_PRIME)); } }
pub mod meta; pub mod parser; pub mod render;
use super::Part; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteObject}; remote_type!( /// An experiment. Obtained by calling `Part::experiment().` object SpaceCenter.Experiment { properties: { { Part { /// Returns the part object for this experiment. /// /// **Game Scenes**: All get: part -> Part } } { Deployed { /// Returns whether the experiment has been deployed. /// /// **Game Scenes**: All get: is_deployed -> bool } } { Rerunnable { /// Returns whether the experiment can be re-run. /// /// **Game Scenes**: All get: is_rerunnable -> bool } } { Inoperable { /// Returns whether the experiment is inoperable. /// /// **Game Scenes**: All get: is_inoperable -> bool } } { HasData { /// Returns whether the experiment contains data. /// /// **Game Scenes**: All get: has_data -> bool } } { Data { /// Returns the data contained in this experiment. /// /// **Game Scenes**: All get: data -> Vec<ScienceData> } } { Biome { /// Returns the name of the biome the experiment is currently in. /// /// **Game Scenes**: All get: biome -> String } } { Available { /// Determines if the experiment is available given the current conditions. /// /// **Game Scenes**: All get: is_available -> bool } } { ScienceSubject { /// Containing information on the corresponding specific science result for the /// current conditions. Returns `None` if the experiment is unavailable. /// /// **Game Scenes**: All get: science_subject -> Option<ScienceSubject> } } } methods: { { /// Run the experiment. /// /// **Game Scenes**: All fn run() { Run() } } { /// Transmit all experimental data contained by this part. /// /// **Game Scenes**: All fn transmit() { Transmit() } } { /// Dump the experimental data contained by the experiment. /// /// **Game Scenes**: All fn dump() { Dump() } } { /// Reset the experiment. /// /// **Game Scenes**: All fn reset() { Reset() } } } }); remote_type!( /// Obtained by calling `Experiment::data()`. object SpaceCenter.ScienceData { properties: { { DataAmount { /// Returns the data mount. /// /// **Game Scenes**: All get: data_amount -> f32 } } { ScienceValue { /// Returns the science value. /// /// **Game Scenes**: All get: science_value -> f32 } } { TransmitValue { /// Returns the transmit value. /// /// **Game Scenes**: All get: transmit_value -> f32 } } } }); remote_type!( /// Obtained by calling `Experiment::science_subject()`. object SpaceCenter.ScienceSubject { properties: { { Title { /// Returns the title of science subject, displayed in science archives. /// /// **Game Scenes**: All get: title -> String } } { IsComplete { /// Returns whether the experiment has been completed. /// /// **Game Scenes**: All get: is_complete -> bool } } { Science { /// Returns the amount of science already earned from this subject, not updated /// until after transmission/recovery. /// /// **Game Scenes**: All get: science -> f32 } } { ScienceCap { /// Returns the total science allowable for this subject. /// /// **Game Scenes**: All get: science_cap -> f32 } } { DataScale { /// Returns the multiply science value by this to determine data amount in mits. /// /// **Game Scenes**: All get: data_scale -> f32 } } { SubjectValue { /// Returns the multiplier for specific Celestial Body/Experiment /// Situation combination. /// /// **Game Scenes**: All get: subject_value -> f32 } } { ScientificValue { /// Returns the diminishing value multiplier for decreasing the science value /// returned from repeated experiments. /// /// **Game Scenes**: All get: scientific_value -> f32 } } } });
use flate2::Compression; use flate2::read::GzDecoder; use flate2::write::GzEncoder; use std::fs::{create_dir_all, rename, File}; use std::path::Path; use tar::{Builder, Archive}; use uuid::Uuid; use crate::error::Error; pub fn to_tar_gz(src: &Path, dest: &Path) -> Result<(), Error> { let file_name = format!(".{}", Uuid::new_v4().to_urn()); let p = dest.with_file_name(file_name); let tmp_dest = p.as_path(); let f = File::create(tmp_dest)?; let gz_encoder = GzEncoder::new(f, Compression::default()); let mut tar_encoder = Builder::new(gz_encoder); tar_encoder.append_dir_all(".", src)?; let gz_encoder = tar_encoder.into_inner()?; gz_encoder.finish()?; rename(tmp_dest, dest)?; Ok(()) } pub fn from_tar_gz(src: &Path, dest: &Path) -> Result<(), Error> { let f = File::open(src)?; let gz = GzDecoder::new(f); let mut ar = Archive::new(gz); create_dir_all(dest)?; ar.unpack(dest)?; Ok(()) }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qscopedpointer.h // dst-file: /src/core/qscopedpointer.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QScopedPointerPodDeleter_Class_Size() -> c_int; // proto: static void QScopedPointerPodDeleter::cleanup(void * pointer); fn C_ZN24QScopedPointerPodDeleter7cleanupEPv(arg0: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QScopedPointerPodDeleter)=1 #[derive(Default)] pub struct QScopedPointerPodDeleter { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QScopedPointerPodDeleter { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QScopedPointerPodDeleter { return QScopedPointerPodDeleter{qclsinst: qthis, ..Default::default()}; } } // proto: static void QScopedPointerPodDeleter::cleanup(void * pointer); impl /*struct*/ QScopedPointerPodDeleter { pub fn cleanup_s<RetType, T: QScopedPointerPodDeleter_cleanup_s<RetType>>( overload_args: T) -> RetType { return overload_args.cleanup_s(); // return 1; } } pub trait QScopedPointerPodDeleter_cleanup_s<RetType> { fn cleanup_s(self ) -> RetType; } // proto: static void QScopedPointerPodDeleter::cleanup(void * pointer); impl<'a> /*trait*/ QScopedPointerPodDeleter_cleanup_s<()> for (*mut c_void) { fn cleanup_s(self ) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN24QScopedPointerPodDeleter7cleanupEPv()}; let arg0 = self as *mut c_void; unsafe {C_ZN24QScopedPointerPodDeleter7cleanupEPv(arg0)}; // return 1; } } // <= body block end
extern crate ncurses; extern crate gui_lib; use std::collections::HashMap; use std::sync::mpsc::{Sender, Receiver}; use ncurses::*; use crate::shared::Event; use crate::protocol::NewWindow; use gui_lib::*; #[derive(Clone, Debug)] pub enum GuiEvent{ CreateWindow(NewWindow), DestroyWindow(String), Log(String), } pub fn launch(tx: Sender<Event>, rx: Receiver<GuiEvent>) { /* Setup ncurses. */ initscr(); raw(); /* Allow for extended keyboard (like F1). */ keypad(stdscr(), true); noecho(); /* Invisible cursor. */ curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE); /* Status/help info. */ put_pos(0, 0); //mvprintw(LINES() - 2, 0, &INSTRUCTIONS); refresh(); // Set up omniscient stuff // HashMap of active windows, so that we know what's bonkin' let mut windows: std::collections::HashMap<String, WINDOW> = HashMap::new(); // Log buffer to use for keeping track of command output. let mut logbuffer: Vec<String> = Vec::new(); for _i in 0..6 { logbuffer.push(" ".to_string()); } showlog(&logbuffer); /* Get the screen bounds. */ let mut max_x = 0; let mut max_y = 0; getmaxyx(stdscr(), &mut max_y, &mut max_x); let mut window_height: i32 = 3; let mut window_width: i32 = 4; /* Start in the center. */ let mut start_y = (max_y - window_height) / 2; let mut start_x = (max_x - window_width) / 2; let mut win = create_win("mainwindow".to_string(), start_y, start_x, window_width, window_height, &mut windows); for message in rx.iter() { match message { GuiEvent::CreateWindow(new_window) => { put_alert(new_window.x_pos, new_window.y_pos, new_window.width, new_window.height, &new_window.id, &new_window.content, &mut windows, &mut logbuffer); }, GuiEvent::DestroyWindow(id) => { close_win(id, &mut windows, &mut logbuffer); }, GuiEvent::Log(log_event) => { logbuffer.insert(0, log_event); showlog(&logbuffer); // dbg!("LOG EVENT RECEIVED!"); } } let ch = getch(); if ch == KEY_F(1) { break; } } endwin(); std::process::exit(0); }
use winapi::shared::windef::{HBITMAP, HBRUSH}; use winapi::um::winuser::{WS_VISIBLE, WS_DISABLED, WS_TABSTOP}; use winapi::um::commctrl::{ LVS_ICON, LVS_SMALLICON, LVS_LIST, LVS_REPORT, LVS_NOCOLUMNHEADER, LVCOLUMNW, LVCFMT_LEFT, LVCFMT_RIGHT, LVCFMT_CENTER, LVCFMT_JUSTIFYMASK, LVCFMT_IMAGE, LVCFMT_BITMAP_ON_RIGHT, LVCFMT_COL_HAS_IMAGES, LVITEMW, LVIF_TEXT, LVCF_WIDTH, LVCF_TEXT, LVS_EX_GRIDLINES, LVS_EX_BORDERSELECT, LVS_EX_AUTOSIZECOLUMNS, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_FULLROWSELECT, LVS_SINGLESEL, LVCF_FMT, LVIF_IMAGE, LVS_SHOWSELALWAYS, LVS_EX_HEADERDRAGDROP, LVS_EX_HEADERINALLVIEWS, LVM_GETHEADER, HDITEMW, HDI_FORMAT, HDM_GETITEMW, HDF_SORTUP, HDF_SORTDOWN, HDM_SETITEMW }; use super::{ControlBase, ControlHandle}; use crate::win32::window_helper as wh; use crate::win32::base_helper::{to_utf16, from_utf16, check_hwnd}; use crate::{NwgError, RawEventHandler, unbind_raw_event_handler}; use std::{mem, ptr, rc::Rc, cell::RefCell}; #[cfg(feature="image-list")] use crate::ImageList; const NOT_BOUND: &'static str = "ListView is not yet bound to a winapi object"; const BAD_HANDLE: &'static str = "INTERNAL ERROR: ListView handle is not HWND!"; bitflags! { /** The list view flags: * VISIBLE: The list view is immediatly visible after creation * DISABLED: The list view cannot be interacted with by the user. It also has a grayed out look. The user can drag the items to any location in the list-view window. * TAB_STOP: The control can be selected using tab navigation * NO_HEADER: Remove the headers in Detailed view (ON by default, use `ListView::set_headers_enabled` to enable headers) * SINGLE_SELECTION: Only one item can be selected * ALWAYS_SHOW_SELECTION: Shows the selected list view item when the control is not in focus */ pub struct ListViewFlags: u32 { const VISIBLE = WS_VISIBLE; const DISABLED = WS_DISABLED; const TAB_STOP = WS_TABSTOP; const SINGLE_SELECTION = LVS_SINGLESEL; const ALWAYS_SHOW_SELECTION = LVS_SHOWSELALWAYS; // Remove the headers in Detailed view (ON by default due to backward compatibility) // TODO: OFF by default in next major releases const NO_HEADER = LVS_NOCOLUMNHEADER; } } bitflags! { /** The list view extended flags (to use with ListViewBuilder::ex_flags): * NONE: Do not use any extended styles * GRID: The list view has a grid. Only if the list view is in report mode. * BORDER_SELECT: Only highlight the border instead of the full item. COMMCTRL version 4.71 or later * AUTO_COLUMN_SIZE: Automatically resize to column * FULL_ROW_SELECT: When an item is selected, the item and all its subitems are highlighted. Only in detailed view * HEADER_DRAG_DROP: The user can drag and drop the headers to rearrage them * HEADER_IN_ALL_VIEW: Show the header in all view (not just report) */ pub struct ListViewExFlags: u32 { const NONE = 0; const GRID = LVS_EX_GRIDLINES; const BORDER_SELECT = LVS_EX_BORDERSELECT; const AUTO_COLUMN_SIZE = LVS_EX_AUTOSIZECOLUMNS; const FULL_ROW_SELECT = LVS_EX_FULLROWSELECT; const HEADER_DRAG_DROP = LVS_EX_HEADERDRAGDROP; const HEADER_IN_ALL_VIEW = LVS_EX_HEADERINALLVIEWS; } } bitflags! { /** The format flags for a list view column. Not all combination are valid. The alignment of the leftmost column is always LEFT. * LEFT: Text is left-aligned. * RIGHT: Text is right-aligned * CENTER: Text is centered * JUSTIFY_MASK: A bitmask used to select those bits of fmt that control field justification. * IMAGE: The items under to column displays an image from an image list * IMAGE_RIGHT: The bitmap appears to the right of text * IMAGE_COL: The header item contains an image in the image list. */ pub struct ListViewColumnFlags: u32 { const LEFT = LVCFMT_LEFT as u32; const RIGHT = LVCFMT_RIGHT as u32; const CENTER = LVCFMT_CENTER as u32; const JUSTIFY_MASK = LVCFMT_JUSTIFYMASK as u32; const IMAGE = LVCFMT_IMAGE as u32; const IMAGE_RIGHT = LVCFMT_BITMAP_ON_RIGHT as u32; const IMAGE_COL = LVCFMT_COL_HAS_IMAGES as u32; } } /** The display style for the items in a list view */ #[derive(Copy, Clone, Debug)] #[repr(u8)] pub enum ListViewStyle { Simple, Detailed, Icon, SmallIcon, } impl ListViewStyle { fn from_bits(bits: u32) -> ListViewStyle { let bits = bits & 0b11; match bits { LVS_ICON => ListViewStyle::Icon, LVS_REPORT => ListViewStyle::Detailed, LVS_SMALLICON => ListViewStyle::SmallIcon, LVS_LIST => ListViewStyle::Simple, _ => unreachable!() } } fn bits(&self) -> u32 { match self { ListViewStyle::Simple => LVS_LIST, ListViewStyle::Detailed => LVS_REPORT, ListViewStyle::Icon => LVS_ICON, ListViewStyle::SmallIcon => LVS_SMALLICON, } } } /** Items in a list view can be associated with multiple image list. This identify which image list to set/get using the ListView api. */ #[cfg(feature="image-list")] #[derive(Copy, Clone, Debug)] pub enum ListViewImageListType { /// Normal sized icons Normal, /// Small icons Small, /// State icons State, /// Group header list (not yet implemented) GroupHeader } #[cfg(feature="image-list")] impl ListViewImageListType { fn to_raw(&self) -> i32 { use winapi::um::commctrl::{LVSIL_NORMAL, LVSIL_SMALL, LVSIL_STATE, LVSIL_GROUPHEADER}; match self { Self::Normal => LVSIL_NORMAL, Self::Small => LVSIL_SMALL, Self::State => LVSIL_STATE, Self::GroupHeader => LVSIL_GROUPHEADER, } } } #[derive(Default, Clone, Debug)] /// Represents a column in a detailed list view pub struct InsertListViewColumn { /// Index of the column pub index: Option<i32>, /// Format of the column pub fmt: Option<ListViewColumnFlags>, /// Width of the column in pixels pub width: Option<i32>, /// Text of the column to insert pub text: Option<String> } /// The data of a list view column #[derive(Default, Clone, Debug)] pub struct ListViewColumn { pub fmt: i32, pub width: i32, pub text: String, } /// Represents a column sort indicator in a detailed list view #[derive(Copy, Clone, Debug)] pub enum ListViewColumnSortArrow { Up, Down, } /// Represents a list view item parameters #[derive(Default, Clone, Debug)] pub struct InsertListViewItem { /// Index of the item to be inserted /// If None and `insert_item` is used, the item is added at the end of the list pub index: Option<i32>, /// Index of the column pub column_index: i32, /// Text of the item to insert pub text: Option<String>, /// Index of the image in the image list /// Icons are only supported at column 0 #[cfg(feature="image-list")] pub image: Option<i32> } /// The data of a list view item #[derive(Default, Clone, Debug)] pub struct ListViewItem { pub row_index: i32, pub column_index: i32, pub text: String, /// If the item is currently selected pub selected: bool, #[cfg(feature="image-list")] pub image: i32, } struct ListViewDoubleBuffer { buffer: HBITMAP, size: [i32; 2], bg: HBRUSH, } /** A list-view control is a window that displays a collection of items. List-view controls provide several ways to arrange and display items and are much more flexible than simple ListBox. Requires the `list-view` feature. Builder parameters: * `parent`: **Required.** The list view parent container. * `size`: The list view size. * `position`: The list view position. * `background_color`: The list view background color in RGB format * `double_buffer`: If the list view should be double buffered (defaults to true) * `text_color`: The list view text color in RGB format * `flags`: A combination of the ListViewFlags values. * `ex_flags`: A combination of the ListViewExFlags values. Not to be confused with `ex_window_flags` * `ex_window_flags`: A combination of win32 window extended flags. This is the equivalent to `ex_flags` in the other controls * `style`: One of the value of `ListViewStyle` * `item_count`: Number of item to preallocate * `list_style`: The default style of the listview * `focus`: The control receive focus after being created **Control events:** * `MousePress(_)`: Generic mouse press events on the tree view * `OnMouseMove`: Generic mouse mouse event * `OnMouseWheel`: Generic mouse wheel event * `OnKeyPress`: Generic key press event * `OnKeyRelease`: Generic key release event * `OnListViewClear`: When all the items in a list view are destroyed * `OnListViewItemRemoved`: When an item is about to be removed from the list view * `OnListViewItemInsert`: When a new item is inserted in the list view * `OnListViewItemActivated`: When an item in the list view is activated by the user * `OnListViewClick`: When the user has clicked the left mouse button within the control * `OnListViewRightClick`: When the user has clicked the right mouse button within the control * `OnListViewDoubleClick`: When the user has clicked the left mouse button within the control twice rapidly * `OnListViewColumnClick`: When the user has clicked the left mouse button on ListView header column * `OnListViewItemChanged`: When an item is selected/unselected in the listview * `OnListViewFocus`: When the list view has received focus * `OnListViewFocusLost`: When the list view has lost focus */ #[derive(Default)] pub struct ListView { pub handle: ControlHandle, double_buffer: Option<Rc<RefCell<ListViewDoubleBuffer>>>, handler0: Option<RawEventHandler>, } impl ListView { pub fn builder() -> ListViewBuilder { ListViewBuilder { size: (300, 300), position: (0, 0), background_color: None, double_buffer: true, text_color: None, focus: false, flags: None, ex_flags: None, ex_window_flags: 0, style: ListViewStyle::Simple, parent: None, item_count: 0 } } /// Sets the image list of the listview /// A listview can accept different kinds of image list. See `ListViewImageListType` #[cfg(feature="image-list")] pub fn set_image_list(&self, list: Option<&ImageList>, list_type: ListViewImageListType) { use winapi::um::commctrl::LVM_SETIMAGELIST; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let list_handle = list.map(|l| l.handle).unwrap_or(ptr::null_mut()); wh::send_message(handle, LVM_SETIMAGELIST, list_type.to_raw() as _, list_handle as _); self.invalidate(); } /// Returns the current image list for the selected type. The returned image list will not be owned. /// Can return `None` if there is no assocaited image list #[cfg(feature="image-list")] pub fn image_list(&self, list_type: ListViewImageListType) -> Option<ImageList> { use winapi::um::commctrl::LVM_GETIMAGELIST; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); match wh::send_message(handle, LVM_GETIMAGELIST, list_type.to_raw() as _, 0) { 0 => None, handle => Some( ImageList { handle: handle as _, owned: false }) } } /// Sets the text color of the list view pub fn set_text_color(&self, r: u8, g: u8, b: u8) { use winapi::um::commctrl::LVM_SETTEXTCOLOR; use winapi::um::wingdi::RGB; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let color = RGB(r, g, b); wh::send_message(handle, LVM_SETTEXTCOLOR, 0, color as _); self.invalidate(); } /// Returns the current text color pub fn text_color(&self) -> [u8; 3] { use winapi::um::commctrl::LVM_GETTEXTCOLOR; use winapi::um::wingdi::{GetRValue, GetGValue, GetBValue}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let col = wh::send_message(handle, LVM_GETTEXTCOLOR, 0, 0) as u32; [ GetRValue(col), GetGValue(col), GetBValue(col), ] } /// Sets the background color of the list view pub fn set_background_color(&self, r: u8, g: u8, b: u8) { use winapi::um::commctrl::LVM_SETBKCOLOR; use winapi::um::wingdi::RGB; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let color = RGB(r, g, b); wh::send_message(handle, LVM_SETBKCOLOR, 0, color as _); self.invalidate(); } /// Returns the background color of the list view pub fn background_color(&self) -> [u8; 3] { use winapi::um::commctrl::LVM_GETBKCOLOR; use winapi::um::wingdi::{GetRValue, GetGValue, GetBValue}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let col = wh::send_message(handle, LVM_GETBKCOLOR, 0, 0) as u32; [ GetRValue(col), GetGValue(col), GetBValue(col), ] } /// Returns the index of the selected column. Only available if Comclt32.dll version is >= 6.0. pub fn selected_column(&self) -> usize { use winapi::um::commctrl::LVM_GETSELECTEDCOLUMN; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_GETSELECTEDCOLUMN, 0, 0) as usize } /// Sets the selected column. Only available if Comclt32.dll version is >= 6.0. pub fn set_selected_column(&self, index: usize) { use winapi::um::commctrl::LVM_SETSELECTEDCOLUMN; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_SETSELECTEDCOLUMN, index as _, 0); } /// Returns the number of selected items pub fn selected_count(&self) -> usize { use winapi::um::commctrl::LVM_GETSELECTEDCOUNT; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_GETSELECTEDCOUNT, 0, 0) as usize } /// Inserts a column in the report. Column are only used with the Detailed list view style. pub fn insert_column<I: Into<InsertListViewColumn>>(&self, insert: I) { use winapi::um::commctrl::LVM_INSERTCOLUMNW; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); match self.list_style() { ListViewStyle::Detailed => {}, _ => { return; } } let insert = insert.into(); let mut mask = LVCF_TEXT | LVCF_WIDTH; let text = insert.text.unwrap_or("".to_string()); let mut text = to_utf16(&text); let col_width = insert.width.unwrap_or(100) as f64 * crate::win32::high_dpi::scale_factor(); if insert.fmt.is_some() { mask |= LVCF_FMT; } let mut item: LVCOLUMNW = unsafe { mem::zeroed() }; item.mask = mask; item.fmt = insert.fmt.unwrap_or(ListViewColumnFlags::empty()).bits() as _; item.cx = col_width as i32; item.pszText = text.as_mut_ptr(); item.cchTextMax = text.len() as i32; let col_count = self.column_len() as i32; wh::send_message( handle, LVM_INSERTCOLUMNW, insert.index.unwrap_or(col_count) as usize, (&item as *const LVCOLUMNW) as _ ); } /// Checks if there is a column at the selected index pub fn has_column(&self, index: usize) -> bool { use winapi::um::commctrl::LVM_GETCOLUMNW; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut col: LVCOLUMNW = unsafe { mem::zeroed() }; wh::send_message(handle, LVM_GETCOLUMNW, index as _, &mut col as *mut LVCOLUMNW as _) != 0 } /// Returns the information of a column. /// Because there's no way to fetch the actual text length, it's up to you to set the maximum buffer size pub fn column(&self, index: usize, text_buffer_size: i32) -> Option<ListViewColumn> { use winapi::um::commctrl::LVM_GETCOLUMNW; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut text_buffer: Vec<u16> = Vec::with_capacity(text_buffer_size as _); unsafe { text_buffer.set_len(text_buffer_size as _); } let mut col: LVCOLUMNW = unsafe { mem::zeroed() }; col.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_FMT; col.pszText = text_buffer.as_mut_ptr(); col.cchTextMax = text_buffer_size; match wh::send_message(handle, LVM_GETCOLUMNW, index as _, &mut col as *mut LVCOLUMNW as _) == 0 { true => None, false => Some(ListViewColumn { fmt: col.fmt, width: col.cx, text: from_utf16(&text_buffer), }) } } /// Sets the information of a column. Does nothing if there is no column at the selected index pub fn update_column<I: Into<InsertListViewColumn>>(&self, index: usize, column: I) { use winapi::um::commctrl::LVM_SETCOLUMNW; if !self.has_column(index) { return; } let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let insert = column.into(); let use_text = insert.text.is_some(); let use_width = insert.width.is_some(); let use_fmt = insert.fmt.is_some(); let mut mask = 0; if use_text { mask |= LVCF_TEXT; } if use_width { mask |= LVCF_WIDTH; } if use_fmt { mask |= LVCF_FMT; } let text = insert.text.unwrap_or("".to_string()); let mut text = to_utf16(&text); let mut item: LVCOLUMNW = unsafe { mem::zeroed() }; item.mask = mask; item.fmt = insert.fmt.unwrap_or(ListViewColumnFlags::empty()).bits() as _; item.cx = insert.width.unwrap_or(0); if use_text { item.pszText = text.as_mut_ptr(); item.cchTextMax = text.len() as i32; } wh::send_message(handle, LVM_SETCOLUMNW, index as _, &mut item as *mut LVCOLUMNW as _); } /// Deletes a column in a list view. Removing the column at index 0 is only available if ComCtl32.dll is version 6 or later. pub fn remove_column(&self, column_index: usize) { use winapi::um::commctrl::LVM_DELETECOLUMN; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_DELETECOLUMN , column_index as _, 0); } /// Returns true if list view headers are visible pub fn headers_enabled(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let style = wh::get_style(handle); (style & LVS_REPORT == LVS_REPORT) && (style & LVS_NOCOLUMNHEADER != LVS_NOCOLUMNHEADER) } /// Enable or disable list view headers pub fn set_headers_enabled(&self, enable: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let style = wh::get_style(handle); if style & LVS_REPORT == LVS_REPORT { if !enable { wh::set_style(handle, style | LVS_NOCOLUMNHEADER); } else { wh::set_style(handle, style & !LVS_NOCOLUMNHEADER); } } } /// Returns column sort indicator pub fn column_sort_arrow(&self, column_index: usize) -> Option<ListViewColumnSortArrow> { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let headers = wh::send_message(handle, LVM_GETHEADER, 0, 0); if headers == 0 { return None; } let mut header: HDITEMW = unsafe { mem::zeroed() }; header.mask = HDI_FORMAT; let l = &mut header as *mut HDITEMW as _; wh::send_message(headers as *mut _, HDM_GETITEMW, column_index, l); match header.fmt & (HDF_SORTUP | HDF_SORTDOWN) { HDF_SORTUP => Some(ListViewColumnSortArrow::Up), HDF_SORTDOWN => Some(ListViewColumnSortArrow::Down), _ => None, } } /// Enable or disable column sort indicator. Draws a up-arrow / down-arrow. pub fn set_column_sort_arrow(&self, column_index: usize, sort: Option<ListViewColumnSortArrow>) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let headers = wh::send_message(handle, LVM_GETHEADER, 0, 0); if headers != 0 { let mut header: HDITEMW = unsafe { mem::zeroed() }; header.mask = HDI_FORMAT; let l = &mut header as *mut HDITEMW as _; wh::send_message(headers as *mut _, HDM_GETITEMW, column_index, l); header.fmt &= !(HDF_SORTUP | HDF_SORTDOWN); match sort { Some(ListViewColumnSortArrow::Up) => header.fmt |= HDF_SORTUP, Some(ListViewColumnSortArrow::Down) => header.fmt |= HDF_SORTDOWN, _ => {} }; let l = &mut header as *mut HDITEMW as _; wh::send_message(headers as *mut _, HDM_SETITEMW, column_index, l); } } /// Set the width of a column pub fn set_column_width(&self, column_index: usize, width: isize) { use winapi::um::commctrl::LVM_SETCOLUMNWIDTH; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_SETCOLUMNWIDTH , column_index as _, width); } /// Returns the width of a column pub fn column_width(&self) -> usize { use winapi::um::commctrl::LVM_GETCOLUMNWIDTH; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_GETCOLUMNWIDTH, 0, 0) as usize } /// Select or unselect an item at `row_index`. Does nothing if the index is out of bounds. pub fn select_item(&self, row_index: usize, selected: bool) { use winapi::um::commctrl::{LVM_SETITEMW, LVIF_STATE, LVIS_SELECTED}; if !self.has_item(row_index, 0) { return; } let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut item: LVITEMW = unsafe { mem::zeroed() }; item.iItem = row_index as _; item.mask = LVIF_STATE; item.state = match selected { true => LVIS_SELECTED, false => 0 }; item.stateMask = LVIS_SELECTED; wh::send_message(handle, LVM_SETITEMW , 0, &mut item as *mut LVITEMW as _); } /// Returns the index of the first selected item. /// If there's more than one item selected, use `selected_items` pub fn selected_item(&self) -> Option<usize> { use winapi::um::commctrl::{LVM_GETNEXTITEMINDEX, LVNI_SELECTED, LVITEMINDEX}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut index = None; let mut i_data = LVITEMINDEX { iItem: -1, iGroup: -1 }; if wh::send_message(handle, LVM_GETNEXTITEMINDEX, &mut i_data as *mut LVITEMINDEX as _, LVNI_SELECTED) != 0 { index = Some(i_data.iItem as usize); } index } /// Returns the indices of every selected items. pub fn selected_items(&self) -> Vec<usize> { use winapi::um::commctrl::{LVM_GETNEXTITEMINDEX, LVNI_SELECTED, LVITEMINDEX}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut indices = Vec::with_capacity(self.len()); let mut i_data = LVITEMINDEX { iItem: -1, iGroup: -1 }; while wh::send_message(handle, LVM_GETNEXTITEMINDEX, &mut i_data as *mut LVITEMINDEX as _, LVNI_SELECTED) != 0 { indices.push(i_data.iItem as usize); } indices } /// Inserts a new item into the list view pub fn insert_item<I: Into<InsertListViewItem>>(&self, insert: I) { use winapi::um::commctrl::{LVM_INSERTITEMW, LVM_SETITEMW}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let insert = insert.into(); let row_insert = insert.index.unwrap_or(i32::max_value()); let column_insert = insert.column_index; if column_insert > 0 && !self.has_item(row_insert as _, 0) { self.insert_item(InsertListViewItem { index: Some(row_insert), column_index: 0, text: None, #[cfg(feature="image-list")] image: None, }); } let mask = LVIF_TEXT | check_image_mask(&insert); let image = check_image(&insert); let text = insert.text.unwrap_or("".to_string()); let mut text = to_utf16(&text); let mut item: LVITEMW = unsafe { mem::zeroed() }; item.mask = mask; item.iItem = row_insert; item.iImage = image; item.iSubItem = column_insert; item.pszText = text.as_mut_ptr(); item.cchTextMax = text.len() as i32; if column_insert == 0 { wh::send_message(handle, LVM_INSERTITEMW , 0, &mut item as *mut LVITEMW as _); } else { wh::send_message(handle, LVM_SETITEMW , 0, &mut item as *mut LVITEMW as _); } } /// Checks if the item at the selected row is visible pub fn item_is_visible(&self, index: usize) -> bool { use winapi::um::commctrl::LVM_ISITEMVISIBLE; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_ISITEMVISIBLE , index as _, 0) == 1 } /// Returns `true` if an item exists at the selected index or `false` otherwise. pub fn has_item(&self, row_index: usize, column_index: usize) -> bool { use winapi::um::commctrl::LVM_GETITEMW; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut item: LVITEMW = unsafe { mem::zeroed() }; item.iItem = row_index as _; item.iSubItem = column_index as _; wh::send_message(handle, LVM_GETITEMW , 0, &mut item as *mut LVITEMW as _) == 1 } /// Returns data of an item in the list view. Returns `None` if there is no data at the selected index /// Because there is no way to fetch the actual text size, `text_buffer_size` must be set manually pub fn item(&self, row_index: usize, column_index: usize, text_buffer_size: usize) -> Option<ListViewItem> { use winapi::um::commctrl::{LVM_GETITEMW, LVIF_STATE, LVIS_SELECTED}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut item: LVITEMW = unsafe { mem::zeroed() }; item.iItem = row_index as _; item.iSubItem = column_index as _; item.mask = LVIF_IMAGE | LVIF_TEXT | LVIF_STATE; item.stateMask = LVIS_SELECTED; let mut text_buffer: Vec<u16> = Vec::with_capacity(text_buffer_size); unsafe { text_buffer.set_len(text_buffer_size); } item.pszText = text_buffer.as_mut_ptr(); item.cchTextMax = text_buffer_size as _; let found = wh::send_message(handle, LVM_GETITEMW , 0, &mut item as *mut LVITEMW as _) == 1; if !found { return None; } Some ( build_list_view_image(row_index, column_index, item.state, &text_buffer, item.iImage) ) } /// Updates the item at the selected position /// Does nothing if there is no item at the selected position pub fn update_item<I: Into<InsertListViewItem>>(&self, row_index: usize, data: I) { use winapi::um::commctrl::LVM_SETITEMW; if !self.has_item(row_index, 0) { return; } let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let insert = data.into(); let mut mask = check_image_mask(&insert); if insert.text.is_some() { mask |= LVIF_TEXT; } let image = check_image(&insert); let use_text = insert.text.is_some(); let text = insert.text.unwrap_or("".to_string()); let mut text = to_utf16(&text); let mut item: LVITEMW = unsafe { mem::zeroed() }; item.mask = mask; item.iItem = row_index as _; item.iImage = image; item.iSubItem = insert.column_index as _; if use_text { item.pszText = text.as_mut_ptr(); item.cchTextMax = text.len() as i32; } wh::send_message(handle, LVM_SETITEMW , 0, &mut item as *mut LVITEMW as _); } /// Remove all items on the seleted row. Returns `true` if an item was removed or false otherwise. /// To "remove" an item without deleting the row, use `update_item` and set the text to "". pub fn remove_item(&self, row_index: usize) -> bool { use winapi::um::commctrl::LVM_DELETEITEM; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_DELETEITEM , row_index as _, 0) == 1 } /// Inserts multiple items into the control. Basically a loop over `insert_item`. pub fn insert_items<I: Clone+Into<InsertListViewItem>>(&self, insert: &[I]) { for i in insert.iter() { self.insert_item(i.clone()); } } /// Insert multiple item at the selected row or at the end of the list if `None` was used. /// This method overrides the `index` and the `column_index` of the items. /// Useful when inserting strings into a single row. Ex: `list.insert_items_row(None, &["Hello", "World"]);` pub fn insert_items_row<I: Clone+Into<InsertListViewItem>>(&self, row_index: Option<i32>, insert: &[I]) { let mut column_index = 0; let row_index = row_index.or(Some(self.len() as _)); for i in insert.iter() { let mut item: InsertListViewItem = i.clone().into(); item.index = row_index; item.column_index = column_index; self.insert_item(item); column_index += 1; } } /// Returns the current style of the list view pub fn list_style(&self) -> ListViewStyle { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); ListViewStyle::from_bits(wh::get_style(handle)) } /// Sets the list view style of the control pub fn set_list_style(&self, style: ListViewStyle) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut old_style = wh::get_style(handle); old_style = old_style & !0b11; wh::set_style(handle, old_style | style.bits()); } /// Returns the number of items in the list view pub fn len(&self) -> usize { use winapi::um::commctrl::LVM_GETITEMCOUNT; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_GETITEMCOUNT , 0, 0) as usize } /// Returns the number of columns in the list view pub fn column_len(&self) -> usize { use winapi::um::commctrl::LVM_GETCOLUMNWIDTH; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let mut count = 0; while wh::send_message(handle, LVM_GETCOLUMNWIDTH, count, 0) != 0 { count += 1; } count } /// Preallocate space for n number of item in the whole control. /// For example calling this method with n=1000 while the list has 500 items will add space for 500 new items. pub fn set_item_count(&self, n: u32) { use winapi::um::commctrl::LVM_SETITEMCOUNT; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_SETITEMCOUNT, n as _, 0); } /// Enable or disable the redrawing of the control when a new item is added. /// When inserting a large number of items, it's better to disable redraw and reenable it after the items are inserted. pub fn set_redraw(&self, enabled: bool) { use winapi::um::winuser::WM_SETREDRAW; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, WM_SETREDRAW, enabled as _, 0); } /// Sets the spacing between icons in list-view controls that have the ICON style. /// `dx` specifies the distance, in pixels, to set between icons on the x-axis /// `dy` specifies the distance, in pixels, to set between icons on the y-axis pub fn set_icon_spacing(&self, dx: u16, dy: u16) { use winapi::um::commctrl::LVM_SETICONSPACING; use winapi::shared::minwindef::MAKELONG; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let spacing = MAKELONG(dx, dy); wh::send_message(handle, LVM_SETICONSPACING, 0 as _, spacing as _); self.invalidate(); } // Common methods /// Invalidate the whole drawing region. pub fn invalidate(&self) { use winapi::um::winuser::InvalidateRect; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { InvalidateRect(handle, ptr::null(), 1); } } /// Removes all item from the listview pub fn clear(&self) { use winapi::um::commctrl::LVM_DELETEALLITEMS; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LVM_DELETEALLITEMS, 0, 0); } /// Returns true if the control currently has the keyboard focus pub fn focus(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_focus(handle) } } /// Sets the keyboard focus on the button pub fn set_focus(&self) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_focus(handle); } } /// Returns true if the control user can interact with the control, return false otherwise pub fn enabled(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_enabled(handle) } } /// Enable or disable the control pub fn set_enabled(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_enabled(handle, v) } } /// Returns true if the control is visible to the user. Will return true even if the /// control is outside of the parent client view (ex: at the position (10000, 10000)) pub fn visible(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_visibility(handle) } } /// Show or hide the control to the user pub fn set_visible(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_visibility(handle, v) } } /// Returns the size of the button in the parent window pub fn size(&self) -> (u32, u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_size(handle) } } /// Sets the size of the button in the parent window pub fn set_size(&self, x: u32, y: u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_size(handle, x, y, true) } } /// Returns the position of the button in the parent window pub fn position(&self) -> (i32, i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_position(handle) } } /// Sets the position of the button in the parent window pub fn set_position(&self, x: i32, y: i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_position(handle, x, y) } } /// Winapi class name used during control creation pub fn class_name(&self) -> &'static str { ::winapi::um::commctrl::WC_LISTVIEW } /// Winapi base flags used during window creation pub fn flags(&self) -> u32 { WS_VISIBLE | WS_TABSTOP | LVS_SHOWSELALWAYS } /// Winapi flags required by the control pub fn forced_flags(&self) -> u32 { use winapi::um::winuser::{WS_CHILD, WS_BORDER}; WS_CHILD | WS_BORDER | LVS_NOCOLUMNHEADER } fn set_double_buffered(&mut self) { use crate::bind_raw_event_handler_inner; use winapi::um::wingdi::{CreateSolidBrush, RGB}; let double_buffer = ListViewDoubleBuffer { buffer: ptr::null_mut(), size: [0, 0], bg: unsafe { CreateSolidBrush(RGB(255, 255, 255)) }, }; let rc_double_buffer = Rc::new(RefCell::new(double_buffer)); let callback_double_buffer = rc_double_buffer.clone(); let handler = bind_raw_event_handler_inner(&self.handle, 0x020, move |hwnd, msg, _, _| { use winapi::um::winuser::{GetClientRect, BeginPaint, EndPaint, FillRect, SendMessageW, RedrawWindow, RDW_ERASENOW, RDW_UPDATENOW, RDW_INVALIDATE}; use winapi::um::winuser::{WM_PAINT, WM_ERASEBKGND, WM_PRINTCLIENT, PAINTSTRUCT}; use winapi::um::wingdi::{CreateCompatibleDC, CreateCompatibleBitmap, SelectObject, BitBlt, DeleteDC, DeleteObject, SRCCOPY}; match msg { WM_PAINT => unsafe { let mut double_buffer = callback_double_buffer.borrow_mut(); let mut r = mem::zeroed(); GetClientRect(hwnd, &mut r); let client_width = r.right - r.left; let client_height = r.bottom - r.top; let mut paint: PAINTSTRUCT = mem::zeroed(); BeginPaint(hwnd, &mut paint); if double_buffer.buffer.is_null() || double_buffer.size != [client_width, client_height] { if !double_buffer.buffer.is_null() { DeleteObject(double_buffer.buffer as _); } double_buffer.size = [client_width, client_height]; double_buffer.buffer = CreateCompatibleBitmap(paint.hdc, client_width, client_height); } let backbuffer = double_buffer.buffer; let backbuffer_dc = CreateCompatibleDC(paint.hdc); // Clear the backbuffer let old = SelectObject(backbuffer_dc, backbuffer as _); FillRect(backbuffer_dc, &r, double_buffer.bg as _); // Draw to the backbuffer and copy the result to the front buffer SendMessageW(hwnd, WM_PRINTCLIENT, backbuffer_dc as _, 0); BitBlt( paint.hdc as _, 0, 0, client_width, client_height, backbuffer_dc, 0, 0, SRCCOPY ); // Cleanup SelectObject(backbuffer_dc, old); DeleteDC(backbuffer_dc); EndPaint(hwnd, &paint); // Redraw header let header = SendMessageW(hwnd, LVM_GETHEADER, 0, 0); if header != 0 { let mut r = mem::zeroed(); GetClientRect(header as _, &mut r); RedrawWindow(header as _, ptr::null_mut(), ptr::null_mut(), RDW_ERASENOW|RDW_UPDATENOW|RDW_INVALIDATE); } Some(1) }, WM_ERASEBKGND => { Some(1) }, _ => None } }).unwrap(); self.handler0 = Some(handler); self.double_buffer = Some(rc_double_buffer); } } impl Drop for ListView { fn drop(&mut self) { use winapi::um::wingdi::DeleteObject; if let Some(backbuffer) = self.double_buffer.take() { let double_buffer = backbuffer.borrow(); unsafe { DeleteObject(double_buffer.buffer as _); DeleteObject(double_buffer.bg as _); } } if let Some(h) = self.handler0.as_ref() { drop(unbind_raw_event_handler(h)); } self.handle.destroy(); } } pub struct ListViewBuilder { size: (i32, i32), position: (i32, i32), background_color: Option<[u8; 3]>, text_color: Option<[u8; 3]>, double_buffer: bool, focus: bool, flags: Option<ListViewFlags>, ex_flags: Option<ListViewExFlags>, ex_window_flags: u32, style: ListViewStyle, item_count: u32, parent: Option<ControlHandle> } impl ListViewBuilder { pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> ListViewBuilder { self.parent = Some(p.into()); self } pub fn flags(mut self, flags: ListViewFlags) -> ListViewBuilder { self.flags = Some(flags); self } pub fn ex_flags(mut self, flags: ListViewExFlags) -> ListViewBuilder { self.ex_flags = Some(flags); self } pub fn ex_window_flags(mut self, flags: u32) -> ListViewBuilder { self.ex_window_flags = flags; self } pub fn size(mut self, size: (i32, i32)) -> ListViewBuilder { self.size = size; self } pub fn position(mut self, position: (i32, i32)) -> ListViewBuilder { self.position = position; self } pub fn double_buffer(mut self, buffer: bool) -> ListViewBuilder { self.double_buffer = buffer; self } pub fn background_color(mut self, color: [u8; 3]) -> ListViewBuilder { self.background_color = Some(color); self } pub fn text_color(mut self, color: [u8; 3]) -> ListViewBuilder { self.text_color = Some(color); self } pub fn item_count(mut self, count: u32) -> ListViewBuilder { self.item_count = count; self } pub fn list_style(mut self, style: ListViewStyle) -> ListViewBuilder { self.style = style; self } pub fn focus(mut self, focus: bool) -> ListViewBuilder { self.focus = focus; self } pub fn build(self, out: &mut ListView) -> Result<(), NwgError> { let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags()); flags |= self.style.bits(); let parent = match self.parent { Some(p) => Ok(p), None => Err(NwgError::no_parent("ListView")) }?; *out = Default::default(); out.handle = ControlBase::build_hwnd() .class_name(out.class_name()) .forced_flags(out.forced_flags()) .flags(flags) .ex_flags(self.ex_window_flags) .size(self.size) .position(self.position) .text("") .parent(Some(parent)) .build()?; if self.double_buffer { out.set_double_buffered(); } if self.item_count > 0 { out.set_item_count(self.item_count); } if self.focus { out.set_focus(); } if let Some(flags) = self.ex_flags { let flags = flags.bits(); wh::send_message(out.handle.hwnd().unwrap(), LVM_SETEXTENDEDLISTVIEWSTYLE, flags as _, flags as _); } if let Some([r, g, b]) = self.background_color { out.set_background_color(r, g, b); } if let Some([r, g, b]) = self.text_color { out.set_text_color(r, g, b); } Ok(()) } } impl<'a> From<&'a str> for InsertListViewItem { fn from(i: &'a str) -> Self { InsertListViewItem { index: None, column_index: 0, text: Some(i.to_string()), #[cfg(feature="image-list")] image: None } } } impl From<String> for InsertListViewItem { fn from(i: String) -> Self { InsertListViewItem { index: None, column_index: 0, text: Some(i), #[cfg(feature="image-list")] image: None } } } impl<'a> From<&'a str> for InsertListViewColumn { fn from(i: &'a str) -> Self { InsertListViewColumn { index: None, fmt: None, width: Some(100), text: Some(i.to_string()) } } } impl From<String> for InsertListViewColumn { fn from(i: String) -> Self { InsertListViewColumn { index: None, fmt: None, width: Some(100), text: Some(i) } } } // Feature check #[cfg(feature="image-list")] fn check_image_mask(i: &InsertListViewItem) -> u32 { if i.image.is_some() { LVIF_IMAGE } else { 0 } } #[cfg(feature="image-list")] fn check_image(i: &InsertListViewItem) -> i32 { i.image.unwrap_or(0) } #[cfg(not(feature="image-list"))] fn check_image_mask(_i: &InsertListViewItem) -> u32 { 0 } #[cfg(not(feature="image-list"))] fn check_image(_i: &InsertListViewItem) -> i32 { 0 } #[cfg(feature="image-list")] fn build_list_view_image(row_index: usize, column_index: usize, state: u32, text_buffer: &[u16], image: i32) -> ListViewItem { use winapi::um::commctrl::LVIS_SELECTED; ListViewItem { row_index: row_index as _, column_index: column_index as _, text: from_utf16(&text_buffer), selected: state & LVIS_SELECTED == LVIS_SELECTED, image } } #[cfg(not(feature="image-list"))] fn build_list_view_image(row_index: usize, column_index: usize, state: u32, text_buffer: &[u16], _image: i32) -> ListViewItem { use winapi::um::commctrl::LVIS_SELECTED; ListViewItem { row_index: row_index as _, column_index: column_index as _, text: from_utf16(&text_buffer), selected: state & LVIS_SELECTED == LVIS_SELECTED, } }
use amcl::{ bls381::{big::Big, bls381::utils}, errors::AmclError, }; use log::trace; pub const SIG_SIZE: usize = 48; const DST: &[u8] = b"MEROS-V00-CS01-with-BLS12381G1_XMD:SHA-256_SSWU_RO_"; #[derive(Clone)] pub struct SecretKey(Big); impl SecretKey { pub fn new(bytes: &[u8]) -> Result<SecretKey, AmclError> { utils::secret_key_from_bytes(bytes).map(SecretKey) } pub fn sign(&self, msg: &[u8]) -> [u8; SIG_SIZE] { let hash = utils::hash_to_curve_g1(msg, DST); let signature = amcl::bls381::pair::g1mul(&hash, &self.0); let sig = utils::serialize_g1(&signature); trace!( "signing {} -> {}", hex::encode_upper(msg), // TODO: remove cast once we update our minimum rust version enough hex::encode_upper(&sig as &[u8]) ); sig } pub fn get_public_key(&self) -> [u8; 96] { let point = amcl::bls381::pair::g2mul(&amcl::bls381::ecp2::ECP2::generator(), &self.0); utils::serialize_g2(&point) } }
use super::*; #[derive(Default)] pub struct Blockchain { pub blocks: Vec<Block>, index: usize, } impl Blockchain { pub fn new() -> Self { Blockchain { blocks: Vec::new(), index: 0, } } pub fn add_block(&mut self, payload: String, difficulty: u128) { if self.blocks.is_empty() { let prev_block_hash = vec![0; 32]; self.create_block(prev_block_hash, payload, difficulty); } else { let prev_block_hash = self.blocks[self.index].hash.clone(); self.index += 1; self.create_block(prev_block_hash, payload, difficulty); } } fn create_block(&mut self, prev_block_hash: Vec<u8>, payload: String, difficulty: u128) { self.blocks.push(Block::new( self.index, now(), prev_block_hash, 0, payload, difficulty, )); self.blocks[self.index].mine(); println!("{:x?}", self.blocks[self.index]); println!("Verify: {}", &self.verify()); } pub fn verify(&self) -> bool { for (i, block) in self.blocks.iter().enumerate() { if block.index != i { println!("Index mismatch {} != {}", &block.index, &i,); return false; } else if !block::check_difficulty(&block.hash(), block.difficulty) { println!("Difficulty fail"); return false; } else if i != 0 { // not genesis let prev_block = &self.blocks[i - 1]; if block.timestamp <= prev_block.timestamp { println!("Time did not increase"); return false; } else if block.prev_block_hash != prev_block.hash { println!("Hash mismatch"); } } else { // genesis if block.prev_block_hash != vec![0; 32] { println!("Genesis block prev_block_hash invalid"); return false; } } } true } }
use atoms::{Location, Token}; use ast::Type; use ast::expressions::Expression; use traits::HasLocation; use std::fmt; #[derive(Debug)] pub struct DeclAssignStmt { pub identifier: Token, pub colon: Token, /// /// The type of the binding being declared /// (optional, will be inferred if not specified). /// pub type_of: Option<Type>, pub assign_op: Token, // '=' if mutable, ':' if immutable. pub expr: Expression, pub semicolon: Option<Token>, } impl HasLocation for DeclAssignStmt { fn start(&self) -> Location { self.identifier.start() } } impl fmt::Display for DeclAssignStmt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Declation of {}", self.identifier.string) } } #[derive(Debug)] pub struct DeclStmt { pub identifier: Token, pub colon: Token, /// /// The type of the binding being declared /// (not optional in this case). /// pub type_of: Type, pub semicolon: Token, } impl HasLocation for DeclStmt { fn start(&self) -> Location { self.identifier.start() } } impl fmt::Display for DeclStmt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Declation of {}", self.identifier.string) } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use std::collections::HashMap; use std::sync::Arc; use common_exception::ErrorCode; use common_infallible::RwLock; use common_meta_types::CreateDatabaseReply; use common_meta_types::CreateTableReply; use common_meta_types::DatabaseInfo; use common_meta_types::MetaId; use common_meta_types::MetaVersion; use common_meta_types::TableInfo; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DropDatabasePlan; use common_planners::DropTablePlan; use crate::catalogs::backends::MetaApiSync; use crate::catalogs::table_id_ranges::LOCAL_TBL_ID_BEGIN; /// This catalog backend used for test only. struct InMemoryTableInfo { pub(crate) name2meta: HashMap<String, Arc<TableInfo>>, pub(crate) id2meta: HashMap<MetaId, Arc<TableInfo>>, } impl InMemoryTableInfo { pub fn create() -> Self { Self { name2meta: HashMap::default(), id2meta: HashMap::default(), } } pub fn insert(&mut self, table_info: TableInfo) { let met_ref = Arc::new(table_info); self.name2meta .insert(met_ref.name.to_owned(), met_ref.clone()); self.id2meta.insert(met_ref.table_id, met_ref); } } type Databases = Arc<RwLock<HashMap<String, (Arc<DatabaseInfo>, InMemoryTableInfo)>>>; pub struct MetaEmbeddedSync { databases: Databases, tbl_id_seq: Arc<RwLock<u64>>, } impl MetaEmbeddedSync { pub fn create() -> Self { let tbl_id_seq = Arc::new(RwLock::new(LOCAL_TBL_ID_BEGIN)); Self { databases: Default::default(), tbl_id_seq, } } fn next_db_id(&self) -> u64 { *self.tbl_id_seq.write() += 1; let r = self.tbl_id_seq.read(); *r } } impl MetaApiSync for MetaEmbeddedSync { fn create_database( &self, plan: CreateDatabasePlan, ) -> common_exception::Result<CreateDatabaseReply> { let db_name = plan.db.as_str(); let mut db = self.databases.write(); if db.get(db_name).is_some() { return if plan.if_not_exists { // TODO(xp): just let it pass. This file will be removed as soon as common/kv provides full meta-APIs. Ok(CreateDatabaseReply { database_id: 0 }) } else { Err(ErrorCode::DatabaseAlreadyExists(format!( "Database: '{}' already exists.", db_name ))) }; } let database_info = DatabaseInfo { // TODO(xp): just let it pass. This file will be removed as soon as common/kv provides full meta-APIs. database_id: 0, db: db_name.to_string(), }; db.insert( plan.db, (Arc::new(database_info), InMemoryTableInfo::create()), ); // TODO(xp): just let it pass. This file will be removed as soon as common/kv provides full meta-APIs. Ok(CreateDatabaseReply { database_id: 0 }) } fn drop_database(&self, plan: DropDatabasePlan) -> common_exception::Result<()> { let db_name = plan.db.as_str(); let removed = { let mut dbs = self.databases.write(); dbs.remove(db_name) }; if removed.is_some() { return Ok(()); } // removed.is_none() if plan.if_exists { Ok(()) } else { Err(ErrorCode::UnknownDatabase(format!( "Unknown database: '{}'", db_name ))) } } fn get_database(&self, db_name: &str) -> common_exception::Result<Arc<DatabaseInfo>> { let lock = self.databases.read(); let db = lock.get(db_name); match db { None => Err(ErrorCode::UnknownDatabase(format!( "Unknown database: '{}'", db_name ))), Some((v, _)) => Ok(v.clone()), } } fn get_databases(&self) -> common_exception::Result<Vec<Arc<DatabaseInfo>>> { let mut res = vec![]; let lock = self.databases.read(); let values = lock.values(); for (db, _) in values { res.push(db.clone()); } Ok(res) } fn create_table(&self, plan: CreateTablePlan) -> common_exception::Result<CreateTableReply> { let clone = plan.clone(); let db_name = clone.db.as_str(); let table_name = clone.table.as_str(); let table_info = TableInfo { database_id: 0, // TODO tobe assigned to some real value db: plan.db, table_id: self.next_db_id(), version: 0, name: plan.table, schema: plan.schema, options: plan.options, engine: plan.engine, }; let mut lock = self.databases.write(); let v = lock.get_mut(db_name); match v { None => { return Err(ErrorCode::UnknownDatabase(format!( "Unknown database: {}", db_name ))); } Some((_db_info, metas)) => { if metas.name2meta.get(table_name).is_some() { if plan.if_not_exists { // TODO(xp): just let it passed, gonna be removed return Ok(CreateTableReply { table_id: 0 }); } else { return Err(ErrorCode::TableAlreadyExists(format!( "Table: '{}.{}' already exists.", db_name, table_name, ))); }; } metas.insert(table_info); } } // TODO(xp): just let it passed, gonna be removed Ok(CreateTableReply { table_id: 0 }) } fn drop_table(&self, plan: DropTablePlan) -> common_exception::Result<()> { let db_name = plan.db.as_str(); let table_name = plan.table.as_str(); let mut lock = self.databases.write(); let v = lock.get(db_name); let tbl_id = match v { None => { return Err(ErrorCode::UnknownDatabase(format!( "Unknown database: {}", db_name ))) } Some((_, metas)) => { let by_name = metas.name2meta.get(table_name); match by_name { None => { if plan.if_exists { return Ok(()); } else { return Err(ErrorCode::UnknownTable(format!( "Unknown table: '{}.{}'", db_name, table_name ))); } } Some(tbl) => tbl.table_id, } } }; let v = lock.get_mut(db_name); match v { None => { return Err(ErrorCode::UnknownDatabase(format!( "Unknown database: {}", db_name ))) } Some((_, metas)) => { metas.name2meta.remove(table_name); metas.id2meta.remove(&tbl_id); } } Ok(()) } fn get_table( &self, db_name: &str, table_name: &str, ) -> common_exception::Result<Arc<TableInfo>> { let lock = self.databases.read(); let v = lock.get(db_name); match v { None => Err(ErrorCode::UnknownDatabase(format!( "Unknown database: {}", db_name ))), Some((_, metas)) => { let table = metas.name2meta.get(table_name).ok_or_else(|| { ErrorCode::UnknownTable(format!("Unknown table: '{}'", table_name)) })?; Ok(table.clone()) } } } fn get_tables(&self, db_name: &str) -> common_exception::Result<Vec<Arc<TableInfo>>> { let mut res = vec![]; let lock = self.databases.read(); let v = lock.get(db_name); match v { None => { return Err(ErrorCode::UnknownDatabase(format!( "Unknown database: {}", db_name ))); } Some((_, metas)) => { for meta in metas.name2meta.values() { res.push(meta.clone()); } } } Ok(res) } fn get_table_by_id( &self, table_id: MetaId, _table_version: Option<MetaVersion>, ) -> common_exception::Result<Arc<TableInfo>> { let map = self.databases.read(); for (_, tbl_idx) in map.values() { match tbl_idx.id2meta.get(&table_id) { None => { continue; } Some(tbl) => { return Ok(tbl.clone()); } } } Err(ErrorCode::UnknownTable(format!( "Unknown table of id: {}", table_id ))) } fn name(&self) -> String { "embedded metastore backend".to_owned() } }
use std::iter::FromIterator; fn scan_polymer(input: String) -> String { let mut units: Vec<_> = input.chars().collect(); let mut idx = 0; let mut current = *units.get(0).unwrap(); while idx + 1 < units.len() { let next = *units.get(idx + 1).unwrap(); if reacts(current, next) { units.remove(idx + 1); units.remove(idx); idx = if idx as i32 - 2 < 0 { 0 } else { idx - 2 }; current = *units.get(idx).unwrap(); } else { idx += 1; current = next; } } String::from_iter(units) } fn reacts(a: char, b: char) -> bool { a != b && a.to_lowercase().to_string() == b.to_lowercase().to_string() } fn main() { let input = include_str!("input.txt").into(); println!("{}", scan_polymer(input).len()); } #[test] fn test_05() { let input = "dabAcCaCBAcCcaDA".into(); let result = scan_polymer(input); assert_eq!(result.len(), 10); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Code generated by tools/fidl/gidl-conformance-suite/regen.sh; DO NOT EDIT. use fidl::{ encoding::{Context, Decodable, Decoder, Encoder}, Error, }; use fidl_conformance as conformance; const OLD_CONTEXT: &Context = &Context { unions_use_xunion_format: false }; const V1_CONTEXT: &Context = &Context { unions_use_xunion_format: true }; #[test] fn test_3_byte_object_alignment_in_struct_encode() { let value = &mut conformance::ThreeByteInStruct { elem1: conformance::ThreeByte { elem1: 1u8, elem2: 2u8, elem3: 3u8 }, elem2: conformance::ThreeByte { elem1: 4u8, elem2: 5u8, elem3: 6u8 }, elem3: conformance::ThreeByte { elem1: 7u8, elem2: 8u8, elem3: 9u8 }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_5_byte_object_alignment_in_struct_encode() { let value = &mut conformance::FiveByteInStruct { elem1: conformance::FiveByte { elem1: 16909060u32, elem2: 5u8 }, elem2: conformance::FiveByte { elem1: 101124105u32, elem2: 10u8 }, elem3: conformance::FiveByte { elem1: 185339150u32, elem2: 15u8 }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x04, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b, 0x0f, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_3_byte_object_alignment_in_vector_encode() { let value = &mut conformance::ThreeByteInVector { elems: vec![ conformance::ThreeByte { elem1: 1u8, elem2: 2u8, elem3: 3u8 }, conformance::ThreeByte { elem1: 4u8, elem2: 5u8, elem3: 6u8 }, conformance::ThreeByte { elem1: 7u8, elem2: 8u8, elem3: 9u8 }, ], }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_5_byte_object_alignment_in_vector_encode() { let value = &mut conformance::FiveByteInVector { elems: vec![ conformance::FiveByte { elem1: 16909060u32, elem2: 5u8 }, conformance::FiveByte { elem1: 101124105u32, elem2: 10u8 }, conformance::FiveByte { elem1: 185339150u32, elem2: 15u8 }, ], }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x04, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b, 0x0f, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_3_byte_object_alignment_in_array_encode() { let value = &mut conformance::ThreeByteInArray { elems: [ conformance::ThreeByte { elem1: 1u8, elem2: 2u8, elem3: 3u8 }, conformance::ThreeByte { elem1: 4u8, elem2: 5u8, elem3: 6u8 }, conformance::ThreeByte { elem1: 7u8, elem2: 8u8, elem3: 9u8 }, ], }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_5_byte_object_alignment_in_array_encode() { let value = &mut conformance::FiveByteInArray { elems: [ conformance::FiveByte { elem1: 16909060u32, elem2: 5u8 }, conformance::FiveByte { elem1: 101124105u32, elem2: 10u8 }, conformance::FiveByte { elem1: 185339150u32, elem2: 15u8 }, ], }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x04, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b, 0x0f, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_empty_struct_encode() { let value = &mut conformance::EmptyStruct {}; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_empty_struct_sandwich_encode() { let value = &mut conformance::EmptyStructSandwich { before: String::from("before"), es: conformance::EmptyStruct {}, after: String::from("after"), }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_uint8_uint16_uint32_uint64_encode() { let value = &mut conformance::Uint8Uint16Uint32Uint64 { f1: 1u8, f2: 515u16, f3: 67438087u32, f4: 579005069656919567u64, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x01, 0x00, 0x03, 0x02, 0x07, 0x06, 0x05, 0x04, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, ][..] ); } #[test] fn test_uint64_uint32_uint16_uint8_encode() { let value = &mut conformance::Uint64Uint32Uint16Uint8 { f1: 579005069656919567u64, f2: 67438087u32, f3: 515u16, f4: 1u8, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, ][..] ); } #[test] fn test_simple_table_empty_encode() { let value = &mut conformance::StructOfSimpleTable { table: conformance::SimpleTable { x: None, y: None }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ][..] ); } #[test] fn test_simple_table_x_and_y_encode() { let value = &mut conformance::StructOfSimpleTable { table: conformance::SimpleTable { x: Some(42i64), y: Some(67i64) }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_simple_table_just_y_encode() { let value = &mut conformance::StructOfSimpleTable { table: conformance::SimpleTable { y: Some(67i64), x: None }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_table_with_string_and_vector_no_vector_content_encode() { let value = &mut conformance::StructOfTableWithStringAndVector { table: conformance::TableWithStringAndVector { foo: Some(String::from("hello")), bar: Some(27i32), baz: None, }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_simple_table_then_uint64_encode() { let value = &mut conformance::SimpleTableThenUint64 { table: conformance::SimpleTable { x: Some(42i64), y: Some(67i64) }, number: 16045690984833335023u64, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xbe, 0xad, 0xde, 0xef, 0xbe, 0xad, 0xde, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_inline_x_union_in_struct_encode() { let value = &mut conformance::TestInlineXUnionInStruct { before: String::from("before"), xu: conformance::SampleXUnion::U(3735928559u32), after: String::from("after"), }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb2, 0x56, 0x9c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_optional_x_union_in_struct_absent_encode() { let value = &mut conformance::TestOptionalXUnionInStruct { before: String::from("before"), after: String::from("after"), xu: None, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_optional_x_union_in_struct_present_encode() { let value = &mut conformance::TestOptionalXUnionInStruct { before: String::from("before"), xu: Some(Box::new(conformance::SampleXUnion::U(3735928559u32))), after: String::from("after"), }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb2, 0x56, 0x9c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_x_union_in_table_x_union_absent_encode() { let value = &mut conformance::TestXUnionInTable { value: conformance::XUnionInTable { before: Some(String::from("before")), after: Some(String::from("after")), xu: None, }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_x_union_in_table_x_union_present_encode() { let value = &mut conformance::TestXUnionInTable { value: conformance::XUnionInTable { before: Some(String::from("before")), xu: Some(conformance::SampleXUnion::U(3735928559u32)), after: Some(String::from("after")), }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0xb2, 0x56, 0x9c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_strict_x_union_encode() { let value = &mut conformance::TestStrictXUnionInStruct { xu: conformance::SampleStrictXUnion::U(3735928559u32), }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x72, 0xea, 0xe2, 0x08, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_add_ethernet_device_request_encode() { let value = &mut conformance::TestAddEthernetDeviceRequest { topological_path: String::from("@/dev/sys/pci/00:03.0/e1000/ethernet"), config: conformance::InterfaceConfig { name: String::from("ethp0003"), ip_address_config: conformance::IpAddressConfig::Dhcp(true), }, this_should_be_a_handle: 4294967295u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x40, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x73, 0x79, 0x73, 0x2f, 0x70, 0x63, 0x69, 0x2f, 0x30, 0x30, 0x3a, 0x30, 0x33, 0x2e, 0x30, 0x2f, 0x65, 0x31, 0x30, 0x30, 0x30, 0x2f, 0x65, 0x74, 0x68, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x00, 0x00, 0x00, 0x00, 0x65, 0x74, 0x68, 0x70, 0x30, 0x30, 0x30, 0x33, ][..] ); } #[test] fn test_file_get_attr_response_encode() { let value = &mut conformance::FileGetAttrResponse { s: 2125315759i32, attributes: conformance::NodeAttributes { mode: 2518909348u32, id: 1u64, content_size: 231u64, storage_size: 231u64, link_count: 1u64, creation_time: 9833440827789222417u64, modification_time: 72038755451251353u64, }, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0xaf, 0xbe, 0xad, 0x7e, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x23, 0x96, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, ][..] ); } #[test] fn test_optionals_encode() { let value = &mut conformance::StructWithOptionals { s: conformance::EmptyStruct {}, s2: Some(Box::new(conformance::EmptyStruct {})), t: conformance::TableWithEmptyStruct { s: Some(conformance::EmptyStruct {}) }, xu: conformance::XUnionWithEmptyStruct::S(conformance::EmptyStruct {}), xu2: Some(Box::new(conformance::XUnionWithEmptyStruct::S(conformance::EmptyStruct {}))), u: conformance::UnionWithEmptyStruct::S(conformance::EmptyStruct {}), u2: Some(Box::new(conformance::UnionWithEmptyStruct::S(conformance::EmptyStruct {}))), }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xe0, 0x99, 0x74, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xe0, 0x99, 0x74, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_arrays_encode() { let value = &mut conformance::StructWithArrays { arr_int: [1i32, 2i32], arr_string: [String::from("a"), String::from("b")], arr_nullable_string: [Some(String::from("c")), None], arr_struct: [ conformance::StructWithInt { x: 1i32 }, conformance::StructWithInt { x: 2i32 }, ], arr_nullable_struct: [None, Some(Box::new(conformance::StructWithInt { x: 16909060i32 }))], arr_arr_int: [[1i32, 2i32, 3i32], [4i32, 5i32, 6i32]], }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_vectors_encode() { let value = &mut conformance::StructWithVectors { vec_empty: vec![], vec_int: vec![1i32, 2i32], vec_string: vec![String::from("a"), String::from("b")], vec_nullable_string: vec![None, Some(String::from("c")), None], vec_struct: vec![conformance::StructWithInt { x: 1i32 }], vec_nullable_struct: vec![ None, None, Some(Box::new(conformance::StructWithInt { x: 2i32 })), ], vec_vec_int: vec![vec![1i32, 2i32], vec![3i32]], }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_bool_true_encode() { let value = &mut conformance::MyBool { value: true }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_bool_false_encode() { let value = &mut conformance::MyBool { value: false }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_byte_zero_encode() { let value = &mut conformance::MyByte { value: 0u8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_byte255_encode() { let value = &mut conformance::MyByte { value: 255u8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int8_min_encode() { let value = &mut conformance::MyInt8 { value: -128i8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int8_zero_encode() { let value = &mut conformance::MyInt8 { value: 0i8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int8_max_encode() { let value = &mut conformance::MyInt8 { value: 127i8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int16_min_encode() { let value = &mut conformance::MyInt16 { value: -32768i16 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int16_zero_encode() { let value = &mut conformance::MyInt16 { value: 0i16 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int16_max_encode() { let value = &mut conformance::MyInt16 { value: 32767i16 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int32_min_encode() { let value = &mut conformance::MyInt32 { value: -2147483648i32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int32_zero_encode() { let value = &mut conformance::MyInt32 { value: 0i32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int32_max_encode() { let value = &mut conformance::MyInt32 { value: 2147483647i32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int64_min_encode() { let value = &mut conformance::MyInt64 { value: -9223372036854775808i64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,][..]); } #[test] fn test_int64_zero_encode() { let value = &mut conformance::MyInt64 { value: 0i64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_int64_max_encode() { let value = &mut conformance::MyInt64 { value: 9223372036854775807i64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,][..]); } #[test] fn test_uint8_zero_encode() { let value = &mut conformance::MyUint8 { value: 0u8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint8_max_encode() { let value = &mut conformance::MyUint8 { value: 255u8 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint16_zero_encode() { let value = &mut conformance::MyUint16 { value: 0u16 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint16_max_encode() { let value = &mut conformance::MyUint16 { value: 65535u16 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint32_zero_encode() { let value = &mut conformance::MyUint32 { value: 0u32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint32_max_encode() { let value = &mut conformance::MyUint32 { value: 4294967295u32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint64_zero_encode() { let value = &mut conformance::MyUint64 { value: 0u64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_uint64_max_encode() { let value = &mut conformance::MyUint64 { value: 18446744073709551615u64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,][..]); } #[test] fn test_float32_zero_encode() { let value = &mut conformance::MyFloat32 { value: 0f32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_float32_one_encode() { let value = &mut conformance::MyFloat32 { value: 1f32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_float32_minus_one_encode() { let value = &mut conformance::MyFloat32 { value: -1f32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_float32_max_encode() { let value = &mut conformance::MyFloat32 { value: 3.4028234663852886e+38f32 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0x7f, 0x7f, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_float64_zero_encode() { let value = &mut conformance::MyFloat64 { value: 0f64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,][..]); } #[test] fn test_float64_one_encode() { let value = &mut conformance::MyFloat64 { value: 1f64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f,][..]); } #[test] fn test_float64_minus_one_encode() { let value = &mut conformance::MyFloat64 { value: -1f64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xbf,][..]); } #[test] fn test_float64_max_encode() { let value = &mut conformance::MyFloat64 { value: 1.7976931348623157e+308f64 }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f,][..]); } #[test] fn test_union_with_bound_string_encode() { let value = &mut conformance::UnionWithBoundStringStruct { v: conformance::UnionWithBoundString::BoundFiveStr(String::from("abcd")), }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x62, 0x63, 0x64, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_migration_single_variant_encode() { let value = &mut conformance::SingleVariantUnionStruct { u: conformance::SingleVariantUnion::X(42u32) }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!(*bytes, &[0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00,][..]); } #[test] fn test_union_migration_single_variant_v1_encode() { let value = &mut conformance::SingleVariantUnionStruct { u: conformance::SingleVariantUnion::X(42u32) }; let bytes = &mut Vec::new(); Encoder::encode_with_context(V1_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size8_alignment4_encode() { let value = &mut conformance::SandwichUnionSize8Alignment4 { before: 10u32, union: conformance::UnionSize8Alignment4::Variant(4u32), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size8_alignment4_v1_encode() { let value = &mut conformance::SandwichUnionSize8Alignment4 { before: 10u32, union: conformance::UnionSize8Alignment4::Variant(4u32), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(V1_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size12_alignment4_encode() { let value = &mut conformance::SandwichUnionSize12Alignment4 { before: 10u32, union: conformance::UnionSize12Alignment4::Variant([1u8, 2u8, 3u8, 4u8, 5u8, 6u8]), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size12_alignment4_v1_encode() { let value = &mut conformance::SandwichUnionSize12Alignment4 { before: 10u32, union: conformance::UnionSize12Alignment4::Variant([1u8, 2u8, 3u8, 4u8, 5u8, 6u8]), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(V1_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x00, ][..] ); } #[test] fn test_union_size24_alignment8_encode() { let value = &mut conformance::SandwichUnionSize24Alignment8 { before: 10u32, union: conformance::UnionSize24Alignment8::Variant(conformance::StructSize16Alignment8 { f1: 1u64, f2: 2u64, }), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size24_alignment8_v1_encode() { let value = &mut conformance::SandwichUnionSize24Alignment8 { before: 10u32, union: conformance::UnionSize24Alignment8::Variant(conformance::StructSize16Alignment8 { f1: 1u64, f2: 2u64, }), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(V1_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size36_alignment4_encode() { let value = &mut conformance::SandwichUnionSize36Alignment4 { before: 10u32, union: conformance::UnionSize36Alignment4::Variant([ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 17u8, 18u8, 19u8, 20u8, 21u8, 22u8, 23u8, 24u8, 25u8, 26u8, 27u8, 28u8, 29u8, 30u8, 31u8, 32u8, ]), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(OLD_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ][..] ); } #[test] fn test_union_size36_alignment4_v1_encode() { let value = &mut conformance::SandwichUnionSize36Alignment4 { before: 10u32, union: conformance::UnionSize36Alignment4::Variant([ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 17u8, 18u8, 19u8, 20u8, 21u8, 22u8, 23u8, 24u8, 25u8, 26u8, 27u8, 28u8, 29u8, 30u8, 31u8, 32u8, ]), after: 20u32, }; let bytes = &mut Vec::new(); Encoder::encode_with_context(V1_CONTEXT, bytes, &mut Vec::new(), value).unwrap(); assert_eq!( *bytes, &[ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, ][..] ); } #[test] fn test_3_byte_object_alignment_in_struct_decode() { let value = &mut conformance::ThreeByteInStruct::new_empty(); let bytes = &mut [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::ThreeByteInStruct { elem1: conformance::ThreeByte { elem1: 1u8, elem2: 2u8, elem3: 3u8 }, elem2: conformance::ThreeByte { elem1: 4u8, elem2: 5u8, elem3: 6u8 }, elem3: conformance::ThreeByte { elem1: 7u8, elem2: 8u8, elem3: 9u8 } } ); } #[test] fn test_5_byte_object_alignment_in_struct_decode() { let value = &mut conformance::FiveByteInStruct::new_empty(); let bytes = &mut [ 0x04, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b, 0x0f, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::FiveByteInStruct { elem1: conformance::FiveByte { elem1: 16909060u32, elem2: 5u8 }, elem2: conformance::FiveByte { elem1: 101124105u32, elem2: 10u8 }, elem3: conformance::FiveByte { elem1: 185339150u32, elem2: 15u8 } } ); } #[test] fn test_3_byte_object_alignment_in_vector_decode() { let value = &mut conformance::ThreeByteInVector::new_empty(); let bytes = &mut [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::ThreeByteInVector { elems: vec![ conformance::ThreeByte { elem1: 1u8, elem2: 2u8, elem3: 3u8 }, conformance::ThreeByte { elem1: 4u8, elem2: 5u8, elem3: 6u8 }, conformance::ThreeByte { elem1: 7u8, elem2: 8u8, elem3: 9u8 } ] } ); } #[test] fn test_5_byte_object_alignment_in_vector_decode() { let value = &mut conformance::FiveByteInVector::new_empty(); let bytes = &mut [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x04, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b, 0x0f, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::FiveByteInVector { elems: vec![ conformance::FiveByte { elem1: 16909060u32, elem2: 5u8 }, conformance::FiveByte { elem1: 101124105u32, elem2: 10u8 }, conformance::FiveByte { elem1: 185339150u32, elem2: 15u8 } ] } ); } #[test] fn test_3_byte_object_alignment_in_array_decode() { let value = &mut conformance::ThreeByteInArray::new_empty(); let bytes = &mut [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::ThreeByteInArray { elems: [ conformance::ThreeByte { elem1: 1u8, elem2: 2u8, elem3: 3u8 }, conformance::ThreeByte { elem1: 4u8, elem2: 5u8, elem3: 6u8 }, conformance::ThreeByte { elem1: 7u8, elem2: 8u8, elem3: 9u8 } ] } ); } #[test] fn test_5_byte_object_alignment_in_array_decode() { let value = &mut conformance::FiveByteInArray::new_empty(); let bytes = &mut [ 0x04, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b, 0x0f, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::FiveByteInArray { elems: [ conformance::FiveByte { elem1: 16909060u32, elem2: 5u8 }, conformance::FiveByte { elem1: 101124105u32, elem2: 10u8 }, conformance::FiveByte { elem1: 185339150u32, elem2: 15u8 } ] } ); } #[test] fn test_empty_struct_decode() { let value = &mut conformance::EmptyStruct::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::EmptyStruct {}); } #[test] fn test_empty_struct_sandwich_decode() { let value = &mut conformance::EmptyStructSandwich::new_empty(); let bytes = &mut [ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::EmptyStructSandwich { before: String::from("before"), es: conformance::EmptyStruct {}, after: String::from("after") } ); } #[test] fn test_uint8_uint16_uint32_uint64_decode() { let value = &mut conformance::Uint8Uint16Uint32Uint64::new_empty(); let bytes = &mut [ 0x01, 0x00, 0x03, 0x02, 0x07, 0x06, 0x05, 0x04, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::Uint8Uint16Uint32Uint64 { f1: 1u8, f2: 515u16, f3: 67438087u32, f4: 579005069656919567u64 } ); } #[test] fn test_uint64_uint32_uint16_uint8_decode() { let value = &mut conformance::Uint64Uint32Uint16Uint8::new_empty(); let bytes = &mut [ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::Uint64Uint32Uint16Uint8 { f1: 579005069656919567u64, f2: 67438087u32, f3: 515u16, f4: 1u8 } ); } #[test] fn test_simple_table_empty_decode() { let value = &mut conformance::StructOfSimpleTable::new_empty(); let bytes = &mut [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructOfSimpleTable { table: conformance::SimpleTable { x: None, y: None } } ); } #[test] fn test_simple_table_x_and_y_decode() { let value = &mut conformance::StructOfSimpleTable::new_empty(); let bytes = &mut [ 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructOfSimpleTable { table: conformance::SimpleTable { x: Some(42i64), y: Some(67i64) } } ); } #[test] fn test_simple_table_just_y_decode() { let value = &mut conformance::StructOfSimpleTable::new_empty(); let bytes = &mut [ 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructOfSimpleTable { table: conformance::SimpleTable { y: Some(67i64), x: None } } ); } #[test] fn test_table_with_string_and_vector_no_vector_content_decode() { let value = &mut conformance::StructOfTableWithStringAndVector::new_empty(); let bytes = &mut [ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructOfTableWithStringAndVector { table: conformance::TableWithStringAndVector { foo: Some(String::from("hello")), bar: Some(27i32), baz: None } } ); } #[test] fn test_simple_table_then_uint64_decode() { let value = &mut conformance::SimpleTableThenUint64::new_empty(); let bytes = &mut [ 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xbe, 0xad, 0xde, 0xef, 0xbe, 0xad, 0xde, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SimpleTableThenUint64 { table: conformance::SimpleTable { x: Some(42i64), y: Some(67i64) }, number: 16045690984833335023u64 } ); } #[test] fn test_inline_x_union_in_struct_decode() { let value = &mut conformance::TestInlineXUnionInStruct::new_empty(); let bytes = &mut [ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb2, 0x56, 0x9c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestInlineXUnionInStruct { before: String::from("before"), xu: conformance::SampleXUnion::U(3735928559u32), after: String::from("after") } ); } #[test] fn test_optional_x_union_in_struct_absent_decode() { let value = &mut conformance::TestOptionalXUnionInStruct::new_empty(); let bytes = &mut [ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestOptionalXUnionInStruct { before: String::from("before"), after: String::from("after"), xu: None } ); } #[test] fn test_optional_x_union_in_struct_present_decode() { let value = &mut conformance::TestOptionalXUnionInStruct::new_empty(); let bytes = &mut [ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb2, 0x56, 0x9c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestOptionalXUnionInStruct { before: String::from("before"), xu: Some(Box::new(conformance::SampleXUnion::U(3735928559u32))), after: String::from("after") } ); } #[test] fn test_x_union_in_table_x_union_absent_decode() { let value = &mut conformance::TestXUnionInTable::new_empty(); let bytes = &mut [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestXUnionInTable { value: conformance::XUnionInTable { before: Some(String::from("before")), after: Some(String::from("after")), xu: None } } ); } #[test] fn test_x_union_in_table_x_union_present_decode() { let value = &mut conformance::TestXUnionInTable::new_empty(); let bytes = &mut [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x00, 0x00, 0xb2, 0x56, 0x9c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestXUnionInTable { value: conformance::XUnionInTable { before: Some(String::from("before")), xu: Some(conformance::SampleXUnion::U(3735928559u32)), after: Some(String::from("after")) } } ); } #[test] fn test_strict_x_union_decode() { let value = &mut conformance::TestStrictXUnionInStruct::new_empty(); let bytes = &mut [ 0x72, 0xea, 0xe2, 0x08, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestStrictXUnionInStruct { xu: conformance::SampleStrictXUnion::U(3735928559u32) } ); } #[test] fn test_add_ethernet_device_request_decode() { let value = &mut conformance::TestAddEthernetDeviceRequest::new_empty(); let bytes = &mut [ 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x40, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x73, 0x79, 0x73, 0x2f, 0x70, 0x63, 0x69, 0x2f, 0x30, 0x30, 0x3a, 0x30, 0x33, 0x2e, 0x30, 0x2f, 0x65, 0x31, 0x30, 0x30, 0x30, 0x2f, 0x65, 0x74, 0x68, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x00, 0x00, 0x00, 0x00, 0x65, 0x74, 0x68, 0x70, 0x30, 0x30, 0x30, 0x33, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::TestAddEthernetDeviceRequest { topological_path: String::from("@/dev/sys/pci/00:03.0/e1000/ethernet"), config: conformance::InterfaceConfig { name: String::from("ethp0003"), ip_address_config: conformance::IpAddressConfig::Dhcp(true) }, this_should_be_a_handle: 4294967295u32 } ); } #[test] fn test_file_get_attr_response_decode() { let value = &mut conformance::FileGetAttrResponse::new_empty(); let bytes = &mut [ 0xaf, 0xbe, 0xad, 0x7e, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x23, 0x96, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::FileGetAttrResponse { s: 2125315759i32, attributes: conformance::NodeAttributes { mode: 2518909348u32, id: 1u64, content_size: 231u64, storage_size: 231u64, link_count: 1u64, creation_time: 9833440827789222417u64, modification_time: 72038755451251353u64 } } ); } #[test] fn test_optionals_decode() { let value = &mut conformance::StructWithOptionals::new_empty(); let bytes = &mut [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xe0, 0x99, 0x74, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xe0, 0x99, 0x74, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructWithOptionals { s: conformance::EmptyStruct {}, s2: Some(Box::new(conformance::EmptyStruct {})), t: conformance::TableWithEmptyStruct { s: Some(conformance::EmptyStruct {}) }, xu: conformance::XUnionWithEmptyStruct::S(conformance::EmptyStruct {}), xu2: Some(Box::new(conformance::XUnionWithEmptyStruct::S(conformance::EmptyStruct {}))), u: conformance::UnionWithEmptyStruct::S(conformance::EmptyStruct {}), u2: Some(Box::new(conformance::UnionWithEmptyStruct::S(conformance::EmptyStruct {}))) } ); } #[test] fn test_arrays_decode() { let value = &mut conformance::StructWithArrays::new_empty(); let bytes = &mut [ 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructWithArrays { arr_int: [1i32, 2i32], arr_string: [String::from("a"), String::from("b")], arr_nullable_string: [Some(String::from("c")), None], arr_struct: [ conformance::StructWithInt { x: 1i32 }, conformance::StructWithInt { x: 2i32 } ], arr_nullable_struct: [ None, Some(Box::new(conformance::StructWithInt { x: 16909060i32 })) ], arr_arr_int: [[1i32, 2i32, 3i32], [4i32, 5i32, 6i32]] } ); } #[test] fn test_vectors_decode() { let value = &mut conformance::StructWithVectors::new_empty(); let bytes = &mut [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::StructWithVectors { vec_empty: vec![], vec_int: vec![1i32, 2i32], vec_string: vec![String::from("a"), String::from("b")], vec_nullable_string: vec![None, Some(String::from("c")), None], vec_struct: vec![conformance::StructWithInt { x: 1i32 }], vec_nullable_struct: vec![ None, None, Some(Box::new(conformance::StructWithInt { x: 2i32 })) ], vec_vec_int: vec![vec![1i32, 2i32], vec![3i32]] } ); } #[test] fn test_bool_true_decode() { let value = &mut conformance::MyBool::new_empty(); let bytes = &mut [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyBool { value: true }); } #[test] fn test_bool_false_decode() { let value = &mut conformance::MyBool::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyBool { value: false }); } #[test] fn test_byte_zero_decode() { let value = &mut conformance::MyByte::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyByte { value: 0u8 }); } #[test] fn test_byte255_decode() { let value = &mut conformance::MyByte::new_empty(); let bytes = &mut [0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyByte { value: 255u8 }); } #[test] fn test_int8_min_decode() { let value = &mut conformance::MyInt8::new_empty(); let bytes = &mut [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt8 { value: -128i8 }); } #[test] fn test_int8_zero_decode() { let value = &mut conformance::MyInt8::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt8 { value: 0i8 }); } #[test] fn test_int8_max_decode() { let value = &mut conformance::MyInt8::new_empty(); let bytes = &mut [0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt8 { value: 127i8 }); } #[test] fn test_int16_min_decode() { let value = &mut conformance::MyInt16::new_empty(); let bytes = &mut [0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt16 { value: -32768i16 }); } #[test] fn test_int16_zero_decode() { let value = &mut conformance::MyInt16::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt16 { value: 0i16 }); } #[test] fn test_int16_max_decode() { let value = &mut conformance::MyInt16::new_empty(); let bytes = &mut [0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt16 { value: 32767i16 }); } #[test] fn test_int32_min_decode() { let value = &mut conformance::MyInt32::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt32 { value: -2147483648i32 }); } #[test] fn test_int32_zero_decode() { let value = &mut conformance::MyInt32::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt32 { value: 0i32 }); } #[test] fn test_int32_max_decode() { let value = &mut conformance::MyInt32::new_empty(); let bytes = &mut [0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt32 { value: 2147483647i32 }); } #[test] fn test_int64_min_decode() { let value = &mut conformance::MyInt64::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt64 { value: -9223372036854775808i64 }); } #[test] fn test_int64_zero_decode() { let value = &mut conformance::MyInt64::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt64 { value: 0i64 }); } #[test] fn test_int64_max_decode() { let value = &mut conformance::MyInt64::new_empty(); let bytes = &mut [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyInt64 { value: 9223372036854775807i64 }); } #[test] fn test_uint8_zero_decode() { let value = &mut conformance::MyUint8::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint8 { value: 0u8 }); } #[test] fn test_uint8_max_decode() { let value = &mut conformance::MyUint8::new_empty(); let bytes = &mut [0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint8 { value: 255u8 }); } #[test] fn test_uint16_zero_decode() { let value = &mut conformance::MyUint16::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint16 { value: 0u16 }); } #[test] fn test_uint16_max_decode() { let value = &mut conformance::MyUint16::new_empty(); let bytes = &mut [0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint16 { value: 65535u16 }); } #[test] fn test_uint32_zero_decode() { let value = &mut conformance::MyUint32::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint32 { value: 0u32 }); } #[test] fn test_uint32_max_decode() { let value = &mut conformance::MyUint32::new_empty(); let bytes = &mut [0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint32 { value: 4294967295u32 }); } #[test] fn test_uint64_zero_decode() { let value = &mut conformance::MyUint64::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint64 { value: 0u64 }); } #[test] fn test_uint64_max_decode() { let value = &mut conformance::MyUint64::new_empty(); let bytes = &mut [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyUint64 { value: 18446744073709551615u64 }); } #[test] fn test_float32_zero_decode() { let value = &mut conformance::MyFloat32::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat32 { value: 0f32 }); } #[test] fn test_float32_one_decode() { let value = &mut conformance::MyFloat32::new_empty(); let bytes = &mut [0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat32 { value: 1f32 }); } #[test] fn test_float32_minus_one_decode() { let value = &mut conformance::MyFloat32::new_empty(); let bytes = &mut [0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat32 { value: -1f32 }); } #[test] fn test_float32_max_decode() { let value = &mut conformance::MyFloat32::new_empty(); let bytes = &mut [0xff, 0xff, 0x7f, 0x7f, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat32 { value: 3.4028234663852886e+38f32 }); } #[test] fn test_float64_zero_decode() { let value = &mut conformance::MyFloat64::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat64 { value: 0f64 }); } #[test] fn test_float64_one_decode() { let value = &mut conformance::MyFloat64::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat64 { value: 1f64 }); } #[test] fn test_float64_minus_one_decode() { let value = &mut conformance::MyFloat64::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xbf]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat64 { value: -1f64 }); } #[test] fn test_float64_max_decode() { let value = &mut conformance::MyFloat64::new_empty(); let bytes = &mut [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!(*value, conformance::MyFloat64 { value: 1.7976931348623157e+308f64 }); } #[test] fn test_union_with_bound_string_decode() { let value = &mut conformance::UnionWithBoundStringStruct::new_empty(); let bytes = &mut [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x61, 0x62, 0x63, 0x64, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::UnionWithBoundStringStruct { v: conformance::UnionWithBoundString::BoundFiveStr(String::from("abcd")) } ); } #[test] fn test_union_migration_single_variant_decode() { let value = &mut conformance::SingleVariantUnionStruct::new_empty(); let bytes = &mut [0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SingleVariantUnionStruct { u: conformance::SingleVariantUnion::X(42u32) } ); } #[test] fn test_union_migration_single_variant_v1_decode() { let value = &mut conformance::SingleVariantUnionStruct::new_empty(); let bytes = &mut [ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(V1_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SingleVariantUnionStruct { u: conformance::SingleVariantUnion::X(42u32) } ); } #[test] fn test_union_size8_alignment4_decode() { let value = &mut conformance::SandwichUnionSize8Alignment4::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize8Alignment4 { before: 10u32, union: conformance::UnionSize8Alignment4::Variant(4u32), after: 20u32 } ); } #[test] fn test_union_size8_alignment4_v1_decode() { let value = &mut conformance::SandwichUnionSize8Alignment4::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(V1_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize8Alignment4 { before: 10u32, union: conformance::UnionSize8Alignment4::Variant(4u32), after: 20u32 } ); } #[test] fn test_union_size12_alignment4_decode() { let value = &mut conformance::SandwichUnionSize12Alignment4::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize12Alignment4 { before: 10u32, union: conformance::UnionSize12Alignment4::Variant([1u8, 2u8, 3u8, 4u8, 5u8, 6u8]), after: 20u32 } ); } #[test] fn test_union_size12_alignment4_v1_decode() { let value = &mut conformance::SandwichUnionSize12Alignment4::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x00, ]; Decoder::decode_with_context(V1_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize12Alignment4 { before: 10u32, union: conformance::UnionSize12Alignment4::Variant([1u8, 2u8, 3u8, 4u8, 5u8, 6u8]), after: 20u32 } ); } #[test] fn test_union_size24_alignment8_decode() { let value = &mut conformance::SandwichUnionSize24Alignment8::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize24Alignment8 { before: 10u32, union: conformance::UnionSize24Alignment8::Variant( conformance::StructSize16Alignment8 { f1: 1u64, f2: 2u64 } ), after: 20u32 } ); } #[test] fn test_union_size24_alignment8_v1_decode() { let value = &mut conformance::SandwichUnionSize24Alignment8::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(V1_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize24Alignment8 { before: 10u32, union: conformance::UnionSize24Alignment8::Variant( conformance::StructSize16Alignment8 { f1: 1u64, f2: 2u64 } ), after: 20u32 } ); } #[test] fn test_union_size36_alignment4_decode() { let value = &mut conformance::SandwichUnionSize36Alignment4::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize36Alignment4 { before: 10u32, union: conformance::UnionSize36Alignment4::Variant([ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 17u8, 18u8, 19u8, 20u8, 21u8, 22u8, 23u8, 24u8, 25u8, 26u8, 27u8, 28u8, 29u8, 30u8, 31u8, 32u8 ]), after: 20u32 } ); } #[test] fn test_union_size36_alignment4_v1_decode() { let value = &mut conformance::SandwichUnionSize36Alignment4::new_empty(); let bytes = &mut [ 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, ]; Decoder::decode_with_context(V1_CONTEXT, bytes, &mut [], value).unwrap(); assert_eq!( *value, conformance::SandwichUnionSize36Alignment4 { before: 10u32, union: conformance::UnionSize36Alignment4::Variant([ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 17u8, 18u8, 19u8, 20u8, 21u8, 22u8, 23u8, 24u8, 25u8, 26u8, 27u8, 28u8, 29u8, 30u8, 31u8, 32u8 ]), after: 20u32 } ); } #[test] fn test_non_empty_string_with_null_ptr_body_decode_failure() { let value = &mut conformance::StringWrapper::new_empty(); let bytes = &mut [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; match Decoder::decode_with_context(OLD_CONTEXT, bytes, &mut [], value) { Err(Error::UnexpectedNullRef { .. }) => (), Err(err) => panic!("unexpected error: {}", err), Ok(_) => panic!("unexpected successful decoding"), } }
#[doc = "Reader of register INI1_FN_MOD_AHB"] pub type R = crate::R<u32, super::INI1_FN_MOD_AHB>; #[doc = "Writer for register INI1_FN_MOD_AHB"] pub type W = crate::W<u32, super::INI1_FN_MOD_AHB>; #[doc = "Register INI1_FN_MOD_AHB `reset()`'s with value 0x04"] impl crate::ResetValue for super::INI1_FN_MOD_AHB { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x04 } } #[doc = "Reader of field `RD_INC_OVERRIDE`"] pub type RD_INC_OVERRIDE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RD_INC_OVERRIDE`"] pub struct RD_INC_OVERRIDE_W<'a> { w: &'a mut W, } impl<'a> RD_INC_OVERRIDE_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 `WR_INC_OVERRIDE`"] pub type WR_INC_OVERRIDE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WR_INC_OVERRIDE`"] pub struct WR_INC_OVERRIDE_W<'a> { w: &'a mut W, } impl<'a> WR_INC_OVERRIDE_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 } } impl R { #[doc = "Bit 0 - Converts all AHB-Lite write transactions to a series of single beat AXI"] #[inline(always)] pub fn rd_inc_override(&self) -> RD_INC_OVERRIDE_R { RD_INC_OVERRIDE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Converts all AHB-Lite read transactions to a series of single beat AXI"] #[inline(always)] pub fn wr_inc_override(&self) -> WR_INC_OVERRIDE_R { WR_INC_OVERRIDE_R::new(((self.bits >> 1) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Converts all AHB-Lite write transactions to a series of single beat AXI"] #[inline(always)] pub fn rd_inc_override(&mut self) -> RD_INC_OVERRIDE_W { RD_INC_OVERRIDE_W { w: self } } #[doc = "Bit 1 - Converts all AHB-Lite read transactions to a series of single beat AXI"] #[inline(always)] pub fn wr_inc_override(&mut self) -> WR_INC_OVERRIDE_W { WR_INC_OVERRIDE_W { w: self } } }
use std::fmt; #[derive(Clone, PartialEq)] struct SpinLock { buf: Vec<u64>, num: u64, cur: usize, step: usize, } impl fmt::Debug for SpinLock { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}", self.buf.iter().enumerate().map(|(ref i, ref s)| { if *i == self.cur { format!("({})", s) } else { format!("{}", s) } }).collect::<Vec<_>>().join(" ")) } } impl SpinLock { fn new(step: usize) -> SpinLock { let mut v = Vec::with_capacity(2018); v.insert(0, 0); SpinLock { buf: v, cur: 0, num: 0, step: step, } } fn advance(&mut self) -> Result<(), ()> { let new_cur = ((self.cur + self.step) % self.buf.len()) + 1; self.num += 1; self.cur = new_cur; self.buf.insert(new_cur, self.num); Ok(()) } fn next(&self) -> Option<u64> { if self.cur == self.buf.len() - 1 { None } else { Some(self.buf[self.cur + 1]) } } } fn run(a: usize) -> u64 { let mut s = SpinLock::new(a); for i in 0..2017 { s.advance(); } s.next().expect("WHOOPS") } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(run(3), 638); } #[test] fn answer() { println!("{}", run(324)); } }
#[path = "with_reference/with_monitor.rs"] pub mod with_monitor; test_stdout!(without_monitor_returns_true, "true\n");
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // compile-flags:--test -g #[cfg(target_os = "macos")] #[test] fn simple_test() { use std::{env, panic, fs}; // Find our dSYM and replace the DWARF binary with an empty file let mut dsym_path = env::current_exe().unwrap(); let executable_name = dsym_path.file_name().unwrap().to_str().unwrap().to_string(); assert!(dsym_path.pop()); // Pop executable dsym_path.push(format!("{}.dSYM/Contents/Resources/DWARF/{0}", executable_name)); { let file = fs::OpenOptions::new().read(false).write(true).truncate(true).create(false) .open(&dsym_path).unwrap(); } env::set_var("RUST_BACKTRACE", "1"); // We don't need to die of panic, just trigger a backtrace let _ = panic::catch_unwind(|| { assert!(false); }); }
// # The Rust Programing Language // // You made it! That was a sizable chapter: you learned about variables, scalar and compound data // types, functions, comments, if expressions, and loops! If you want to practice with the concepts // discussed in this chapter, try building programs to do the following: // // - Convert temperatures between Fahrenheit and Celsius // // [Source](https://doc.rust-lang.org/book/ch03-05-control-flow.html) // use std::io::{self, Write}; #[derive(Debug)] enum Temp { DegreesCelsius(f32), DegreesFarenheit(f32), } fn main() { println!("This program will convert between degrees celsius and degrees farenheit"); let input = prompt_user_for_input(); match convert(input) { Temp::DegreesCelsius(c) => println!("= {}℃", c), Temp::DegreesFarenheit(f) => println!("= {}℉", f), } } fn convert(input: Temp) -> Temp { match input { Temp::DegreesCelsius(x) => Temp::DegreesFarenheit((x * 9.0 / 5.0) + 32.0), Temp::DegreesFarenheit(x) => Temp::DegreesCelsius((x - 32.0) * 5.0 / 9.0), } } fn prompt_user_for_input() -> Temp { let is_celsius = loop { print!("Is your input in degrees or farenheit? [C/F]> "); let _ = io::stdout().flush(); let mut entry = String::new(); io::stdin() .read_line(&mut entry) .expect("Failed to read line"); match entry.trim() { "C" | "c" => { break true; } "F" | "f" => { break false; } _ => { continue; } } }; loop { print!("Value (in {}) > ", { if is_celsius { "degrees celsius" } else { "degerees farenheit" } }); let _ = io::stdout().flush(); let mut entry = String::new(); io::stdin() .read_line(&mut entry) .expect("Failed to read line"); return match entry.trim().parse() { Ok(num) => { if is_celsius { Temp::DegreesCelsius(num) } else { Temp::DegreesFarenheit(num) } } Err(_) => { println!("Please enter a valid number"); continue; } }; } }
use crate::utils::print_updates; use crate::*; use std::path::Path; fn get_file_list(opt: &Opt) -> Vec<String> { let mut files = Vec::<String>::new(); for item in opt.input.iter() { if opt.recursive && item.is_dir() { let mut tmp = match scope_dir(&item.to_path_buf()) { Ok(t) => t, Err(_) => { println!("Error: Cannot read item: {:?}", item); continue; } }; files.append(&mut tmp); } else if item.is_file() { files.push(item.to_str().unwrap().to_string()); } } files } fn scope_dir(dir: &Path) -> Result<Vec<String>, Error> { let path = Path::new(&dir); let mut files = Vec::<String>::new(); for entry in path.read_dir().unwrap() { if entry.as_ref().unwrap().file_type().unwrap().is_dir() { if entry.as_ref().unwrap().path() == *dir { continue; } let mut tmp = match scope_dir(&entry.as_ref().unwrap().path()) { Ok(t) => t, Err(_) => { println!("Error: Cannot read dir: {:?}", entry); continue; } }; files.append(&mut tmp); } else if entry.as_ref().unwrap().file_type().unwrap().is_file() { files.push(entry.unwrap().path().to_str().unwrap().to_string()); } } Ok(files) } /// Client function sends filename and file data for each filepath pub fn run(opt: Opt) -> Result<(), Error> { println!("Teleporter Client {}", VERSION); let files = get_file_list(&opt); if files.is_empty() { println!(" => No files to send. (Did you mean to add '-r'?)"); return Ok(()); } // For each filepath in the input vector... for (num, item) in files.iter().enumerate() { let filepath = item; let mut filename = filepath.clone().to_string(); // Validate file let file = match File::open(&filepath) { Ok(f) => f, Err(s) => { println!("Error opening file: {}", filepath); return Err(s); } }; let thread_file = filepath.clone().to_string(); let handle = match opt.overwrite { true => Some(thread::spawn(move || { utils::calc_file_hash(thread_file).unwrap() })), false => None, }; // Remove '/' root if exists if opt.recursive && filepath.starts_with('/') { filename.remove(0); } else if !opt.recursive { filename = Path::new(item) .file_name() .unwrap() .to_str() .unwrap() .to_string(); } let meta = file.metadata()?; let header = TeleportInit { protocol: PROTOCOL.to_string(), version: VERSION.to_string(), filenum: (num + 1) as u64, totalfiles: files.len() as u64, filesize: meta.len(), filename: filename.to_string(), chmod: meta.permissions().mode(), overwrite: opt.overwrite, }; // Connect to server let addr = format!("{}:{}", opt.dest, opt.port); let mut stream = match TcpStream::connect(match addr.parse::<SocketAddr>() { Ok(a) => a, Err(_) => { return Err(Error::new( ErrorKind::InvalidData, "Error with destination address", )) } }) { Ok(s) => s, Err(s) => { println!("Error connecting to: {}:{}", opt.dest, opt.port); return Err(s); } }; println!( "Sending file {}/{}: {:?}", header.filenum, header.totalfiles, header.filename ); // Send header first stream.write_all(&header.serialize())?; // Receive response from server let recv = match recv_ack(&stream) { Some(t) => t, None => { println!("Receive TeleportInitAck timed out"); return Ok(()); } }; // Validate response match &recv.ack { TeleportInitStatus::Overwrite => { println!("The server is overwriting the file: {}", &header.filename) } TeleportInitStatus::NoOverwrite => { println!( "The server refused to overwrite the file: {}", &header.filename ); continue; } TeleportInitStatus::NoPermission => { println!( "The server does not have permission to write to this file: {}", &header.filename ); continue; } TeleportInitStatus::NoSpace => { println!( "The server has no space available to write the file: {}", &header.filename ); continue; } TeleportInitStatus::WrongVersion => { println!( "Error: Version mismatch! Server: {} Us: {}", recv.version, VERSION ); break; } _ => (), }; let csum_recv = recv.delta.as_ref().map(|r| r.csum); let checksum = handle.map(|s| s.join().expect("calc_file_hash panicked")); if checksum != None && checksum == csum_recv { // File matches hash send_delta_complete(stream, file)?; } else { // Send file data send(stream, file, header, recv.delta)?; } println!(" done!"); } Ok(()) } fn recv_ack(mut stream: &TcpStream) -> Option<TeleportInitAck> { let mut buf: [u8; 4096 * 3] = [0; 4096 * 3]; // Receive ACK that the server is ready for data let len = match stream.read(&mut buf) { Ok(l) => l, Err(_) => return None, }; let fix = &buf[..len]; let mut resp = TeleportInitAck::new(TeleportInitStatus::WrongVersion); if let Err(e) = resp.deserialize(fix.to_vec()) { println!("{:?}", e); return None; }; Some(resp) } fn send_delta_complete(mut stream: TcpStream, file: File) -> Result<(), Error> { let meta = file.metadata()?; let chunk = TeleportData { length: 0, offset: meta.len() as u64, data: Vec::<u8>::new(), }; // Send the data chunk stream.write_all(&chunk.serialize())?; stream.flush()?; Ok(()) } /// Send function receives the ACK for data and sends the file data fn send( mut stream: TcpStream, mut file: File, header: TeleportInit, delta: Option<TeleportDelta>, ) -> Result<(), Error> { let mut buf = Vec::<u8>::new(); let mut hash_list = Vec::<Hash>::new(); let mut hasher = blake3::Hasher::new(); match delta { Some(d) => { buf.resize(d.delta_size as usize, 0); hash_list = d.delta_csum; } None => buf.resize(4096, 0), } // Send file data let mut sent = 0; loop { // Read a chunk of the file let len = match file.read(&mut buf) { Ok(l) => l, Err(s) => return Err(s), }; // If a length of 0 was read, we're done sending if len == 0 { break; } // Check if hash matches, if so: skip chunk let index = sent / buf.len(); if !hash_list.is_empty() && index < hash_list.len() { hasher.update(&buf); if hash_list[index] == hasher.finalize() { sent += len; continue; } hasher.reset(); } let data = &buf[..len]; let chunk = TeleportData { length: len as u32, offset: sent as u64, data: data.to_vec(), }; // Send the data chunk match stream.write_all(&chunk.serialize()) { Ok(_) => {} Err(s) => return Err(s), }; match stream.flush() { Ok(_) => {} Err(s) => return Err(s), }; sent += len; print_updates(sent as f64, &header); } send_delta_complete(stream, file)?; Ok(()) }
#[doc = "Writer for register C2IFCR"] pub type W = crate::W<u32, super::C2IFCR>; #[doc = "Register C2IFCR `reset()`'s with value 0"] impl crate::ResetValue for super::C2IFCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CTEIF2`"] pub struct CTEIF2_W<'a> { w: &'a mut W, } impl<'a> CTEIF2_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 = "Write proxy for field `CCTCIF2`"] pub struct CCTCIF2_W<'a> { w: &'a mut W, } impl<'a> CCTCIF2_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 = "Write proxy for field `CBRTIF2`"] pub struct CBRTIF2_W<'a> { w: &'a mut W, } impl<'a> CBRTIF2_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 = "Write proxy for field `CBTIF2`"] pub struct CBTIF2_W<'a> { w: &'a mut W, } impl<'a> CBTIF2_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 = "Write proxy for field `CLTCIF2`"] pub struct CLTCIF2_W<'a> { w: &'a mut W, } impl<'a> CLTCIF2_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 } } impl W { #[doc = "Bit 0 - Channel x clear transfer error interrupt flag Writing a 1 into this bit clears TEIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cteif2(&mut self) -> CTEIF2_W { CTEIF2_W { w: self } } #[doc = "Bit 1 - Clear Channel transfer complete interrupt flag for channel x Writing a 1 into this bit clears CTCIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cctcif2(&mut self) -> CCTCIF2_W { CCTCIF2_W { w: self } } #[doc = "Bit 2 - Channel x clear block repeat transfer complete interrupt flag Writing a 1 into this bit clears BRTIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cbrtif2(&mut self) -> CBRTIF2_W { CBRTIF2_W { w: self } } #[doc = "Bit 3 - Channel x Clear block transfer complete interrupt flag Writing a 1 into this bit clears BTIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cbtif2(&mut self) -> CBTIF2_W { CBTIF2_W { w: self } } #[doc = "Bit 4 - CLear buffer Transfer Complete Interrupt Flag for channel x Writing a 1 into this bit clears TCIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cltcif2(&mut self) -> CLTCIF2_W { CLTCIF2_W { w: self } } }
use crate::{app::AppContextPointer, gui::control_area::BOX_SPACING}; use gtk::{self, gdk::RGBA, prelude::*, Frame, ScrolledWindow}; use std::rc::Rc; pub fn make_active_readout_frame(ac: &AppContextPointer) -> ScrolledWindow { let f = Frame::new(None); f.set_hexpand(true); f.set_vexpand(true); // Layout vertically let v_box = gtk::Box::new(gtk::Orientation::Vertical, BOX_SPACING); v_box.set_baseline_position(gtk::BaselinePosition::Top); let sample_frame = gtk::Frame::new(Some("View")); let sample_box = gtk::Box::new(gtk::Orientation::Vertical, BOX_SPACING); sample_frame.set_child(Some(&sample_box)); // Active readout build_config_color!(sample_box, "Sampling marker", ac, active_readout_line_rgba); build_config_color!( sample_box, "Sample profile", ac, sample_parcel_profile_color ); build_config_color!( sample_box, "Sample mix down profile", ac, sample_mix_down_rgba ); build_config_color!(sample_box, "Fire Plume Profile", ac, fire_plume_line_color); // Layout boxes in the frame f.set_child(Some(&v_box)); v_box.append(&sample_frame); let sw = ScrolledWindow::new(); sw.set_child(Some(&f)); sw }
#[doc = "Reader of register OR"] pub type R = crate::R<u32, super::OR>; #[doc = "Writer for register OR"] pub type W = crate::W<u32, super::OR>; #[doc = "Register OR `reset()`'s with value 0"] impl crate::ResetValue for super::OR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `AFOP`"] pub type AFOP_R = crate::R<u16, u16>; #[doc = "Write proxy for field `AFOP`"] pub struct AFOP_W<'a> { w: &'a mut W, } impl<'a> AFOP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x07ff) | ((value as u32) & 0x07ff); self.w } } #[doc = "Reader of field `OR`"] pub type OR_R = crate::R<u32, u32>; #[doc = "Write proxy for field `OR`"] pub struct OR_W<'a> { w: &'a mut W, } impl<'a> OR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !(0x001f_ffff << 11)) | (((value as u32) & 0x001f_ffff) << 11); self.w } } impl R { #[doc = "Bits 0:10 - Selection of source for alternate function of output ports"] #[inline(always)] pub fn afop(&self) -> AFOP_R { AFOP_R::new((self.bits & 0x07ff) as u16) } #[doc = "Bits 11:31 - Option Register"] #[inline(always)] pub fn or(&self) -> OR_R { OR_R::new(((self.bits >> 11) & 0x001f_ffff) as u32) } } impl W { #[doc = "Bits 0:10 - Selection of source for alternate function of output ports"] #[inline(always)] pub fn afop(&mut self) -> AFOP_W { AFOP_W { w: self } } #[doc = "Bits 11:31 - Option Register"] #[inline(always)] pub fn or(&mut self) -> OR_W { OR_W { w: self } } }
extern crate chrono; extern crate serde; extern crate serde_json; extern crate sha2; extern crate rsa; use super::wt; pub mod block; pub mod chain; pub mod digest; pub mod miner; pub mod transaction; pub mod wallet; pub mod system; pub mod system_persistence;
use dotenv::dotenv; use ojichat::ojichat; use serenity::{ async_trait, client::bridge::gateway::ShardManager, framework::standard::{ help_commands, macros::{command, group, help, hook}, Args, CommandGroup, CommandResult, DispatchError, HelpOptions, StandardFramework, }, http::Http, model::{channel::Message, gateway::Ready, id::UserId}, prelude::*, }; use std::{ collections::{HashMap, HashSet}, env, sync::Arc, }; struct SharedManagerContainer; impl TypeMapKey for SharedManagerContainer { type Value = Arc<Mutex<ShardManager>>; } struct CommandCounter; impl TypeMapKey for CommandCounter { type Value = HashMap<String, u64>; } struct Handler; #[async_trait] impl EventHandler for Handler { async fn ready(&self, _ctx: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } } #[group] #[description = "おじさんが喋ります。"] #[commands(ojichat)] struct Ojichat; #[help] #[command_not_found_text = "Could not find: `{}`."] async fn my_help( context: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { let _ = help_commands::with_embeds(context, msg, args, help_options, groups, owners).await; Ok(()) } #[hook] async fn unknown_command(_ctx: &Context, _msg: &Message, unknown_command_name: &str) { println!("Could not find command named '{}'", unknown_command_name); } #[hook] async fn dispatch_error(ctx: &Context, msg: &Message, error: DispatchError) { if let DispatchError::Ratelimited(duration) = error { let _ = msg .channel_id .say( &ctx.http, &format!("Type this again in {} seconds.", duration.as_secs()), ) .await; } } use serenity::{futures::future::BoxFuture, FutureExt}; fn _dispatch_error_no_macro<'fut>( ctx: &'fut mut Context, msg: &'fut Message, error: DispatchError, ) -> BoxFuture<'fut, ()> { async move { if let DispatchError::Ratelimited(duration) = error { let _ = msg .channel_id .say( &ctx.http, &format!("Type this again in {} seconds.", duration.as_secs()), ) .await; }; } .boxed() } #[tokio::main] async fn main() { dotenv().ok(); let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment or .env file"); let http = Http::new_with_token(&token); let (owners, bot_id) = match http.get_current_application_info().await { Ok(info) => { let mut owners = HashSet::new(); if let Some(team) = info.team { owners.insert(team.owner_user_id); } else { owners.insert(info.owner.id); } match http.get_current_user().await { Ok(bot_id) => (owners, bot_id.id), Err(why) => panic!("Could not access the bot id: {:?}", why), } } Err(why) => panic!("Could not access application info: {:?}", why), }; let framework = StandardFramework::new() .configure(|c| { c.with_whitespace(true) .on_mention(Some(bot_id)) .prefix("~") .owners(owners) }) .unrecognised_command(unknown_command) .on_dispatch_error(dispatch_error) .help(&MY_HELP) .group(&OJICHAT_GROUP); let mut client = Client::builder(token) .event_handler(Handler) .framework(framework) .await .expect("Error creating client"); { let mut data = client.data.write().await; data.insert::<CommandCounter>(HashMap::default()); data.insert::<SharedManagerContainer>(Arc::clone(&client.shard_manager)); } if let Err(why) = client.start().await { eprintln!("An Error occurred while running the client: {:?}", why); } } #[command] async fn ojichat(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let emoji_num = args.single::<usize>().ok(); let punctuation_level = args.single::<usize>().ok(); let target = args.single::<String>().ok(); let res = ojichat::get_message(target, emoji_num, punctuation_level); msg.channel_id.say(&ctx.http, &res.to_string()).await?; Ok(()) }
#[doc = "Reader of register PPUART"] pub type R = crate::R<u32, super::PPUART>; #[doc = "Reader of field `P0`"] pub type P0_R = crate::R<bool, bool>; #[doc = "Reader of field `P1`"] pub type P1_R = crate::R<bool, bool>; #[doc = "Reader of field `P2`"] pub type P2_R = crate::R<bool, bool>; #[doc = "Reader of field `P3`"] pub type P3_R = crate::R<bool, bool>; #[doc = "Reader of field `P4`"] pub type P4_R = crate::R<bool, bool>; #[doc = "Reader of field `P5`"] pub type P5_R = crate::R<bool, bool>; #[doc = "Reader of field `P6`"] pub type P6_R = crate::R<bool, bool>; #[doc = "Reader of field `P7`"] pub type P7_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - UART Module 0 Present"] #[inline(always)] pub fn p0(&self) -> P0_R { P0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - UART Module 1 Present"] #[inline(always)] pub fn p1(&self) -> P1_R { P1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - UART Module 2 Present"] #[inline(always)] pub fn p2(&self) -> P2_R { P2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - UART Module 3 Present"] #[inline(always)] pub fn p3(&self) -> P3_R { P3_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - UART Module 4 Present"] #[inline(always)] pub fn p4(&self) -> P4_R { P4_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - UART Module 5 Present"] #[inline(always)] pub fn p5(&self) -> P5_R { P5_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - UART Module 6 Present"] #[inline(always)] pub fn p6(&self) -> P6_R { P6_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - UART Module 7 Present"] #[inline(always)] pub fn p7(&self) -> P7_R { P7_R::new(((self.bits >> 7) & 0x01) != 0) } }
use std::collections::HashMap; use crate::ast::*; use crate::object::*; pub trait Evaluation { fn evaluate(self, env: &mut Environment) -> Result<Object, String>; } impl Evaluation for Program { fn evaluate(self, env: &mut Environment) -> Result<Object, String> { match self { Program { statements, errors: _, } => eval_program(statements, env), } } } impl Evaluation for Statement { fn evaluate(self, env: &mut Environment) -> Result<Object, String> { match self { Statement::Expression { token: _, expression, } => eval(expression, env), Statement::Block { token: _, statements, } => eval_block_statement(statements, env), Statement::Return { token: _, return_value, } => { let value = eval(return_value, env)?; Ok(Object::ReturnValue { value: Box::new(value), }) } Statement::Let { token: _, identifier, value, } => { let value = eval(value, env)?; env.set(identifier.to_string(), value); Ok(Object::Null) } } } } impl Evaluation for Expression { fn evaluate(self, env: &mut Environment) -> Result<Object, String> { match self { Expression::If { .. } => eval_if_expression(self, env), Expression::IntegerLiteral { token: _, value } => Ok(Object::Integer { value }), Expression::Boolean { token: _, value } => Ok(Object::Boolean { value }), Expression::Prefix { operator, right } => { let right = eval(*right, env)?; eval_prefix_expression(&operator.to_string(), right) } Expression::Infix { operator, left, right, } => { let right = eval(*right, env)?; let left = eval(*left, env)?; let operator = operator.to_string(); eval_infix_expression(operator, left, right) } Expression::StringLiteral { token } => Ok(Object::String { value: token.to_string(), }), Expression::Identifier(token) => eval_identifier(&token.to_string(), env), Expression::FunctionLiteral { token: _, parameters, body, } => Ok(Object::Function { parameters, body: *body, env: env.clone(), }), Expression::Call { token: _, function, arguments, } => { let function = eval(*function, env)?; let args = eval_expressions(arguments, env)?; apply_function(function, args) } } } } #[derive(Debug, Eq, PartialEq, Clone)] pub struct Environment { store: HashMap<String, Object>, outer: Option<Box<Environment>>, } impl Environment { pub fn get(&self, identifier: &str) -> Option<&Object> { match self.store.contains_key(identifier) { true => self.store.get(identifier), false => match &self.outer { Some(out) => (*out).get(identifier), _ => None, }, } } pub fn set(&mut self, identifier: String, value: Object) { self.store.insert(identifier, value); } pub fn new() -> Environment { Environment { store: HashMap::new(), outer: None, } } pub fn new_enclosed(outer: &Environment) -> Environment { Environment { store: HashMap::new(), outer: Some(Box::new(outer.clone())), } } } pub fn eval<T: Evaluation>(node: T, env: &mut Environment) -> Result<Object, String> { node.evaluate(env) } fn apply_function(function: Object, args: Vec<Object>) -> Result<Object, String> { match function { Object::Function { parameters, body, env, } => { let mut extended_env = extend_function_env(&env, parameters, args); let evaluated = eval(body, &mut extended_env)?; unwrap_return_value(evaluated) } _ => Err(format!("not a function: {}", function.get_type())), } } fn extend_function_env( current_env: &Environment, parameters: Vec<Expression>, args: Vec<Object>, ) -> Environment { let mut extend_env = Environment::new_enclosed(current_env); assert!( args.len() == parameters.len(), "argument count does not match parameter count. {} parameters, {} arguments", parameters.len(), args.len() ); for (identifier, arg) in parameters.into_iter().zip(args.into_iter()) { extend_env.set(identifier.to_string(), arg); } extend_env } fn unwrap_return_value(obj: Object) -> Result<Object, String> { match obj { Object::ReturnValue { value } => Ok(*value), _ => Ok(obj), } } fn eval_expressions(exprs: Vec<Expression>, env: &mut Environment) -> Result<Vec<Object>, String> { let mut result = vec![]; for expr in exprs { let evaluated = eval(expr, env)?; result.push(evaluated); } Ok(result) } fn eval_identifier(identifier: &str, env: &mut Environment) -> Result<Object, String> { let value = env.get(identifier); match value { Some(obj) => Ok(obj.clone()), _ => Err(format!("identifier not found: {}", identifier)), } } fn eval_program(statements: Vec<Statement>, env: &mut Environment) -> Result<Object, String> { let mut result = Object::Null; for statement in statements { result = eval(statement, env)?; if let Object::ReturnValue { value } = result { return Ok(*value); } } Ok(result) } fn eval_block_statement( statements: Vec<Statement>, env: &mut Environment, ) -> Result<Object, String> { let mut result = Object::Null; for statement in statements { result = eval(statement, env)?; if let Object::ReturnValue { .. } = result { return Ok(result); } } Ok(result) } fn eval_prefix_expression(operator: &str, right: Object) -> Result<Object, String> { match operator { "!" => eval_bang_operator_expression(right), "-" => eval_minus_prefix_operator_expression(right), _ => Err(format!( "unknown operator: {}{}", operator, right.get_type() )), } } fn eval_bang_operator_expression(right: Object) -> Result<Object, String> { match right { Object::Boolean { value } => Ok(Object::Boolean { value: !value }), Object::Integer { value } => { match value { 0 => Ok(Object::Boolean { value: true }), // !0 == true _ => Ok(Object::Boolean { value: false }), // !n == false, n > 0 } } Object::Null => Ok(Object::Boolean { value: true }), _ => Err(format!("unknown operator: !{}", right.get_type())), } } fn eval_minus_prefix_operator_expression(right: Object) -> Result<Object, String> { match right { Object::Integer { value } => Ok(Object::Integer { value: -value }), _ => Err(format!("unknown operator: -{}", right.get_type())), } } fn eval_infix_expression(operator: String, left: Object, right: Object) -> Result<Object, String> { match (&left, &right) { (Object::Integer { value: l }, Object::Integer { value: r }) => { eval_integer_infix_expression(operator, *l, *r) } (Object::Boolean { value: l }, Object::Boolean { value: r }) => { eval_boolean_infix_expression(operator, *l, *r) } (Object::String { value: l }, Object::String { value: r }) => { eval_string_infix_expression(operator, l, r) } _ => match left.get_type() != right.get_type() { true => Err(format!( "type mismatch: {} {} {}", left.get_type(), operator, right.get_type() )), false => Err(format!( "unknown operator: {} {} {}", left.get_type(), operator, right.get_type() )), }, } } fn eval_string_infix_expression( operator: String, left: &str, right: &str, ) -> Result<Object, String> { match operator.as_str() { "+" => { let mut value= String::new(); value.push_str(left); value.push_str(right); Ok(Object::String{value}) }, "!=" => { Ok(Object::Boolean{value: left != right}) }, "==" => { Ok(Object::Boolean{value: left == right}) }, _ => Err(format!("unknown operator: {} {} {}", "STRING", operator, "STRING")), } } fn eval_integer_infix_expression( operator: String, left: i64, right: i64, ) -> Result<Object, String> { match operator.as_str() { "+" => Ok(Object::Integer { value: left + right, }), "-" => Ok(Object::Integer { value: left - right, }), "*" => Ok(Object::Integer { value: left * right, }), "/" => Ok(Object::Integer { value: left / right, }), ">" => Ok(Object::Boolean { value: left > right, }), "<" => Ok(Object::Boolean { value: left < right, }), "==" => Ok(Object::Boolean { value: left == right, }), "!=" => Ok(Object::Boolean { value: left != right, }), _ => Err(format!("unknown operator: {} {} {}", left, operator, right)), } } fn eval_boolean_infix_expression( operator: String, left: bool, right: bool, ) -> Result<Object, String> { match operator.as_str() { "==" => Ok(Object::Boolean { value: left == right, }), "!=" => Ok(Object::Boolean { value: left != right, }), _ => Err(format!( "unknown operator: {} {} {}", "BOOLEAN", operator, "BOOLEAN" )), } } fn eval_if_expression(expression: Expression, env: &mut Environment) -> Result<Object, String> { match expression { Expression::If { token: _, condition, consequence, alternative, } => { let condition = eval(*condition, env)?; if is_truthy(condition) { return eval(*consequence, env); } if let Some(alt) = alternative { return eval(*alt, env); } Ok(Object::Null) } _ => return Err(format!("expected If Expression, got {:?}", expression)), } } fn is_truthy(obj: Object) -> bool { match obj { Object::Null => false, Object::Boolean { value } => value, _ => true, } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use common_expression::DataSchema; use common_sql::plans::UseDatabasePlan; use crate::interpreters::Interpreter; use crate::pipelines::PipelineBuildResult; use crate::sessions::QueryAffect; use crate::sessions::QueryContext; pub struct UseDatabaseInterpreter { ctx: Arc<QueryContext>, plan: UseDatabasePlan, } impl UseDatabaseInterpreter { pub fn try_create(ctx: Arc<QueryContext>, plan: UseDatabasePlan) -> Result<Self> { Ok(UseDatabaseInterpreter { ctx, plan }) } } #[async_trait::async_trait] impl Interpreter for UseDatabaseInterpreter { fn name(&self) -> &str { "UseDatabaseInterpreter" } async fn execute2(&self) -> Result<PipelineBuildResult> { if self.plan.database.trim().is_empty() { return Err(ErrorCode::UnknownDatabase("No database selected")); } self.ctx .set_current_database(self.plan.database.clone()) .await?; self.ctx.set_affect(QueryAffect::UseDB { name: self.plan.database.clone(), }); let _schema = Arc::new(DataSchema::empty()); Ok(PipelineBuildResult::create()) } }
#[macro_use] extern crate nom; extern crate num; mod parser; use nom::IResult; use num::{Complex, Zero}; use std::collections::HashSet; use std::io::{self, Read}; use parser::road; #[derive(Copy, Clone, Debug)] enum Direction { Left, Right, } #[derive(Copy, Clone, Debug)] pub struct Walk { direction: Direction, steps: i32, } fn rotate(number: Complex<i32>, direction: Direction) -> Complex<i32> { let direction = match direction { Direction::Left => -Complex::i(), Direction::Right => Complex::i(), }; number * direction } fn taxicab_distance(Complex { re, im }: Complex<i32>) -> i32 { re.abs() + im.abs() } fn calculate_position(road: &[Walk]) -> Complex<i32> { road.iter() .fold((Complex::i(), Complex::zero()), |(direction, position), walk| { let new_direction = rotate(direction, walk.direction); (new_direction, position + new_direction * Complex::from(walk.steps)) }) .1 } fn first_duplicate(road: &[Walk]) -> Option<Complex<i32>> { let mut direction = Complex::i(); let mut position = Complex::zero(); let mut reached = HashSet::new(); reached.insert((0, 0)); for walk in road { direction = rotate(direction, walk.direction); for _ in 0..walk.steps { position = position + direction; if !reached.insert((position.re, position.im)) { return Some(position); } } } None } fn main() { let input = io::stdin(); let mut out = Vec::new(); input.lock().read_to_end(&mut out).unwrap(); match road(&out) { IResult::Done(_, road) => { println!("Distance: {}", taxicab_distance(calculate_position(&road))); let duplicate = first_duplicate(&road).map(taxicab_distance); match duplicate { Some(position) => println!("First duplicate location: {}", position), None => println!("No duplicates found"), } } IResult::Error(_) => panic!("Syntax error"), IResult::Incomplete(_) => panic!("Incomplete input"), } } #[test] fn destination() { let tests: [(&[u8], i32); 3] = [(b"R2, L3", 5), (b"R2, R2, R2", 2), (b"R5, L5, R5, R3", 12)]; for &(route, answer) in &tests { assert_eq!(taxicab_distance(calculate_position(&road(route).unwrap().1)), answer); } } #[test] fn duplicate() { assert_eq!(first_duplicate(&[]), None); assert_eq!(first_duplicate(&road(b"R8, R4, R4, R8").unwrap().1).map(taxicab_distance), Some(4)); }
//! GraphQL support for [`chrono-tz`] crate types. //! //! # Supported types //! //! | Rust type | Format | GraphQL scalar | //! |-----------|--------------------|----------------| //! | [`Tz`] | [IANA database][1] | `TimeZone` | //! //! [`chrono-tz`]: chrono_tz //! [`Tz`]: chrono_tz::Tz //! [1]: http://www.iana.org/time-zones use crate::{graphql_scalar, InputValue, ScalarValue, Value}; /// Timezone based on [`IANA` database][1]. /// /// See ["List of tz database time zones"][2] `TZ database name` column for /// available names. /// /// See also [`chrono_tz::Tz`][3] for detals. /// /// [1]: https://www.iana.org/time-zones /// [2]: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones /// [3]: https://docs.rs/chrono-tz/latest/chrono_tz/enum.Tz.html #[graphql_scalar(with = tz, parse_token(String))] pub type TimeZone = chrono_tz::Tz; mod tz { use super::*; pub(super) fn to_output<S: ScalarValue>(v: &TimeZone) -> Value<S> { Value::scalar(v.name().to_owned()) } pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<TimeZone, String> { v.as_string_value() .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { s.parse::<TimeZone>() .map_err(|e| format!("Failed to parse `TimeZone`: {e}")) }) } } #[cfg(test)] mod test { use super::TimeZone; mod from_input_value { use super::TimeZone; use crate::{graphql_input_value, FromInputValue, InputValue, IntoFieldError}; fn tz_input_test(raw: &'static str, expected: Result<TimeZone, &str>) { let input: InputValue = graphql_input_value!((raw)); let parsed = FromInputValue::from_input_value(&input); assert_eq!( parsed.as_ref(), expected.map_err(IntoFieldError::into_field_error).as_ref(), ); } #[test] fn europe_zone() { tz_input_test("Europe/London", Ok(chrono_tz::Europe::London)); } #[test] fn etc_minus() { tz_input_test("Etc/GMT-3", Ok(chrono_tz::Etc::GMTMinus3)); } mod invalid { use super::tz_input_test; #[test] fn forward_slash() { tz_input_test( "Abc/Xyz", Err("Failed to parse `TimeZone`: received invalid timezone"), ); } #[test] fn number() { tz_input_test( "8086", Err("Failed to parse `TimeZone`: received invalid timezone"), ); } #[test] fn no_forward_slash() { tz_input_test( "AbcXyz", Err("Failed to parse `TimeZone`: received invalid timezone"), ); } } } }
#[doc = "Reader of register TAMPCR"] pub type R = crate::R<u32, super::TAMPCR>; #[doc = "Writer for register TAMPCR"] pub type W = crate::W<u32, super::TAMPCR>; #[doc = "Register TAMPCR `reset()`'s with value 0"] impl crate::ResetValue for super::TAMPCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Tamper 2 mask flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMP2MF_A { #[doc = "0: Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"] NOTMASKED = 0, #[doc = "1: Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased."] MASKED = 1, } impl From<TAMP2MF_A> for bool { #[inline(always)] fn from(variant: TAMP2MF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMP2MF`"] pub type TAMP2MF_R = crate::R<bool, TAMP2MF_A>; impl TAMP2MF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMP2MF_A { match self.bits { false => TAMP2MF_A::NOTMASKED, true => TAMP2MF_A::MASKED, } } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == TAMP2MF_A::NOTMASKED } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == TAMP2MF_A::MASKED } } #[doc = "Write proxy for field `TAMP2MF`"] pub struct TAMP2MF_W<'a> { w: &'a mut W, } impl<'a> TAMP2MF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP2MF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TAMP2MF_A::NOTMASKED) } #[doc = "Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased."] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TAMP2MF_A::MASKED) } #[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 = "Tamper 2 no erase\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMP2NOERASE_A { #[doc = "0: Tamper x event erases the backup registers"] ERASE = 0, #[doc = "1: Tamper x event does not erase the backup registers"] NOERASE = 1, } impl From<TAMP2NOERASE_A> for bool { #[inline(always)] fn from(variant: TAMP2NOERASE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMP2NOERASE`"] pub type TAMP2NOERASE_R = crate::R<bool, TAMP2NOERASE_A>; impl TAMP2NOERASE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMP2NOERASE_A { match self.bits { false => TAMP2NOERASE_A::ERASE, true => TAMP2NOERASE_A::NOERASE, } } #[doc = "Checks if the value of the field is `ERASE`"] #[inline(always)] pub fn is_erase(&self) -> bool { *self == TAMP2NOERASE_A::ERASE } #[doc = "Checks if the value of the field is `NOERASE`"] #[inline(always)] pub fn is_no_erase(&self) -> bool { *self == TAMP2NOERASE_A::NOERASE } } #[doc = "Write proxy for field `TAMP2NOERASE`"] pub struct TAMP2NOERASE_W<'a> { w: &'a mut W, } impl<'a> TAMP2NOERASE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP2NOERASE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x event erases the backup registers"] #[inline(always)] pub fn erase(self) -> &'a mut W { self.variant(TAMP2NOERASE_A::ERASE) } #[doc = "Tamper x event does not erase the backup registers"] #[inline(always)] pub fn no_erase(self) -> &'a mut W { self.variant(TAMP2NOERASE_A::NOERASE) } #[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 = "Tamper 2 interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMP2IE_A { #[doc = "0: Tamper x interrupt is disabled if TAMPIE = 0"] DISABLED = 0, #[doc = "1: Tamper x interrupt enabled"] ENABLED = 1, } impl From<TAMP2IE_A> for bool { #[inline(always)] fn from(variant: TAMP2IE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMP2IE`"] pub type TAMP2IE_R = crate::R<bool, TAMP2IE_A>; impl TAMP2IE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMP2IE_A { match self.bits { false => TAMP2IE_A::DISABLED, true => TAMP2IE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TAMP2IE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TAMP2IE_A::ENABLED } } #[doc = "Write proxy for field `TAMP2IE`"] pub struct TAMP2IE_W<'a> { w: &'a mut W, } impl<'a> TAMP2IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP2IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x interrupt is disabled if TAMPIE = 0"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMP2IE_A::DISABLED) } #[doc = "Tamper x interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMP2IE_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Tamper 1 mask flag"] pub type TAMP1MF_A = TAMP2MF_A; #[doc = "Reader of field `TAMP1MF`"] pub type TAMP1MF_R = crate::R<bool, TAMP2MF_A>; #[doc = "Write proxy for field `TAMP1MF`"] pub struct TAMP1MF_W<'a> { w: &'a mut W, } impl<'a> TAMP1MF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP1MF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TAMP2MF_A::NOTMASKED) } #[doc = "Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased."] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TAMP2MF_A::MASKED) } #[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 = "Tamper 1 no erase"] pub type TAMP1NOERASE_A = TAMP2NOERASE_A; #[doc = "Reader of field `TAMP1NOERASE`"] pub type TAMP1NOERASE_R = crate::R<bool, TAMP2NOERASE_A>; #[doc = "Write proxy for field `TAMP1NOERASE`"] pub struct TAMP1NOERASE_W<'a> { w: &'a mut W, } impl<'a> TAMP1NOERASE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP1NOERASE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x event erases the backup registers"] #[inline(always)] pub fn erase(self) -> &'a mut W { self.variant(TAMP2NOERASE_A::ERASE) } #[doc = "Tamper x event does not erase the backup registers"] #[inline(always)] pub fn no_erase(self) -> &'a mut W { self.variant(TAMP2NOERASE_A::NOERASE) } #[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 = "Tamper 1 interrupt enable"] pub type TAMP1IE_A = TAMP2IE_A; #[doc = "Reader of field `TAMP1IE`"] pub type TAMP1IE_R = crate::R<bool, TAMP2IE_A>; #[doc = "Write proxy for field `TAMP1IE`"] pub struct TAMP1IE_W<'a> { w: &'a mut W, } impl<'a> TAMP1IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP1IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x interrupt is disabled if TAMPIE = 0"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMP2IE_A::DISABLED) } #[doc = "Tamper x interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMP2IE_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "RTC_TAMPx pull-up disable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMPPUDIS_A { #[doc = "0: Precharge RTC_TAMPx pins before sampling (enable internal pull-up)"] ENABLED = 0, #[doc = "1: Disable precharge of RTC_TAMPx pins"] DISABLED = 1, } impl From<TAMPPUDIS_A> for bool { #[inline(always)] fn from(variant: TAMPPUDIS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMPPUDIS`"] pub type TAMPPUDIS_R = crate::R<bool, TAMPPUDIS_A>; impl TAMPPUDIS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMPPUDIS_A { match self.bits { false => TAMPPUDIS_A::ENABLED, true => TAMPPUDIS_A::DISABLED, } } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TAMPPUDIS_A::ENABLED } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TAMPPUDIS_A::DISABLED } } #[doc = "Write proxy for field `TAMPPUDIS`"] pub struct TAMPPUDIS_W<'a> { w: &'a mut W, } impl<'a> TAMPPUDIS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMPPUDIS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Precharge RTC_TAMPx pins before sampling (enable internal pull-up)"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMPPUDIS_A::ENABLED) } #[doc = "Disable precharge of RTC_TAMPx pins"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMPPUDIS_A::DISABLED) } #[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 = "RTC_TAMPx precharge duration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum TAMPPRCH_A { #[doc = "0: 1 RTCCLK cycle"] CYCLES1 = 0, #[doc = "1: 2 RTCCLK cycles"] CYCLES2 = 1, #[doc = "2: 4 RTCCLK cycles"] CYCLES4 = 2, #[doc = "3: 8 RTCCLK cycles"] CYCLES8 = 3, } impl From<TAMPPRCH_A> for u8 { #[inline(always)] fn from(variant: TAMPPRCH_A) -> Self { variant as _ } } #[doc = "Reader of field `TAMPPRCH`"] pub type TAMPPRCH_R = crate::R<u8, TAMPPRCH_A>; impl TAMPPRCH_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMPPRCH_A { match self.bits { 0 => TAMPPRCH_A::CYCLES1, 1 => TAMPPRCH_A::CYCLES2, 2 => TAMPPRCH_A::CYCLES4, 3 => TAMPPRCH_A::CYCLES8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `CYCLES1`"] #[inline(always)] pub fn is_cycles1(&self) -> bool { *self == TAMPPRCH_A::CYCLES1 } #[doc = "Checks if the value of the field is `CYCLES2`"] #[inline(always)] pub fn is_cycles2(&self) -> bool { *self == TAMPPRCH_A::CYCLES2 } #[doc = "Checks if the value of the field is `CYCLES4`"] #[inline(always)] pub fn is_cycles4(&self) -> bool { *self == TAMPPRCH_A::CYCLES4 } #[doc = "Checks if the value of the field is `CYCLES8`"] #[inline(always)] pub fn is_cycles8(&self) -> bool { *self == TAMPPRCH_A::CYCLES8 } } #[doc = "Write proxy for field `TAMPPRCH`"] pub struct TAMPPRCH_W<'a> { w: &'a mut W, } impl<'a> TAMPPRCH_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMPPRCH_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "1 RTCCLK cycle"] #[inline(always)] pub fn cycles1(self) -> &'a mut W { self.variant(TAMPPRCH_A::CYCLES1) } #[doc = "2 RTCCLK cycles"] #[inline(always)] pub fn cycles2(self) -> &'a mut W { self.variant(TAMPPRCH_A::CYCLES2) } #[doc = "4 RTCCLK cycles"] #[inline(always)] pub fn cycles4(self) -> &'a mut W { self.variant(TAMPPRCH_A::CYCLES4) } #[doc = "8 RTCCLK cycles"] #[inline(always)] pub fn cycles8(self) -> &'a mut W { self.variant(TAMPPRCH_A::CYCLES8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 13)) | (((value as u32) & 0x03) << 13); self.w } } #[doc = "RTC_TAMPx filter count\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum TAMPFLT_A { #[doc = "0: Tamper event is activated on edge of RTC_TAMPx input transitions to the active level (no internal pull-up on RTC_TAMPx input)"] IMMEDIATE = 0, #[doc = "1: Tamper event is activated after 2 consecutive samples at the active level"] SAMPLES2 = 1, #[doc = "2: Tamper event is activated after 4 consecutive samples at the active level"] SAMPLES4 = 2, #[doc = "3: Tamper event is activated after 8 consecutive samples at the active level"] SAMPLES8 = 3, } impl From<TAMPFLT_A> for u8 { #[inline(always)] fn from(variant: TAMPFLT_A) -> Self { variant as _ } } #[doc = "Reader of field `TAMPFLT`"] pub type TAMPFLT_R = crate::R<u8, TAMPFLT_A>; impl TAMPFLT_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMPFLT_A { match self.bits { 0 => TAMPFLT_A::IMMEDIATE, 1 => TAMPFLT_A::SAMPLES2, 2 => TAMPFLT_A::SAMPLES4, 3 => TAMPFLT_A::SAMPLES8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `IMMEDIATE`"] #[inline(always)] pub fn is_immediate(&self) -> bool { *self == TAMPFLT_A::IMMEDIATE } #[doc = "Checks if the value of the field is `SAMPLES2`"] #[inline(always)] pub fn is_samples2(&self) -> bool { *self == TAMPFLT_A::SAMPLES2 } #[doc = "Checks if the value of the field is `SAMPLES4`"] #[inline(always)] pub fn is_samples4(&self) -> bool { *self == TAMPFLT_A::SAMPLES4 } #[doc = "Checks if the value of the field is `SAMPLES8`"] #[inline(always)] pub fn is_samples8(&self) -> bool { *self == TAMPFLT_A::SAMPLES8 } } #[doc = "Write proxy for field `TAMPFLT`"] pub struct TAMPFLT_W<'a> { w: &'a mut W, } impl<'a> TAMPFLT_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMPFLT_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Tamper event is activated on edge of RTC_TAMPx input transitions to the active level (no internal pull-up on RTC_TAMPx input)"] #[inline(always)] pub fn immediate(self) -> &'a mut W { self.variant(TAMPFLT_A::IMMEDIATE) } #[doc = "Tamper event is activated after 2 consecutive samples at the active level"] #[inline(always)] pub fn samples2(self) -> &'a mut W { self.variant(TAMPFLT_A::SAMPLES2) } #[doc = "Tamper event is activated after 4 consecutive samples at the active level"] #[inline(always)] pub fn samples4(self) -> &'a mut W { self.variant(TAMPFLT_A::SAMPLES4) } #[doc = "Tamper event is activated after 8 consecutive samples at the active level"] #[inline(always)] pub fn samples8(self) -> &'a mut W { self.variant(TAMPFLT_A::SAMPLES8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 11)) | (((value as u32) & 0x03) << 11); self.w } } #[doc = "Tamper sampling frequency\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum TAMPFREQ_A { #[doc = "0: RTCCLK / 32768 (1 Hz when RTCCLK = 32768 Hz)"] DIV32768 = 0, #[doc = "1: RTCCLK / 16384 (2 Hz when RTCCLK = 32768 Hz)"] DIV16384 = 1, #[doc = "2: RTCCLK / 8192 (4 Hz when RTCCLK = 32768 Hz)"] DIV8192 = 2, #[doc = "3: RTCCLK / 4096 (8 Hz when RTCCLK = 32768 Hz)"] DIV4096 = 3, #[doc = "4: RTCCLK / 2048 (16 Hz when RTCCLK = 32768 Hz)"] DIV2048 = 4, #[doc = "5: RTCCLK / 1024 (32 Hz when RTCCLK = 32768 Hz)"] DIV1024 = 5, #[doc = "6: RTCCLK / 512 (64 Hz when RTCCLK = 32768 Hz)"] DIV512 = 6, #[doc = "7: RTCCLK / 256 (128 Hz when RTCCLK = 32768 Hz)"] DIV256 = 7, } impl From<TAMPFREQ_A> for u8 { #[inline(always)] fn from(variant: TAMPFREQ_A) -> Self { variant as _ } } #[doc = "Reader of field `TAMPFREQ`"] pub type TAMPFREQ_R = crate::R<u8, TAMPFREQ_A>; impl TAMPFREQ_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMPFREQ_A { match self.bits { 0 => TAMPFREQ_A::DIV32768, 1 => TAMPFREQ_A::DIV16384, 2 => TAMPFREQ_A::DIV8192, 3 => TAMPFREQ_A::DIV4096, 4 => TAMPFREQ_A::DIV2048, 5 => TAMPFREQ_A::DIV1024, 6 => TAMPFREQ_A::DIV512, 7 => TAMPFREQ_A::DIV256, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV32768`"] #[inline(always)] pub fn is_div32768(&self) -> bool { *self == TAMPFREQ_A::DIV32768 } #[doc = "Checks if the value of the field is `DIV16384`"] #[inline(always)] pub fn is_div16384(&self) -> bool { *self == TAMPFREQ_A::DIV16384 } #[doc = "Checks if the value of the field is `DIV8192`"] #[inline(always)] pub fn is_div8192(&self) -> bool { *self == TAMPFREQ_A::DIV8192 } #[doc = "Checks if the value of the field is `DIV4096`"] #[inline(always)] pub fn is_div4096(&self) -> bool { *self == TAMPFREQ_A::DIV4096 } #[doc = "Checks if the value of the field is `DIV2048`"] #[inline(always)] pub fn is_div2048(&self) -> bool { *self == TAMPFREQ_A::DIV2048 } #[doc = "Checks if the value of the field is `DIV1024`"] #[inline(always)] pub fn is_div1024(&self) -> bool { *self == TAMPFREQ_A::DIV1024 } #[doc = "Checks if the value of the field is `DIV512`"] #[inline(always)] pub fn is_div512(&self) -> bool { *self == TAMPFREQ_A::DIV512 } #[doc = "Checks if the value of the field is `DIV256`"] #[inline(always)] pub fn is_div256(&self) -> bool { *self == TAMPFREQ_A::DIV256 } } #[doc = "Write proxy for field `TAMPFREQ`"] pub struct TAMPFREQ_W<'a> { w: &'a mut W, } impl<'a> TAMPFREQ_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMPFREQ_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "RTCCLK / 32768 (1 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div32768(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV32768) } #[doc = "RTCCLK / 16384 (2 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div16384(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV16384) } #[doc = "RTCCLK / 8192 (4 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div8192(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV8192) } #[doc = "RTCCLK / 4096 (8 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div4096(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV4096) } #[doc = "RTCCLK / 2048 (16 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div2048(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV2048) } #[doc = "RTCCLK / 1024 (32 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div1024(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV1024) } #[doc = "RTCCLK / 512 (64 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div512(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV512) } #[doc = "RTCCLK / 256 (128 Hz when RTCCLK = 32768 Hz)"] #[inline(always)] pub fn div256(self) -> &'a mut W { self.variant(TAMPFREQ_A::DIV256) } #[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 << 8)) | (((value as u32) & 0x07) << 8); self.w } } #[doc = "Activate timestamp on tamper detection event\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMPTS_A { #[doc = "0: Tamper detection event does not cause a timestamp to be saved"] NOSAVE = 0, #[doc = "1: Save timestamp on tamper detection event"] SAVE = 1, } impl From<TAMPTS_A> for bool { #[inline(always)] fn from(variant: TAMPTS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMPTS`"] pub type TAMPTS_R = crate::R<bool, TAMPTS_A>; impl TAMPTS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMPTS_A { match self.bits { false => TAMPTS_A::NOSAVE, true => TAMPTS_A::SAVE, } } #[doc = "Checks if the value of the field is `NOSAVE`"] #[inline(always)] pub fn is_no_save(&self) -> bool { *self == TAMPTS_A::NOSAVE } #[doc = "Checks if the value of the field is `SAVE`"] #[inline(always)] pub fn is_save(&self) -> bool { *self == TAMPTS_A::SAVE } } #[doc = "Write proxy for field `TAMPTS`"] pub struct TAMPTS_W<'a> { w: &'a mut W, } impl<'a> TAMPTS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMPTS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper detection event does not cause a timestamp to be saved"] #[inline(always)] pub fn no_save(self) -> &'a mut W { self.variant(TAMPTS_A::NOSAVE) } #[doc = "Save timestamp on tamper detection event"] #[inline(always)] pub fn save(self) -> &'a mut W { self.variant(TAMPTS_A::SAVE) } #[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 = "Active level for RTC_TAMP2 input\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMP2TRG_A { #[doc = "0: If TAMPFLT = 00: RTC_TAMPx input rising edge triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input staying low triggers a tamper detection event."] RISINGEDGE = 0, #[doc = "1: If TAMPFLT = 00: RTC_TAMPx input staying high triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input falling edge triggers a tamper detection event"] FALLINGEDGE = 1, } impl From<TAMP2TRG_A> for bool { #[inline(always)] fn from(variant: TAMP2TRG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMP2TRG`"] pub type TAMP2TRG_R = crate::R<bool, TAMP2TRG_A>; impl TAMP2TRG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMP2TRG_A { match self.bits { false => TAMP2TRG_A::RISINGEDGE, true => TAMP2TRG_A::FALLINGEDGE, } } #[doc = "Checks if the value of the field is `RISINGEDGE`"] #[inline(always)] pub fn is_rising_edge(&self) -> bool { *self == TAMP2TRG_A::RISINGEDGE } #[doc = "Checks if the value of the field is `FALLINGEDGE`"] #[inline(always)] pub fn is_falling_edge(&self) -> bool { *self == TAMP2TRG_A::FALLINGEDGE } } #[doc = "Write proxy for field `TAMP2TRG`"] pub struct TAMP2TRG_W<'a> { w: &'a mut W, } impl<'a> TAMP2TRG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP2TRG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "If TAMPFLT = 00: RTC_TAMPx input rising edge triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input staying low triggers a tamper detection event."] #[inline(always)] pub fn rising_edge(self) -> &'a mut W { self.variant(TAMP2TRG_A::RISINGEDGE) } #[doc = "If TAMPFLT = 00: RTC_TAMPx input staying high triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input falling edge triggers a tamper detection event"] #[inline(always)] pub fn falling_edge(self) -> &'a mut W { self.variant(TAMP2TRG_A::FALLINGEDGE) } #[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 = "RTC_TAMP2 input detection enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMP2E_A { #[doc = "0: RTC_TAMPx input detection disabled"] DISABLED = 0, #[doc = "1: RTC_TAMPx input detection enabled"] ENABLED = 1, } impl From<TAMP2E_A> for bool { #[inline(always)] fn from(variant: TAMP2E_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMP2E`"] pub type TAMP2E_R = crate::R<bool, TAMP2E_A>; impl TAMP2E_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMP2E_A { match self.bits { false => TAMP2E_A::DISABLED, true => TAMP2E_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TAMP2E_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TAMP2E_A::ENABLED } } #[doc = "Write proxy for field `TAMP2E`"] pub struct TAMP2E_W<'a> { w: &'a mut W, } impl<'a> TAMP2E_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP2E_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RTC_TAMPx input detection disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMP2E_A::DISABLED) } #[doc = "RTC_TAMPx input detection enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMP2E_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 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Tamper interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TAMPIE_A { #[doc = "0: Tamper interrupt disabled"] DISABLED = 0, #[doc = "1: Tamper interrupt enabled"] ENABLED = 1, } impl From<TAMPIE_A> for bool { #[inline(always)] fn from(variant: TAMPIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TAMPIE`"] pub type TAMPIE_R = crate::R<bool, TAMPIE_A>; impl TAMPIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TAMPIE_A { match self.bits { false => TAMPIE_A::DISABLED, true => TAMPIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TAMPIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TAMPIE_A::ENABLED } } #[doc = "Write proxy for field `TAMPIE`"] pub struct TAMPIE_W<'a> { w: &'a mut W, } impl<'a> TAMPIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMPIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMPIE_A::DISABLED) } #[doc = "Tamper interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMPIE_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 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Active level for RTC_TAMP1 input"] pub type TAMP1TRG_A = TAMP2TRG_A; #[doc = "Reader of field `TAMP1TRG`"] pub type TAMP1TRG_R = crate::R<bool, TAMP2TRG_A>; #[doc = "Write proxy for field `TAMP1TRG`"] pub struct TAMP1TRG_W<'a> { w: &'a mut W, } impl<'a> TAMP1TRG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP1TRG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "If TAMPFLT = 00: RTC_TAMPx input rising edge triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input staying low triggers a tamper detection event."] #[inline(always)] pub fn rising_edge(self) -> &'a mut W { self.variant(TAMP2TRG_A::RISINGEDGE) } #[doc = "If TAMPFLT = 00: RTC_TAMPx input staying high triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input falling edge triggers a tamper detection event"] #[inline(always)] pub fn falling_edge(self) -> &'a mut W { self.variant(TAMP2TRG_A::FALLINGEDGE) } #[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 = "RTC_TAMP1 input detection enable"] pub type TAMP1E_A = TAMP2E_A; #[doc = "Reader of field `TAMP1E`"] pub type TAMP1E_R = crate::R<bool, TAMP2E_A>; #[doc = "Write proxy for field `TAMP1E`"] pub struct TAMP1E_W<'a> { w: &'a mut W, } impl<'a> TAMP1E_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP1E_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RTC_TAMPx input detection disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMP2E_A::DISABLED) } #[doc = "RTC_TAMPx input detection enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMP2E_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 } } #[doc = "Tamper 3 mask flag"] pub type TAMP3MF_A = TAMP2MF_A; #[doc = "Reader of field `TAMP3MF`"] pub type TAMP3MF_R = crate::R<bool, TAMP2MF_A>; #[doc = "Write proxy for field `TAMP3MF`"] pub struct TAMP3MF_W<'a> { w: &'a mut W, } impl<'a> TAMP3MF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP3MF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x event generates a trigger event and TAMPxF must be cleared by software to allow next tamper event detection"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TAMP2MF_A::NOTMASKED) } #[doc = "Tamper x event generates a trigger event. TAMPxF is masked and internally cleared by hardware. The backup registers are not erased."] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TAMP2MF_A::MASKED) } #[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 = "Tamper 3 no erase"] pub type TAMP3NOERASE_A = TAMP2NOERASE_A; #[doc = "Reader of field `TAMP3NOERASE`"] pub type TAMP3NOERASE_R = crate::R<bool, TAMP2NOERASE_A>; #[doc = "Write proxy for field `TAMP3NOERASE`"] pub struct TAMP3NOERASE_W<'a> { w: &'a mut W, } impl<'a> TAMP3NOERASE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP3NOERASE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x event erases the backup registers"] #[inline(always)] pub fn erase(self) -> &'a mut W { self.variant(TAMP2NOERASE_A::ERASE) } #[doc = "Tamper x event does not erase the backup registers"] #[inline(always)] pub fn no_erase(self) -> &'a mut W { self.variant(TAMP2NOERASE_A::NOERASE) } #[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 = "Tamper 3 interrupt enable"] pub type TAMP3IE_A = TAMP2IE_A; #[doc = "Reader of field `TAMP3IE`"] pub type TAMP3IE_R = crate::R<bool, TAMP2IE_A>; #[doc = "Write proxy for field `TAMP3IE`"] pub struct TAMP3IE_W<'a> { w: &'a mut W, } impl<'a> TAMP3IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP3IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tamper x interrupt is disabled if TAMPIE = 0"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMP2IE_A::DISABLED) } #[doc = "Tamper x interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMP2IE_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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Active level for RTC_TAMP3 input"] pub type TAMP3TRG_A = TAMP2TRG_A; #[doc = "Reader of field `TAMP3TRG`"] pub type TAMP3TRG_R = crate::R<bool, TAMP2TRG_A>; #[doc = "Write proxy for field `TAMP3TRG`"] pub struct TAMP3TRG_W<'a> { w: &'a mut W, } impl<'a> TAMP3TRG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP3TRG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "If TAMPFLT = 00: RTC_TAMPx input rising edge triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input staying low triggers a tamper detection event."] #[inline(always)] pub fn rising_edge(self) -> &'a mut W { self.variant(TAMP2TRG_A::RISINGEDGE) } #[doc = "If TAMPFLT = 00: RTC_TAMPx input staying high triggers a tamper detection event. If TAMPFLT =\u{338} 00: RTC_TAMPx input falling edge triggers a tamper detection event"] #[inline(always)] pub fn falling_edge(self) -> &'a mut W { self.variant(TAMP2TRG_A::FALLINGEDGE) } #[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 = "RTC_TAMP3 detection enable"] pub type TAMP3E_A = TAMP2E_A; #[doc = "Reader of field `TAMP3E`"] pub type TAMP3E_R = crate::R<bool, TAMP2E_A>; #[doc = "Write proxy for field `TAMP3E`"] pub struct TAMP3E_W<'a> { w: &'a mut W, } impl<'a> TAMP3E_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TAMP3E_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RTC_TAMPx input detection disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TAMP2E_A::DISABLED) } #[doc = "RTC_TAMPx input detection enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TAMP2E_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 << 5)) | (((value as u32) & 0x01) << 5); self.w } } impl R { #[doc = "Bit 21 - Tamper 2 mask flag"] #[inline(always)] pub fn tamp2mf(&self) -> TAMP2MF_R { TAMP2MF_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - Tamper 2 no erase"] #[inline(always)] pub fn tamp2noerase(&self) -> TAMP2NOERASE_R { TAMP2NOERASE_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - Tamper 2 interrupt enable"] #[inline(always)] pub fn tamp2ie(&self) -> TAMP2IE_R { TAMP2IE_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - Tamper 1 mask flag"] #[inline(always)] pub fn tamp1mf(&self) -> TAMP1MF_R { TAMP1MF_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - Tamper 1 no erase"] #[inline(always)] pub fn tamp1noerase(&self) -> TAMP1NOERASE_R { TAMP1NOERASE_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - Tamper 1 interrupt enable"] #[inline(always)] pub fn tamp1ie(&self) -> TAMP1IE_R { TAMP1IE_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 15 - RTC_TAMPx pull-up disable"] #[inline(always)] pub fn tamppudis(&self) -> TAMPPUDIS_R { TAMPPUDIS_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 13:14 - RTC_TAMPx precharge duration"] #[inline(always)] pub fn tampprch(&self) -> TAMPPRCH_R { TAMPPRCH_R::new(((self.bits >> 13) & 0x03) as u8) } #[doc = "Bits 11:12 - RTC_TAMPx filter count"] #[inline(always)] pub fn tampflt(&self) -> TAMPFLT_R { TAMPFLT_R::new(((self.bits >> 11) & 0x03) as u8) } #[doc = "Bits 8:10 - Tamper sampling frequency"] #[inline(always)] pub fn tampfreq(&self) -> TAMPFREQ_R { TAMPFREQ_R::new(((self.bits >> 8) & 0x07) as u8) } #[doc = "Bit 7 - Activate timestamp on tamper detection event"] #[inline(always)] pub fn tampts(&self) -> TAMPTS_R { TAMPTS_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 4 - Active level for RTC_TAMP2 input"] #[inline(always)] pub fn tamp2trg(&self) -> TAMP2TRG_R { TAMP2TRG_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - RTC_TAMP2 input detection enable"] #[inline(always)] pub fn tamp2e(&self) -> TAMP2E_R { TAMP2E_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Tamper interrupt enable"] #[inline(always)] pub fn tampie(&self) -> TAMPIE_R { TAMPIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Active level for RTC_TAMP1 input"] #[inline(always)] pub fn tamp1trg(&self) -> TAMP1TRG_R { TAMP1TRG_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - RTC_TAMP1 input detection enable"] #[inline(always)] pub fn tamp1e(&self) -> TAMP1E_R { TAMP1E_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 24 - Tamper 3 mask flag"] #[inline(always)] pub fn tamp3mf(&self) -> TAMP3MF_R { TAMP3MF_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - Tamper 3 no erase"] #[inline(always)] pub fn tamp3noerase(&self) -> TAMP3NOERASE_R { TAMP3NOERASE_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - Tamper 3 interrupt enable"] #[inline(always)] pub fn tamp3ie(&self) -> TAMP3IE_R { TAMP3IE_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 6 - Active level for RTC_TAMP3 input"] #[inline(always)] pub fn tamp3trg(&self) -> TAMP3TRG_R { TAMP3TRG_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - RTC_TAMP3 detection enable"] #[inline(always)] pub fn tamp3e(&self) -> TAMP3E_R { TAMP3E_R::new(((self.bits >> 5) & 0x01) != 0) } } impl W { #[doc = "Bit 21 - Tamper 2 mask flag"] #[inline(always)] pub fn tamp2mf(&mut self) -> TAMP2MF_W { TAMP2MF_W { w: self } } #[doc = "Bit 20 - Tamper 2 no erase"] #[inline(always)] pub fn tamp2noerase(&mut self) -> TAMP2NOERASE_W { TAMP2NOERASE_W { w: self } } #[doc = "Bit 19 - Tamper 2 interrupt enable"] #[inline(always)] pub fn tamp2ie(&mut self) -> TAMP2IE_W { TAMP2IE_W { w: self } } #[doc = "Bit 18 - Tamper 1 mask flag"] #[inline(always)] pub fn tamp1mf(&mut self) -> TAMP1MF_W { TAMP1MF_W { w: self } } #[doc = "Bit 17 - Tamper 1 no erase"] #[inline(always)] pub fn tamp1noerase(&mut self) -> TAMP1NOERASE_W { TAMP1NOERASE_W { w: self } } #[doc = "Bit 16 - Tamper 1 interrupt enable"] #[inline(always)] pub fn tamp1ie(&mut self) -> TAMP1IE_W { TAMP1IE_W { w: self } } #[doc = "Bit 15 - RTC_TAMPx pull-up disable"] #[inline(always)] pub fn tamppudis(&mut self) -> TAMPPUDIS_W { TAMPPUDIS_W { w: self } } #[doc = "Bits 13:14 - RTC_TAMPx precharge duration"] #[inline(always)] pub fn tampprch(&mut self) -> TAMPPRCH_W { TAMPPRCH_W { w: self } } #[doc = "Bits 11:12 - RTC_TAMPx filter count"] #[inline(always)] pub fn tampflt(&mut self) -> TAMPFLT_W { TAMPFLT_W { w: self } } #[doc = "Bits 8:10 - Tamper sampling frequency"] #[inline(always)] pub fn tampfreq(&mut self) -> TAMPFREQ_W { TAMPFREQ_W { w: self } } #[doc = "Bit 7 - Activate timestamp on tamper detection event"] #[inline(always)] pub fn tampts(&mut self) -> TAMPTS_W { TAMPTS_W { w: self } } #[doc = "Bit 4 - Active level for RTC_TAMP2 input"] #[inline(always)] pub fn tamp2trg(&mut self) -> TAMP2TRG_W { TAMP2TRG_W { w: self } } #[doc = "Bit 3 - RTC_TAMP2 input detection enable"] #[inline(always)] pub fn tamp2e(&mut self) -> TAMP2E_W { TAMP2E_W { w: self } } #[doc = "Bit 2 - Tamper interrupt enable"] #[inline(always)] pub fn tampie(&mut self) -> TAMPIE_W { TAMPIE_W { w: self } } #[doc = "Bit 1 - Active level for RTC_TAMP1 input"] #[inline(always)] pub fn tamp1trg(&mut self) -> TAMP1TRG_W { TAMP1TRG_W { w: self } } #[doc = "Bit 0 - RTC_TAMP1 input detection enable"] #[inline(always)] pub fn tamp1e(&mut self) -> TAMP1E_W { TAMP1E_W { w: self } } #[doc = "Bit 24 - Tamper 3 mask flag"] #[inline(always)] pub fn tamp3mf(&mut self) -> TAMP3MF_W { TAMP3MF_W { w: self } } #[doc = "Bit 23 - Tamper 3 no erase"] #[inline(always)] pub fn tamp3noerase(&mut self) -> TAMP3NOERASE_W { TAMP3NOERASE_W { w: self } } #[doc = "Bit 22 - Tamper 3 interrupt enable"] #[inline(always)] pub fn tamp3ie(&mut self) -> TAMP3IE_W { TAMP3IE_W { w: self } } #[doc = "Bit 6 - Active level for RTC_TAMP3 input"] #[inline(always)] pub fn tamp3trg(&mut self) -> TAMP3TRG_W { TAMP3TRG_W { w: self } } #[doc = "Bit 5 - RTC_TAMP3 detection enable"] #[inline(always)] pub fn tamp3e(&mut self) -> TAMP3E_W { TAMP3E_W { w: self } } }
#[repr(C)] #[derive(Copy,Clone,PartialEq,Eq)] /// EFI Status type pub struct Status(u64); impl Status { #[inline] pub fn new(val: u64) -> Status { Status(val) } #[inline] pub fn err_or<T>(self, v: T) -> Result<T,Status> { if self.0 == 0 { Ok(v) } else { Err(self) } } #[inline] pub fn err_or_else<F, T>(self, f: F) -> Result<T,Status> where F: FnOnce()->T { if self.0 == 0 { Ok( f() ) } else { Err(self) } } #[inline] /// Panic if the status isn't SUCCESS pub fn unwrap(self) { self.unwrap_or( () ) } #[inline] /// Return the passed value, or panic if not SUCCESS pub fn unwrap_or<T>(self, v: T) -> T { self.expect_or("Called unwrap on a non-SUCCESS result", v) } #[inline] pub fn expect(self, msg: &str) { self.expect_or( msg, () ) } #[inline] pub fn expect_or<T,M: ::core::fmt::Display>(self, msg: M, v: T)->T { if self == SUCCESS { v } else { panic!("{}: {}", msg, self.message()); } } /// Return the official description message for this status value pub fn message(&self) -> &str { value_to_description(*self).unwrap_or("?") } } /// Allow `Status` to be used with the `?` operator impl ::core::ops::Try for Status { type Ok = (); type Error = Status; fn into_result(self) -> Result<(), Status> { if self == SUCCESS { Ok( () ) } else { Err(self) } } fn from_error(v: Status) -> Status { v } fn from_ok(_: ()) -> Status { SUCCESS } } impl ::core::fmt::Debug for Status { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { f.write_str("Status(")?; // Quick macro to reduce duplication of getting names for each status value match value_to_ident(*self) { Some(v) => f.write_str(v)?, None => write!(f, "Status({:#x})", self.0)?, } f.write_str(" ")?; f.write_str(self.message())?; f.write_str(")")?; Ok( () ) } } macro_rules! status_values { ($($v:expr => $n:ident $d:expr,)* @ERRORS $($v2:expr => $n2:ident $d2:expr,)*) => { $(pub const $n : Status = Status(0 << 63 | $v);)* $(pub const $n2 : Status = Status(1 << 63 | $v2);)* fn value_to_ident(v: Status)->Option<&'static str> { match v { $($n => Some(stringify!($n)),)* $($n2 => Some(stringify!($n2)),)* _ => None, } } fn value_to_description(v: Status) -> Option<&'static str> { match v { $($n => Some(stringify!($d1)),)* $($n2 => Some(stringify!($d2)),)* _ => None, } } } } pub const SUCCESS: Status = Status(0); status_values! { 1 => WARN_UNKNOWN_GLYPH "The string contained one or more characters that the device could not render and were skipped.", 2 => WARN_DELETE_FAILURE "The handle was closed, but the file was not deleted.", 3 => WARN_WRITE_FAILURE "The handle was closed, but the data to the file was not flushed properly.", 4 => WARN_BUFFER_TOO_SMALL "The resulting buffer was too small, and the data was truncated to the buffer size.", 5 => WARN_STALE_DATA "The data has not been updated within the timeframe set by local policy for this type of data.", 6 => WARN_FILE_SYSTEM "The resulting buffer contains UEFI-compliant file system.", @ERRORS 1 => LOAD_ERROR "The image failed to load.", 2 => INVALID_PARAMETER "A parameter was incorrect.", 3 => UNSUPPORTED "The operation is not supported.", 4 => BAD_BUFFER_SIZE "The buffer was not the proper size for the request.", 5 => BUFFER_TOO_SMALL "The buffer is not large enough to hold the requested data.", 6 => NOT_READY "There is no data pending upon return.", 7 => DEVICE_ERROR "The physical device reported an error while attempting the operation.", 8 => WRITE_PROTECTED "The device cannot be written to.", 9 => OUT_OF_RESOURCES "A resource has run out.", 10 => VOLUME_CORRUPTED "An inconstancy was detected on the file system causing the operating to fail.", 11 => VOLUME_FULL "There is no more space on the file system.", 12 => NO_MEDIA "The device does not contain any medium to perform the operation.", 13 => MEDIA_CHANGED "The medium in the device has changed since the last access.", 14 => NOT_FOUND "The item was not found.", 15 => ACCESS_DENIED "Access was denied.", 16 => NO_RESPONSE "The server was not found or did not respond to the request.", 17 => NO_MAPPING "A mapping to a device does not exist.", 18 => TIMEOUT "The timeout time expired.", 19 => NOT_STARTED "The protocol has not been started.", }
use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use web_sys::*; use wasm_bindgen::JsCast; use wasm_bindgen::JsValue; use web_sys::WebGl2RenderingContext as GL; use std::borrow::Borrow; mod dom; mod controls; mod ecs; use crate::texture; use crate::render::WebRenderer; use crate::app::{App, Msg}; use crate::prim::rect::Rectangle; use crate::client::controls::*; use crate::client::ecs::*; #[wasm_bindgen] pub struct WebClient { gl: Rc<GL>, app: Rc<App>, render: WebRenderer, clock: RefCell<f32>, } #[wasm_bindgen] impl WebClient { #[wasm_bindgen(constructor)] pub fn new() -> WebClient { wasm_logger::init(wasm_logger::Config::new(log::Level::Debug)); info!("New WebClient!"); // ------------------------------------------------------------ run_ecs(); // ------------------------------------------------------------ let gl = Rc::new(dom::create_webgl_context().unwrap()); let app = Rc::new(App::new()); let render = WebRenderer::new(&gl); append_controls(Rc::clone(&app)).expect("Append controls"); WebClient { gl, app, render, clock: RefCell::new(0.0) } } pub fn start(&self) -> Result<(), JsValue> { info!("WebClient starting..."); texture::Texture::new( &self.gl, "cat.png", 0); Ok(()) } pub fn update(&self, delta: u32) { self.app.msg(Msg::Tick(delta as f32 / 1000.)); let clock = *self.clock.borrow() + (delta as f32 / 1000.0); *self.clock.borrow_mut() = clock; } pub fn render(&mut self) { self.render.render(&self.gl, &self.clock.borrow()); // info!("Clock: {}", self.clock.borrow()); // self.render.render(&self.gl, &1.0); } }
pub type IDummyHICONIncluder = *mut ::core::ffi::c_void; pub type IThumbnailExtractor = *mut ::core::ffi::c_void;
use super::*; mod with_heap_binary; mod with_subbinary; #[test] fn without_non_negative_integer_position_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::is_bitstring(arc_process.clone()), strategy::term::is_not_non_negative_integer(arc_process.clone()), ) }, |(arc_process, binary, position)| { prop_assert_badarg!( result(&arc_process, binary, position), format!("position ({}) must be in 0..byte_size(binary)", position) ); Ok(()) }, ); } #[test] fn with_zero_position_returns_empty_prefix_and_binary() { with_process_arc(|arc_process| { let position = arc_process.integer(0); TestRunner::new(Config::with_source_file(file!())) .run( &strategy::term::is_bitstring(arc_process.clone()), |binary| { prop_assert_eq!( result(&arc_process, binary, position), Ok(arc_process .tuple_from_slice(&[arc_process.binary_from_bytes(&[]), binary],)) ); Ok(()) }, ) .unwrap(); }); }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::codec::Codec; use crate::errors::Result; use crate::metrics::RampReporter; use crate::permge::PriorityMerge; use crate::pipeline; use crate::registry::ServantId; use crate::sink::{ self, amqp, blackhole, cb, debug, dns, elastic, exit, file, gcs, gpub, handle_response, kafka, kv, nats, newrelic, otel, postgres, rest, stderr, stdout, tcp, udp, ws, }; use crate::source::Processors; use crate::url::ports::{IN, METRICS}; use crate::url::TremorUrl; use crate::{Event, OpConfig}; use async_channel::{self, bounded, unbounded}; use async_std::stream::StreamExt; // for .next() on PriorityMerge use async_std::task::{self, JoinHandle}; use beef::Cow; use halfbrown::HashMap; use pipeline::ConnectTarget; use std::borrow::{Borrow, BorrowMut}; use std::fmt; use tremor_common::ids::OfframpIdGen; use tremor_common::time::nanotime; #[derive(Debug)] pub enum Msg { Event { event: Event, input: Cow<'static, str>, }, Signal(Event), Connect { port: Cow<'static, str>, id: TremorUrl, addr: Box<pipeline::Addr>, }, Disconnect { port: Cow<'static, str>, id: TremorUrl, tx: async_channel::Sender<bool>, }, Terminate, } pub(crate) type Sender = async_channel::Sender<ManagerMsg>; pub type Addr = async_channel::Sender<Msg>; #[async_trait::async_trait] pub trait Offramp: Send { #[allow(clippy::too_many_arguments)] async fn start( &mut self, offramp_uid: u64, offramp_url: &TremorUrl, codec: &dyn Codec, codec_map: &HashMap<String, Box<dyn Codec>>, processors: Processors<'_>, is_linked: bool, reply_channel: async_channel::Sender<sink::Reply>, ) -> Result<()>; async fn on_event( &mut self, codec: &mut dyn Codec, codec_map: &HashMap<String, Box<dyn Codec>>, input: &str, event: Event, ) -> Result<()>; #[cfg(not(tarpaulin_include))] async fn on_signal(&mut self, _signal: Event) -> Option<Event> { None } async fn terminate(&mut self) {} fn default_codec(&self) -> &str; fn add_pipeline(&mut self, id: TremorUrl, addr: pipeline::Addr); fn remove_pipeline(&mut self, id: TremorUrl) -> bool; fn add_dest_pipeline(&mut self, port: Cow<'static, str>, id: TremorUrl, addr: pipeline::Addr); fn remove_dest_pipeline(&mut self, port: Cow<'static, str>, id: TremorUrl) -> bool; #[cfg(not(tarpaulin_include))] fn is_active(&self) -> bool { true } #[cfg(not(tarpaulin_include))] fn auto_ack(&self) -> bool { true } } pub trait Impl { fn from_config(config: &Option<OpConfig>) -> Result<Box<dyn Offramp>>; } // just a lookup #[cfg(not(tarpaulin_include))] pub fn lookup(name: &str, config: &Option<OpConfig>) -> Result<Box<dyn Offramp>> { match name { "amqp" => amqp::Amqp::from_config(config), "blackhole" => blackhole::Blackhole::from_config(config), "cb" => cb::Cb::from_config(config), "debug" => debug::Debug::from_config(config), "dns" => dns::Dns::from_config(config), "elastic" => elastic::Elastic::from_config(config), "exit" => exit::Exit::from_config(config), "file" => file::File::from_config(config), "kafka" => kafka::Kafka::from_config(config), "kv" => kv::Kv::from_config(config), "nats" => nats::Nats::from_config(config), "newrelic" => newrelic::NewRelic::from_config(config), "otel" => otel::OpenTelemetry::from_config(config), "postgres" => postgres::Postgres::from_config(config), "rest" => rest::Rest::from_config(config), "stderr" => stderr::StdErr::from_config(config), "stdout" => stdout::StdOut::from_config(config), "tcp" => tcp::Tcp::from_config(config), "udp" => udp::Udp::from_config(config), "ws" => ws::Ws::from_config(config), "gcs" => gcs::GoogleCloudStorage::from_config(config), "gpub" => gpub::GoogleCloudPubSub::from_config(config), _ => Err(format!("Offramp {} not known", name).into()), } } pub(crate) struct Create { pub id: ServantId, pub offramp: Box<dyn Offramp>, pub codec: Box<dyn Codec>, pub codec_map: halfbrown::HashMap<String, Box<dyn Codec>>, pub preprocessors: Vec<String>, pub postprocessors: Vec<String>, pub metrics_reporter: RampReporter, pub is_linked: bool, } #[cfg(not(tarpaulin_include))] impl fmt::Debug for Create { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "StartOfframp({})", self.id) } } /// This is control plane pub(crate) enum ManagerMsg { Create(async_channel::Sender<Result<Addr>>, Box<Create>), Stop, } #[derive(Debug, Default)] pub(crate) struct Manager { qsize: usize, } async fn send_to_pipelines( offramp_id: &TremorUrl, pipelines: &mut HashMap<TremorUrl, pipeline::Addr>, e: Event, ) { let mut i = pipelines.values_mut(); if let Some(first) = i.next() { for p in i { if let Err(e) = p.send_insight(e.clone()).await { error!("[Offramp::{}] Counterflow error: {}", offramp_id, e); }; } if let Err(e) = first.send_insight(e).await { error!("[Offramp::{}] Counterflow error: {}", offramp_id, e); }; } } pub(crate) enum OfframpMsg { Msg(Msg), Reply(sink::Reply), } impl Manager { pub fn new(qsize: usize) -> Self { Self { qsize } } #[allow(clippy::too_many_lines)] async fn offramp_task( &self, r: async_channel::Sender<Result<Addr>>, Create { mut codec, codec_map, mut offramp, preprocessors, postprocessors, mut metrics_reporter, is_linked, id, }: Create, offramp_uid: u64, ) -> Result<()> { let (msg_tx, msg_rx) = bounded::<Msg>(self.qsize); let (cf_tx, cf_rx) = unbounded::<sink::Reply>(); // we might need to wrap that somehow, but *shrug* if let Err(e) = offramp .start( offramp_uid, &id, codec.borrow(), &codec_map, Processors { pre: &preprocessors, post: &postprocessors, }, is_linked, cf_tx.clone(), ) .await { error!("Failed to create offramp {}: {}", id, e); return Err(e); } // merge channels and prioritize contraflow/insight events let m_rx = msg_rx.map(OfframpMsg::Msg); let c_rx = cf_rx.map(OfframpMsg::Reply); let mut to_and_from_offramp_rx = PriorityMerge::new(c_rx, m_rx); let offramp_url = id.clone(); let offramp_addr = msg_tx.clone(); task::spawn::<_, Result<()>>(async move { let mut pipelines: HashMap<TremorUrl, pipeline::Addr> = HashMap::new(); // for linked offramp output (port to pipeline(s) mapping) let mut dest_pipelines: HashMap<Cow<'static, str>, Vec<(TremorUrl, pipeline::Addr)>> = HashMap::new(); info!("[Offramp::{}] started", offramp_url); while let Some(offramp_msg) = to_and_from_offramp_rx.next().await { match offramp_msg { OfframpMsg::Msg(m) => { match m { Msg::Signal(signal) => { if let Some(insight) = offramp.on_signal(signal).await { send_to_pipelines(&offramp_url, &mut pipelines, insight).await; } } Msg::Event { event, input } => { let ingest_ns = event.ingest_ns; let transactional = event.transactional; let ids = event.id.clone(); metrics_reporter.periodic_flush(ingest_ns); metrics_reporter.increment_in(); let c: &mut dyn Codec = codec.borrow_mut(); let fail = if let Err(err) = offramp.on_event(c, &codec_map, input.borrow(), event).await { error!("[Offramp::{}] On Event error: {}", offramp_url, err); metrics_reporter.increment_err(); true } else { metrics_reporter.increment_out(); false }; // always send a fail, if on_event errored and the event is transactional // assuming if a sink fails, it didnt already sent a fail insight via reply_channel // even if it did, double fails or double acks should not lead to trouble // this will prevent fail insights being swallowed here // sinks need to take care of sending acks themselves. Deal with it. if (fail || offramp.auto_ack()) && transactional { let e = Event::ack_or_fail(!fail, ingest_ns, ids); send_to_pipelines(&offramp_url, &mut pipelines, e).await; } } Msg::Connect { port, id, addr } => { if port.eq_ignore_ascii_case(IN.as_ref()) { // connect incoming pipeline info!( "[Offramp::{}] Connecting pipeline {} to incoming port {}", offramp_url, id, port ); // if we are linked we send CB when an output is connected // TODO: if we are linked we should only send CB restore/break events if we receive one from the dest_pipelines if !is_linked || !dest_pipelines.is_empty() { let insight = Event::restore_or_break( offramp.is_active(), nanotime(), ); if let Err(e) = addr.send_insight(insight).await { error!( "[Offramp::{}] Could not send initial insight to {}: {}", offramp_url, id, e ); }; } pipelines.insert(id.clone(), (*addr).clone()); offramp.add_pipeline(id, *addr); } else if port.eq_ignore_ascii_case(METRICS.as_ref()) { info!( "[Offramp::{}] Connecting system metrics pipeline {}", offramp_url, id ); metrics_reporter.set_metrics_pipeline((id, *addr)); } else { // connect pipeline to outgoing port info!( "[Offramp::{}] Connecting pipeline {} via outgoing port {}", offramp_url, id, port ); let p = (id.clone(), (*addr).clone()); if let Some(port_ps) = dest_pipelines.get_mut(&port) { port_ps.push(p); } else { dest_pipelines.insert(port.clone(), vec![p]); } offramp.add_dest_pipeline(port, id.clone(), (*addr).clone()); // send connectInput msg to pipeline if let Err(e) = addr .send_mgmt(pipeline::MgmtMsg::ConnectInput { input_url: offramp_url.clone(), target: ConnectTarget::Offramp(offramp_addr.clone()), transactional: false, // TODO: Linked Offramps do not support insights yet }) .await { error!("[Offramp::{}] Error connecting this offramp as input to pipeline {}: {}", offramp_url, &id, e); } // send a CB restore/break if we have both an input an an output connected // to all the connected inputs if is_linked && !pipelines.is_empty() { let insight = Event::restore_or_break( offramp.is_active(), nanotime(), ); let mut iter = pipelines.iter(); if let Some((input_id, input_addr)) = iter.next() { for (input_id, input_addr) in iter { if let Err(e) = input_addr.send_insight(insight.clone()).await { error!( "[Offramp::{}] Could not send initial insight to {}: {}", offramp_url, input_id, e ); }; } if let Err(e) = input_addr.send_insight(insight).await { error!( "[Offramp::{}] Could not send initial insight to {}: {}", offramp_url, input_id, e ); }; } } } } Msg::Disconnect { port, id, tx } => { info!( "[Offramp::{}] Disconnecting pipeline {} on port {}", offramp_url, id, port ); let marked_done = if port.eq_ignore_ascii_case(IN.as_ref()) { pipelines.remove(&id); offramp.remove_pipeline(id.clone()) } else if port.eq_ignore_ascii_case(METRICS.as_ref()) { warn!( "[Offramp::{}] Cannot unlink pipeline {} from port {}", offramp_url, &id, &port ); false } else { if let Some(port_ps) = dest_pipelines.get_mut(&port) { port_ps.retain(|(url, _)| url != &id); } offramp.remove_dest_pipeline(port.clone(), id.clone()) }; tx.send(marked_done).await?; info!( "[Offramp::{}] Pipeline {} disconnected from port {}", offramp_url, &id, &port ); if marked_done { info!("[Offramp::{}] Marked as done ", offramp_url); offramp.terminate().await; break; } } Msg::Terminate => { info!("[Offramp::{}] Terminating...", offramp_url); offramp.terminate().await; break; } } } OfframpMsg::Reply(sink::Reply::Insight(event)) => { send_to_pipelines(&offramp_url, &mut pipelines, event).await; } OfframpMsg::Reply(sink::Reply::Response(port, event)) => { if let Some(pipelines) = dest_pipelines.get_mut(&port) { if let Err(e) = handle_response(event, pipelines.iter()).await { error!("[Offramp::{}] Response error: {}", offramp_url, e); } } } } } info!("[Offramp::{}] stopped", offramp_url); Ok(()) }); r.send(Ok(msg_tx)).await?; Ok(()) } pub fn start(self) -> (JoinHandle<Result<()>>, Sender) { let (tx, rx) = bounded(crate::QSIZE); let h = task::spawn(async move { info!("Offramp manager started"); let mut offramp_id_gen = OfframpIdGen::new(); while let Ok(msg) = rx.recv().await { match msg { ManagerMsg::Stop => { info!("Stopping onramps..."); break; } ManagerMsg::Create(r, c) => { self.offramp_task(r, *c, offramp_id_gen.next_id()).await?; } }; info!("Stopping offramps..."); } info!("Offramp manager stopped."); Ok(()) }); (h, tx) } } #[cfg(test)] mod tests { use super::*; use crate::QSIZE; #[derive(Debug)] enum FakeOfframpMsg { Event(Event), Signal(Event), AddPipeline(TremorUrl, pipeline::Addr), RemovePipeline(TremorUrl), AddDestPipeline(Cow<'static, str>, TremorUrl, pipeline::Addr), RemoveDestPipeline(Cow<'static, str>, TremorUrl), Start(u64), Terminate, } struct FakeOfframp { pipelines: usize, sender: async_channel::Sender<FakeOfframpMsg>, } impl FakeOfframp { fn new(sender: async_channel::Sender<FakeOfframpMsg>) -> Self { Self { pipelines: 0, sender, } } } #[async_trait::async_trait] impl Offramp for FakeOfframp { async fn start( &mut self, offramp_uid: u64, _offramp_url: &TremorUrl, _codec: &dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, _processors: Processors<'_>, _is_linked: bool, _reply_channel: async_channel::Sender<sink::Reply>, ) -> Result<()> { self.sender.send(FakeOfframpMsg::Start(offramp_uid)).await?; Ok(()) } async fn on_event( &mut self, _codec: &mut dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, _input: &str, event: Event, ) -> Result<()> { self.sender.send(FakeOfframpMsg::Event(event)).await?; Ok(()) } async fn on_signal(&mut self, signal: Event) -> Option<Event> { self.sender .send(FakeOfframpMsg::Signal(signal)) .await .unwrap(); None } fn default_codec(&self) -> &str { "json" } fn add_pipeline(&mut self, id: TremorUrl, addr: pipeline::Addr) { self.pipelines += 1; let sender = self.sender.clone(); task::block_on(async { sender .send(FakeOfframpMsg::AddPipeline(id, addr)) .await .unwrap(); }) } fn remove_pipeline(&mut self, id: TremorUrl) -> bool { self.pipelines -= 1; let sender = self.sender.clone(); task::block_on(async { sender .send(FakeOfframpMsg::RemovePipeline(id)) .await .unwrap(); }); self.pipelines == 0 } fn add_dest_pipeline( &mut self, port: Cow<'static, str>, id: TremorUrl, addr: pipeline::Addr, ) { self.pipelines += 1; let sender = self.sender.clone(); task::block_on(async { sender .send(FakeOfframpMsg::AddDestPipeline(port, id, addr)) .await .unwrap(); }) } fn remove_dest_pipeline(&mut self, port: Cow<'static, str>, id: TremorUrl) -> bool { self.pipelines -= 1; let sender = self.sender.clone(); task::block_on(async { sender .send(FakeOfframpMsg::RemoveDestPipeline(port, id)) .await .unwrap(); }); self.pipelines == 0 } async fn terminate(&mut self) { self.sender.send(FakeOfframpMsg::Terminate).await.unwrap() } } #[async_std::test] async fn offramp_lifecycle_test() -> Result<()> { let mngr = Manager::new(QSIZE); let (handle, sender) = mngr.start(); let (tx, rx) = async_channel::bounded(1); let codec = crate::codec::lookup("json")?; let id = TremorUrl::parse("/offramp/fake/instance")?; let ramp_reporter = RampReporter::new(id.clone(), Some(1_000_000_000)); let (offramp_tx, offramp_rx) = async_channel::unbounded(); let offramp = FakeOfframp::new(offramp_tx); let create = ManagerMsg::Create( tx, Box::new(Create { id, codec, codec_map: HashMap::new(), preprocessors: vec!["lines".into()], postprocessors: vec!["lines".into()], metrics_reporter: ramp_reporter, offramp: Box::new(offramp), is_linked: true, }), ); sender.send(create).await?; let offramp_sender = rx.recv().await??; match offramp_rx.recv().await? { FakeOfframpMsg::Start(id) => { println!("started with id: {}", id); } e => assert!(false, "Expected start msg, got {:?}", e), } let fake_pipeline_id = TremorUrl::parse("/pipeline/fake/instance/out")?; let (tx, _rx) = async_channel::unbounded(); let (cf_tx, _cf_rx) = async_channel::unbounded(); let (mgmt_tx, _mgmt_rx) = async_channel::unbounded(); let fake_pipeline = Box::new(pipeline::Addr::new( tx, cf_tx, mgmt_tx, fake_pipeline_id.clone(), )); // connect incoming pipeline offramp_sender .send(Msg::Connect { port: IN, id: fake_pipeline_id.clone(), addr: fake_pipeline.clone(), }) .await?; match offramp_rx.recv().await? { FakeOfframpMsg::AddPipeline(id, _addr) => { assert_eq!(fake_pipeline_id, id); } e => { assert!(false, "Expected add pipeline msg, got {:?}", e) } } // send event offramp_sender .send(Msg::Event { input: IN, event: Event::default(), }) .await?; match offramp_rx.recv().await? { FakeOfframpMsg::Event(_event) => {} e => assert!(false, "Expected event msg, got {:?}", e), } let (disc_tx, disc_rx) = async_channel::bounded(1); offramp_sender .send(Msg::Disconnect { port: IN, id: fake_pipeline_id.clone(), tx: disc_tx, }) .await?; assert!( disc_rx.recv().await?, "expected true, as nothing is connected anymore" ); match offramp_rx.recv().await? { FakeOfframpMsg::RemovePipeline(id) => { assert_eq!(fake_pipeline_id, id); } e => { assert!(false, "Expected terminate msg, got {:?}", e) } } // stop shit sender.send(ManagerMsg::Stop).await?; handle.cancel().await; Ok(()) } }
use super::lexer::Lexer; use std::io::{BufRead, Write}; const PROMPT: &[u8] = b">> "; pub fn start<R, W>(mut reader: R, mut writer: W) where R: BufRead, W: Write, { loop { writer.write(PROMPT).unwrap(); writer.flush().unwrap(); let mut line = String::new(); if let Ok(_) = reader.read_line(&mut line) { let mut l = Lexer::new(line); l.for_each(|tok| { writer.write_fmt(format_args!("{:?}\n", tok)).unwrap(); writer.flush().unwrap(); }); } else { return; } } }
mod decimal; mod multi_btreemap; pub mod top_sort { use std::num::ParseIntError; use topsort::decimal::Decimal; use topsort::multi_btreemap::MBTreeMap; use csv::ByteRecord; #[derive(Clone)] pub enum OrderType { DEFAULT, REVERSE, } pub struct TopSortEntry<'a> { key: Decimal, byte_record: &'a ByteRecord, } impl<'a> TopSortEntry<'a> { pub fn new(key: &str, line: &'a ByteRecord) -> Result<TopSortEntry<'a>, ParseIntError> { Ok(TopSortEntry { key: key.parse::<Decimal>()?, byte_record: line, }) } } pub struct TopSort { ordering: OrderType, desired_resuts: usize, tree: MBTreeMap<Decimal, ByteRecord>, trim_ratio: usize, bound: Option<Decimal>, } impl TopSort { pub fn new(ordering: OrderType, desired_resuts: usize) -> TopSort { TopSort { ordering, desired_resuts, tree: MBTreeMap::new(), trim_ratio: 2, bound: None, } } fn in_bound(&self, value: Decimal) -> bool { // match self.ordering { // OrderType::DEFAULT => self.tree.iter().nth(0).map_or(true,|(key,_)| key < &value), // OrderType::REVERSE => self.tree.iter().last().map_or(true,|(key,_)| key > &value), // } match self.ordering { OrderType::DEFAULT => self.bound.map_or(true, |bound| bound <= value), OrderType::REVERSE => self.bound.map_or(true, |bound| bound >= value), } } fn update_bound(&mut self) { self.bound = match self.ordering { OrderType::DEFAULT => self.tree.iter().nth(0).map(|x| x.0).cloned(), OrderType::REVERSE => self.tree.iter().last().map(|x| x.0).cloned(), } } pub fn add(&mut self, entry: TopSortEntry) -> () { if !self.in_bound(entry.key) { return; } let decimal_key = entry.key; self.tree.insert(decimal_key, entry.byte_record.clone()); if self.bound.is_none() { self.update_bound(); } if self.tree.len() > self.desired_resuts * self.trim_ratio { self.trim_tree(); } } fn trim_tree(&mut self) -> () { match self.ordering { OrderType::DEFAULT => self.trim_tree_top(), OrderType::REVERSE => self.trim_tree_bottom(), } self.update_bound(); } fn trim_tree_top(&mut self) -> () { if self.desired_resuts > self.tree.len() { return; } let ammount_to_prune = self.tree.len() - self.desired_resuts; let (&splitter, _) = self.tree.iter().nth(ammount_to_prune).unwrap(); let tree_top = self.tree.split_off(&splitter); self.tree = tree_top; assert_eq!(self.tree.len(), self.desired_resuts); } fn trim_tree_bottom(&mut self) -> () { if self.desired_resuts > self.tree.len() { println!("{}", "early exit"); return; } let ammount_to_prune = self.tree.len() - self.desired_resuts; let (&splitter, _) = self.tree.iter().rev().nth(ammount_to_prune - 1).unwrap(); let _tree_top = self.tree.split_off(&splitter); } pub fn get_result(&self) -> Vec<ByteRecord> { let results = self.tree.flatten(); let should_skip = if results.len() > self.desired_resuts { results.len() - self.desired_resuts } else { 0 }; match self.ordering { OrderType::DEFAULT => results.iter().skip(should_skip).cloned().collect(), OrderType::REVERSE => results.iter().rev().skip(should_skip).cloned().collect(), } } } }
pub mod beta; pub mod cek; pub mod cps; #[derive(Clone, Debug, PartialEq)] pub enum Term { Var(usize), Abs(Box<Term>), App(Box<Term>, Box<Term>), } impl Term { fn whnf(&self) -> bool { match self { Term::Abs(e) => e.whnf(), Term::App(e, _) => e.whnf(), _ => true, } } fn nf(&self) -> bool { match self { Term::App(_, _) => false, _ => true, } } } #[macro_export] macro_rules! var { ($ex:expr) => { Term::Var($ex) }; } #[macro_export] macro_rules! abs { ($ex:expr) => { Term::Abs(Box::new($ex)) }; } #[macro_export] macro_rules! app { ($ex:expr, $ex2:expr) => { Term::App(Box::new($ex), Box::new($ex2)) }; } pub mod church { use super::*; pub fn tru() -> Term { abs!(abs!(var!(1))) } pub fn fls() -> Term { abs!(abs!(var!(0))) } pub fn test() -> Term { abs!(abs!(abs!(app!(app!(var!(2), var!(1)), var!(0))))) } pub fn and() -> Term { abs!(abs!(app!(app!(var!(1), var!(0)), fls()))) } }
// Copyright 2021 Chiral Ltd. // Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0) // This file may not be copied, modified, or distributed // except according to those terms. //! Case breakable use crate::core; use super::mapping_ops; fn is_neighbour_breakable<T: core::graph::Vertex>( vertex_index: usize, neighbour_index: usize, vertices_unexpected: &Vec<usize>, vertex_vec: &core::graph::VertexVec<T> ) -> bool { let mut vertices_visited: Vec<usize> = vec![vertex_index]; let mut vertices_boundary: Vec<usize> = vertex_vec[neighbour_index].neighbour_indexes().into_iter() .filter(|&idx| idx != vertex_index) .collect(); for vn in vertices_unexpected.iter() { if vertices_boundary.contains(vn) { return false; } } while vertices_boundary.len() > 0 { let neighbours: Vec<usize> = vertices_boundary.iter() .map(|&idx| vertex_vec[idx].neighbour_indexes()) .flatten() .filter(|idx| !vertices_visited.contains(idx)) .filter(|idx| !vertices_boundary.contains(idx)) .collect(); for vn in vertices_unexpected.iter() { if neighbours.contains(vn) { return false; } } vertices_visited.append(&mut vertices_boundary); vertices_boundary = neighbours; } true } fn get_breakable_neighbours<T: core::graph::Vertex>( vertex_index: usize, vertices_unexpected: &Vec<usize>, vv: &core::graph::VertexVec<T> ) -> Vec<usize> { vv[vertex_index].neighbour_indexes().into_iter() .filter(|&vi| is_neighbour_breakable(vertex_index, vi, vertices_unexpected, vv)) .collect() } /// The maximum graph distance between two vertices in an orbit /// Normally every two-vertex pair should be considered. /// As the orbit is resulted from givp process, we only consider the distances between the first vertex and the other vertices fn max_graph_distance_inside_orbit<T: core::graph::Vertex>( orbit: &Vec<usize>, vv: &core::graph::VertexVec<T> ) -> usize { let mut distance: usize = 0; for idx in 1..orbit.len() { let distance_tmp: usize = core::graph_ops::graph_distance(orbit[0], orbit[idx], vv); if distance_tmp > distance { distance = distance_tmp; } } distance } /// return start orbit and mapping starting vertices fn find_starting_orbit<T: core::graph::Vertex>( orbits_after_partition: &Vec<core::orbit_ops::Orbit>, vv: &core::graph::VertexVec<T> ) -> (core::orbit_ops::Orbit, Vec<Vec<usize>>) { let mut orbits_cloned = orbits_after_partition.to_vec(); orbits_cloned.sort_by_cached_key( |orbit| max_graph_distance_inside_orbit(orbit, vv) ); for orbit in orbits_cloned.iter() { if vv[orbit[0]].degree() == 1 { continue; } if get_breakable_neighbours(orbit[0], orbit, vv).len() > 0 { return (orbit.clone(), orbit.iter().map(|&vi| get_breakable_neighbours(vi, orbit, vv)).collect()); } } (vec![], vec![]) } fn get_boundary_edges_for_breakable_subgraph<T: core::graph::Vertex>( vertex_index: usize, starting_neighbours: &mapping_ops::NeighbourIndexes, vv: &core::graph::VertexVec<T> ) -> Vec<mapping_ops::SimpleEdge> { vv[vertex_index].neighbour_indexes().iter() .filter(|nvi| !starting_neighbours.contains(nvi)) .map(|&nvi| (vertex_index, nvi)) .collect() } pub fn create_mapping<T: core::graph::Vertex>( orbits_after_partition: &Vec<core::orbit_ops::Orbit>, numbering: &Vec<usize>, vv: &core::graph::VertexVec<T> ) -> Result<(mapping_ops::VertexMapping, mapping_ops::BoundaryEdges), String> { let (starting_orbit, starting_neighbours) = find_starting_orbit(orbits_after_partition, vv); if starting_orbit.len() == 0 { Err(format!("Breakable Mapping: cannot find a starting orbit from orbits: {:?}", orbits_after_partition)) } else { if cfg!(debug_assertions) { println!("Breakable Mapping: starting orbit {:?}", starting_orbit); println!("Breakable Mapping: starting neighbours: {:?}", starting_neighbours); } let boundary_edges = (0..starting_orbit.len()) .map(|idx| get_boundary_edges_for_breakable_subgraph(starting_orbit[idx], &starting_neighbours[idx], vv)) .collect(); let mut mapping: mapping_ops::VertexMapping = starting_orbit.iter() .map(|&v_idx| vec![v_idx]) .collect(); let mut mapping_stack: Vec<mapping_ops::MappingStatus> = vec![]; let mut mapped_cur: usize = 0; match mapping_ops::mapping_neighbours(&mut starting_neighbours.clone(), numbering) { Ok(neighbour_mappings) => { mapping_ops::update_mapping_stack(mapped_cur, &mapping, &boundary_edges, &neighbour_mappings, &mut mapping_stack); if let Some((_, new_mapping, _)) = mapping_stack.pop() { mapping = new_mapping; } else { panic!("successful neighbour mapping should have at least one mapping!") } }, Err(_) => { panic!("Error on mapping starting neighbours") } } // Mapping Process mapped_cur += 1; while mapped_cur < mapping[0].len() { let mut neighbours: Vec<mapping_ops::NeighbourIndexes> = (0..mapping.len()) .map(|idx| mapping_ops::find_new_neighbours(mapping[idx][mapped_cur], &mapping[idx], vv)) .collect(); if neighbours[0].len() > 0 { match mapping_ops::mapping_neighbours(&mut neighbours, numbering) { Ok(neighbour_mappings) => { mapping_ops::update_mapping_stack(mapped_cur, &mapping, &boundary_edges, &neighbour_mappings, &mut mapping_stack); }, Err(_) => { } } if let Some((new_mapped_cur, new_mapping, _)) = mapping_stack.pop() { mapping = new_mapping; mapped_cur = new_mapped_cur; } else { panic!("mapping status runs out! mapping fails!") } } else { mapped_cur += 1; } } Ok((mapping, boundary_edges)) } } #[cfg(test)] mod test_reduce_case_breakable { use super::*; use crate::ext::molecule; #[test] fn test_is_neighbour_breakable() { let smiles_vec: Vec<String> = vec![ r#"COc1cc(Cc2cnc(/N=C3\C(=O)N(CN(Cc4ccccc4)Cc4ccccc4)c4ccc(Cl)cc43)nc2N)cc(OC)c1OC"#, // chembl 2209 "CCCC[C@H](NC(=O)[C@H](Cc1c[nH]c2ccccc12)NC(=O)CCNC(=O)CCNC(=S)Nc1ccc(O)c(NC(=O)CNC(=O)CSC(c2ccccc2)(c2ccccc2)c2ccccc2)c1)C(=O)N[C@@H](CC(=O)O)C(=O)N[C@@H](Cc1ccccc1)C(N)=O", // chembl 2067 ].iter().map(|s| s.to_string()).collect(); let tests_params: Vec<Vec<(usize, usize, Vec<usize>, bool)>> = vec![ vec![ (2, 1, vec![2, 45, 42], true), (2, 3, vec![2, 45, 42], false), (2, 45, vec![2, 45, 42], false) ], vec![ (61, 62, vec![61, 49, 55], true), (61, 66, vec![61, 49, 55], true), (61, 48, vec![61, 49, 55], false), ], ]; for (idx, smiles) in smiles_vec.iter().enumerate() { let mol = molecule::Molecule::from_smiles(smiles); println!("{}", mol.smiles_with_index(smiles, &vec![])); let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); for tp in tests_params[idx].iter() { assert_eq!(is_neighbour_breakable(tp.0, tp.1, &tp.2, &vv), tp.3); } } } #[test] fn test_find_starting_orbit() { type InputType1 = String; type ReturnType = (core::orbit_ops::Orbit, Vec<Vec<usize>>); let test_data: Vec<(InputType1, ReturnType)> = vec![ ( "O=C(O)CCCC(=O)NCCCC[C@@H](C(=O)NCCCCCCCCCCCCNC(=O)[C@@H](CCCCNC(=O)CCCC(=O)O)N(Cc1ccc(OCc2ccccc2)cc1)Cc1ccc(OCc2ccccc2)cc1)N(Cc1ccc(OCc2ccccc2)cc1)Cc1ccc(OCc2ccccc2)cc1", (vec![22, 23], vec![vec![21], vec![24]]), ), ( "CCOP(=O)(OCC)OCc1ccc(S(=O)(=O)CC(C[C@H]2O[C@@H]3C[C@]4(C)CC[C@H]5[C@H](C)CC[C@@H]([C@H]2C)[C@]53OO4)C[C@H]2O[C@@H]3C[C@]4(C)CC[C@H]5[C@H](C)CC[C@@H]([C@H]2C)[C@]53OO4)cc1", (vec![19, 39], vec![vec![20], vec![40]]), ), ( "CC(C)(C)c1cc2c(OCCCCNC(=N)N)c(c1)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)C2", (vec![7, 29, 49, 69], vec![vec![8], vec![30], vec![50], vec![70]]), ), ( "O=c1cc(-c2ccc(OCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOc3ccc(-c4cc(=O)c5ccccc5o4)cc3)cc2)oc2ccccc12", (vec![27, 28], vec![vec![26], vec![29]]), ), ( "CC1=C(CC[C@H](C)CO[C@@H]2O[C@H](CO)[C@@H](O)[C@H](O)[C@H]2O)O[C@H]2C[C@H]3[C@@H]4CC[C@@H]5C[C@@H](O[C@@H]6O[C@H](CO)[C@H](O)[C@H](O)[C@H]6O[C@@H]6O[C@H](CO)[C@@H](O)[C@H](O)[C@H]6O)CC[C@]5(C)[C@H]4CC[C@]3(C)[C@@H]12", (vec![], vec![]), ), ( "CCn1c2ccc3cc2c2cc(ccc21)C(=O)c1ccc(cc1)Cn1cc[n+](c1)Cc1ccc(cc1)C(=O)c1ccc2c(c1)c1cc(ccc1n2CC)C(=O)c1ccc(cc1)C[n+]1ccn(c1)Cc1ccc(cc1)C3=O", (vec![15, 74], vec![vec![16], vec![75]]), ), ( "CCCCCCCCOc1c2cc(C(=O)O)cc1Cc1cc(C(=O)O)cc(c1OCCCCCCCC)Cc1cc(C(=O)O)cc(c1OCCCCCCCC)Cc1cc(cc(C(=O)O)c1)C2", (vec![9, 46], vec![vec![8], vec![47]]), ), ( "O=C(Nc1ccc([N+](=O)[O-])cc1)OCCN1CCN(CCOC(=O)Nc2ccc([N+](=O)[O-])cc2)CCN(CCOC(=O)Nc2ccc([N+](=O)[O-])cc2)CCN(CCOC(=O)Nc2ccc([N+](=O)[O-])cc2)CC1", (vec![15, 18, 36, 54], vec![vec![14], vec![19], vec![37], vec![55]]), ), ( "CC(C)C[C@@H]1NC(=O)[C@H](CCCN)NC(=O)[C@H](C(C)C)NC(=O)[C@@H]2CCCN2C(=O)[C@@H](C2c3ccccc3-c3ccccc32)NC(=O)[C@H](CC(C)C)NC(=O)[C@H](CCCN)NC(=O)[C@H](C(C)C)NC(=O)[C@@H]2CCCN2C(=O)[C@@H](C2c3ccccc3-c3ccccc32)NC1=O", (vec![4, 47], vec![vec![3], vec![48]]), ), ( "CC(=O)O[C@H]1[C@H](C2=CC(=O)c3ccccc3C2=O)O[C@H](Cn2cc(COC(=O)c3cccc(C(=O)OCc4cn(C[C@H]5O[C@@H](C6=CC(=O)c7ccccc7C6=O)[C@H](OC(C)=O)[C@@H](OC(C)=O)[C@H]5OC(C)=O)nn4)c3)nn2)[C@H](OC(C)=O)[C@@H]1OC(C)=O", (vec![28, 32], vec![vec![26], vec![33]]), ), ( "c1ccc(Cc2ccc[n+](CCCCCc3cc(CCCCC[n+]4cccc(Cc5ccccc5)c4)c(CCCCC[n+]4cccc(Cc5ccccc5)c4)cc3CCCCC[n+]3cccc(Cc4ccccc4)c3)c2)cc1", (vec![15, 17, 36, 56], vec![vec![14], vec![18], vec![37], vec![57]]), ), ( "NCCCNCCCCN(CCCN)C(=O)CCCCNC(=O)c1ccc(-c2c3nc(c(-c4ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc4)c4ccc([nH]4)c(-c4ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc4)c4nc(c(-c5ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc5)c5ccc2[nH]5)C=C4)C=C3)cc1", (vec![27, 31, 66, 99], vec![vec![26], vec![32], vec![67], vec![100]]), ), ( "CC(C)C[C@H]1C(=O)N(C)CC(=O)N(C)[C@@H](C(C)C)C(=O)NC[C@H](NC(=O)c2ccc3ccccc3n2)C(=O)N(C)[C@@H](CC(C)C)C(=O)N(C)CC(=O)N(C)[C@@H](C(C)C)C(=O)NC[C@H](NC(=O)c2ccc3ccccc3n2)C(=O)N1C", (vec![4, 40], vec![vec![3], vec![41]]), ), ( "CCCC[C@H](NC(=O)[C@H](Cc1c[nH]c2ccccc12)NC(=O)CCNC(=O)CCNC(=S)Nc1ccc(O)c(NC(=O)CNC(=O)CSC(c2ccccc2)(c2ccccc2)c2ccccc2)c1)C(=O)N[C@@H](CC(=O)O)C(=O)N[C@@H](Cc1ccccc1)C(N)=O", // chembl 2067 (vec![49, 55, 61], vec![vec![54, 50], vec![60, 56], vec![66, 62]]), ), ].iter().map(|td| (td.0.to_string(), td.1.clone())).collect(); for td in test_data.iter() { let (smiles, results) = td; let mol = molecule::Molecule::from_smiles(smiles); println!("{}", mol.smiles_with_index(smiles, &vec![])); let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); let mut numbering: Vec<usize> = vec![]; let mut orbits_after_partition: Vec<core::orbit_ops::Orbit> = vec![]; core::givp::run::<molecule::AtomExtendable>(&vv, &mut numbering, &mut orbits_after_partition); assert_eq!(find_starting_orbit(&orbits_after_partition, &vv), *results); } } #[test] fn test_mapping() { type InputType1 = String; type ReturnType = (mapping_ops::VertexMapping, mapping_ops::BoundaryEdges); let test_data: Vec<(InputType1, ReturnType)> = vec![ ( "O=C(O)CCCC(=O)NCCCC[C@@H](C(=O)NCCCCCCCCCCCCNC(=O)[C@@H](CCCCNC(=O)CCCC(=O)O)N(Cc1ccc(OCc2ccccc2)cc1)Cc1ccc(OCc2ccccc2)cc1)N(Cc1ccc(OCc2ccccc2)cc1)Cc1ccc(OCc2ccccc2)cc1", (vec![vec![22, 21, 20, 19, 18, 17, 16, 14, 15, 13, 12, 77, 11, 78, 93, 10, 79, 94, 9, 92, 80, 107, 95, 8, 91, 81, 106, 96, 6, 82, 97, 7, 5, 83, 98, 4, 84, 99, 3, 85, 100, 1, 90, 86, 105, 101, 2, 0, 89, 87, 104, 102, 88, 103], vec![23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 46, 34, 62, 47, 35, 63, 48, 36, 64, 76, 49, 61, 37, 65, 75, 50, 60, 38, 66, 51, 39, 40, 67, 52, 41, 68, 53, 42, 69, 54, 43, 70, 74, 55, 59, 45, 44, 71, 73, 56, 58, 72, 57]], vec![vec![(22, 23)], vec![(23, 22)]]), ), ( "CCOP(=O)(OCC)OCc1ccc(S(=O)(=O)CC(C[C@H]2O[C@@H]3C[C@]4(C)CC[C@H]5[C@H](C)CC[C@@H]([C@H]2C)[C@]53OO4)C[C@H]2O[C@@H]3C[C@]4(C)CC[C@H]5[C@H](C)CC[C@@H]([C@H]2C)[C@]53OO4)cc1", (vec![vec![19, 20, 21, 34, 22, 35, 33, 23, 36, 32, 24, 37, 28, 31, 25, 26, 38, 27, 29, 30], vec![39, 40, 41, 54, 42, 55, 53, 43, 56, 52, 44, 57, 48, 51, 45, 46, 58, 47, 49, 50]], vec![vec![(19, 18)], vec![(39, 18)]]), ), ( "CC(C)(C)c1cc2c(OCCCCNC(=N)N)c(c1)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)C2", (vec![vec![7, 8, 9, 10, 11, 12, 13, 14, 16, 15], vec![29, 30, 31, 32, 33, 34, 35, 36, 38, 37], vec![49, 50, 51, 52, 53, 54, 55, 56, 58, 57], vec![69, 70, 71, 72, 73, 74, 75, 76, 78, 77]], vec![vec![(7, 6), (7, 17)], vec![(29, 28), (29, 20)], vec![(49, 48), (49, 40)], vec![(69, 68), (69, 60)]]), ), ( "O=c1cc(-c2ccc(OCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOc3ccc(-c4cc(=O)c5ccccc5o4)cc3)cc2)oc2ccccc12", (vec![vec![27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 65, 5, 66, 4, 3, 2, 67, 1, 68, 0, 73, 69, 72, 70, 71], vec![28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 64, 50, 63, 51, 52, 53, 62, 54, 61, 55, 56, 60, 57, 59, 58]], vec![vec![(27, 28)], vec![(28, 27)]]), ), ( "CCn1c2ccc3cc2c2cc(ccc21)C(=O)c1ccc(cc1)Cn1cc[n+](c1)Cc1ccc(cc1)C(=O)c1ccc2c(c1)c1cc(ccc1n2CC)C(=O)c1ccc(cc1)C[n+]1ccn(c1)Cc1ccc(cc1)C3=O", (vec![vec![15, 16], vec![74, 75]], vec![vec![(15, 11), (15, 17)], vec![(74, 71), (74, 6)]]), ), ( "CCCCCCCCOc1c2cc(C(=O)O)cc1Cc1cc(C(=O)O)cc(c1OCCCCCCCC)Cc1cc(C(=O)O)cc(c1OCCCCCCCC)Cc1cc(cc(C(=O)O)c1)C2", (vec![vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0], vec![46, 47, 48, 49, 50, 51, 52, 53, 54, 55]], vec![vec![(9, 17), (9, 10)], vec![(46, 45), (46, 38)]]), ), ( "O=C(Nc1ccc([N+](=O)[O-])cc1)OCCN1CCN(CCOC(=O)Nc2ccc([N+](=O)[O-])cc2)CCN(CCOC(=O)Nc2ccc([N+](=O)[O-])cc2)CCN(CCOC(=O)Nc2ccc([N+](=O)[O-])cc2)CC1", (vec![vec![15, 14, 13, 12, 1, 0, 2, 3, 11, 4, 10, 5, 6, 7, 9, 8], vec![18, 19, 20, 21, 22, 23, 24, 25, 26, 33, 27, 32, 28, 29, 31, 30], vec![36, 37, 38, 39, 40, 41, 42, 43, 51, 44, 50, 45, 46, 47, 49, 48], vec![54, 55, 56, 57, 58, 59, 60, 61, 62, 69, 63, 68, 64, 65, 67, 66]], vec![vec![(15, 71), (15, 16)], vec![(18, 17), (18, 34)], vec![(36, 35), (36, 52)], vec![(54, 53), (54, 70)]]), ), ( "CC(C)C[C@@H]1NC(=O)[C@H](CCCN)NC(=O)[C@H](C(C)C)NC(=O)[C@@H]2CCCN2C(=O)[C@@H](C2c3ccccc3-c3ccccc32)NC(=O)[C@H](CC(C)C)NC(=O)[C@H](CCCN)NC(=O)[C@H](C(C)C)NC(=O)[C@@H]2CCCN2C(=O)[C@@H](C2c3ccccc3-c3ccccc32)NC1=O", (vec![vec![4, 3, 1, 0, 2], vec![47, 48, 49, 51, 50]], vec![vec![(4, 92), (4, 5)], vec![(47, 45), (47, 52)]]), ), ( "CC(=O)O[C@H]1[C@H](C2=CC(=O)c3ccccc3C2=O)O[C@H](Cn2cc(COC(=O)c3cccc(C(=O)OCc4cn(C[C@H]5O[C@@H](C6=CC(=O)c7ccccc7C6=O)[C@H](OC(C)=O)[C@@H](OC(C)=O)[C@H]5OC(C)=O)nn4)c3)nn2)[C@H](OC(C)=O)[C@@H]1OC(C)=O", (vec![vec![28, 26, 27, 25, 24, 23, 22, 74, 21, 75, 20, 19, 18, 76, 5, 77, 81, 4, 6, 78, 82, 3, 7, 16, 79, 80, 83, 1, 8, 17, 15, 84, 85, 0, 2, 9, 10, 14, 11, 13, 12], vec![32, 33, 34, 35, 36, 37, 38, 72, 39, 71, 40, 41, 42, 66, 43, 67, 61, 56, 44, 68, 62, 57, 45, 54, 69, 70, 63, 58, 46, 55, 53, 64, 65, 59, 60, 47, 48, 52, 49, 51, 50]], vec![vec![(28, 73), (28, 29)], vec![(32, 31), (32, 73)]]), ), ( "c1ccc(Cc2ccc[n+](CCCCCc3cc(CCCCC[n+]4cccc(Cc5ccccc5)c4)c(CCCCC[n+]4cccc(Cc5ccccc5)c4)cc3CCCCC[n+]3cccc(Cc4ccccc4)c3)c2)cc1", (vec![vec![15, 14, 13, 12, 11, 10, 9, 8, 75, 7, 5, 6, 4, 3, 2, 76, 1, 77, 0], vec![17, 18, 19, 20, 21, 22, 23, 24, 35, 25, 27, 26, 28, 29, 30, 34, 31, 33, 32], vec![36, 37, 38, 39, 40, 41, 42, 43, 54, 44, 46, 45, 47, 48, 53, 49, 52, 50, 51], vec![56, 57, 58, 59, 60, 61, 62, 63, 74, 64, 66, 65, 67, 68, 69, 73, 70, 72, 71]], vec![vec![(15, 56), (15, 16)], vec![(17, 16), (17, 36)], vec![(36, 17), (36, 55)], vec![(56, 55), (56, 15)]]), ), ( "NCCCNCCCCN(CCCN)C(=O)CCCCNC(=O)c1ccc(-c2c3nc(c(-c4ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc4)c4ccc([nH]4)c(-c4ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc4)c4nc(c(-c5ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc5)c5ccc2[nH]5)C=C4)C=C3)cc1", (vec![vec![27, 26, 25, 138, 24, 139, 23, 21, 22, 20, 19, 18, 17, 16, 14, 15, 9, 10, 8, 11, 7, 12, 6, 13, 5, 4, 3, 2, 1, 0], vec![31, 32, 33, 60, 34, 59, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 50, 47, 51, 48, 52, 49, 53, 54, 55, 56, 57, 58], vec![66, 67, 95, 68, 94, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 85, 82, 86, 83, 87, 84, 88, 89, 90, 91, 92, 93], vec![99, 100, 101, 128, 102, 127, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 118, 115, 119, 116, 120, 117, 121, 122, 123, 124, 125, 126]], vec![vec![(27, 132), (27, 28)], vec![(31, 30), (31, 61)], vec![(66, 64), (66, 96)], vec![(99, 98), (99, 129)]]), ), ( "CC(C)C[C@H]1C(=O)N(C)CC(=O)N(C)[C@@H](C(C)C)C(=O)NC[C@H](NC(=O)c2ccc3ccccc3n2)C(=O)N(C)[C@@H](CC(C)C)C(=O)N(C)CC(=O)N(C)[C@@H](C(C)C)C(=O)NC[C@H](NC(=O)c2ccc3ccccc3n2)C(=O)N1C", (vec![vec![4, 3, 1, 0, 2], vec![40, 41, 42, 44, 43]], vec![vec![(4, 78), (4, 5)], vec![(40, 38), (40, 45)]]), ) ].iter().map(|td| (td.0.to_string(), td.1.clone())).collect(); for td in test_data.iter() { let (smiles, results) = td; let mol = molecule::Molecule::from_smiles(smiles); println!("{}", mol.smiles_with_index(smiles, &vec![])); let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); let mut numbering: Vec<usize> = vec![]; let mut orbits_after_partition: Vec<core::orbit_ops::Orbit> = vec![]; core::givp::run::<molecule::AtomExtendable>(&vv, &mut numbering, &mut orbits_after_partition); match create_mapping(&orbits_after_partition, &numbering, &vv) { Ok(mapping_results) => { assert_eq!(mapping_results, *results); } Err(s) => { panic!("mapping failed: {:?}", s); } } } } #[test] fn test_molecules() { type ParamType1 = String; let test_data: Vec<ParamType1> = vec![ "C1CCC2C(CC1)C1CCCCCC21", // an example for the paper ].iter().map(|td| td.to_string()).collect(); for td in test_data.iter() { let smiles = td; let mol = molecule::Molecule::from_smiles(smiles); if cfg!(debug_assertions) { println!("{}", mol.smiles_with_index(smiles, &vec![])); } let mut orbits_partitioned: Vec<core::orbit_ops::Orbit> = vec![]; let mut orbits_symmetry: Vec<core::orbit_ops::Orbit> = vec![]; let mut numbering: Vec<usize> = vec![]; molecule::canonical_numbering_and_symmetry_perception(&mol.atoms, &mut orbits_partitioned, &mut orbits_symmetry, &mut numbering); if cfg!(debug_assertions) { core::orbit_ops::orbits_sort(&mut orbits_partitioned); core::orbit_ops::orbits_sort(&mut orbits_symmetry); println!("GIVP vs CNAP\n{:?}\n{:?}", orbits_partitioned, orbits_symmetry); } assert_eq!(core::orbit_ops::orbits_equal(&orbits_partitioned, &orbits_symmetry), true); } } }
use std::io::{self, Write}; fn main() { print!("空白区切りで最小公倍数を求めたい2数を入力してください。 >> "); let _ = io::stdout().flush(); let mut input = String::new(); io::stdin().read_line(&mut input). expect("読み取りに失敗しました。"); let list: Vec<&str> = input.split_whitespace().collect(); let mut a:u32 = list[0].parse().expect("数字を入力してください。"); let mut b:u32 = list[1].parse().expect("数字を入力してください。"); let c:u32 = &a * &b; loop{ if a > b { a = a - b; } else if b > a { b = b - a; } else { break; } } let result = c / b; println!("{} と{}の最大公約数は{} ,最小公倍数は{}です。", list[0], list[1],a,result); }
use juniper::GraphQLInterface; #[derive(GraphQLInterface)] struct Character { id: String, #[graphql(name = "id")] id2: String, } fn main() {}
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::Error, fidl_fuchsia_media::AudioRenderUsage, fidl_fuchsia_settings::{ AudioInput, AudioProxy, AudioSettings, AudioStreamSettingSource, AudioStreamSettings, Volume, }, }; pub async fn command( proxy: AudioProxy, stream: Option<fidl_fuchsia_media::AudioRenderUsage>, source: Option<fidl_fuchsia_settings::AudioStreamSettingSource>, level: Option<f32>, volume_muted: Option<bool>, input_muted: Option<bool>, ) -> Result<String, Error> { let mut output = String::new(); let mut audio_settings = AudioSettings::empty(); let mut stream_settings = AudioStreamSettings::empty(); let mut volume = Volume::empty(); let mut input = AudioInput::empty(); volume.level = level; volume.muted = volume_muted; stream_settings.stream = stream; stream_settings.source = source; if volume != Volume::empty() { stream_settings.user_volume = Some(volume); } input.muted = input_muted; if stream_settings != AudioStreamSettings::empty() { audio_settings.streams = Some(vec![stream_settings]); } if input != AudioInput::empty() { audio_settings.input = Some(input); } let none_set = stream.is_none() && source.is_none() && level.is_none() && volume_muted.is_none() && input_muted.is_none(); if none_set { let settings = proxy.watch().await?; match settings { Ok(setting_value) => { let setting_string = format!("{:?}", setting_value); output.push_str(&setting_string); } Err(err) => output.push_str(&format!("{:?}", err)), } } else { let mutate_result = proxy.set(audio_settings).await?; match mutate_result { Ok(_) => { if let Some(stream_val) = stream { output.push_str(&format!( "Successfully set stream to {:?}", describe_audio_stream(stream_val), )); } if let Some(source_val) = source { output.push_str(&format!( "Successfully set source to {}", describe_audio_source(source_val) )); } if let Some(level_val) = level { output.push_str(&format!("Successfully set level to {}", level_val)); } if let Some(volume_muted_val) = volume_muted { output.push_str(&format!( "Successfully set volume_muted to {}", volume_muted_val )); } if let Some(input_muted_val) = input_muted { output .push_str(&format!("Successfully set input_muted to {}", input_muted_val)); } } Err(err) => output.push_str(&format!("{:?}", err)), } } Ok(output) } fn describe_audio_stream(stream: AudioRenderUsage) -> String { match stream { AudioRenderUsage::Background => "Background", AudioRenderUsage::Media => "Media", AudioRenderUsage::SystemAgent => "System Agent", AudioRenderUsage::Communication => "Communication", _ => "UNKNOWN AUDIO ENUM VALUE", } .to_string() } fn describe_audio_source(source: AudioStreamSettingSource) -> String { match source { AudioStreamSettingSource::Default => "Default", AudioStreamSettingSource::User => "User", AudioStreamSettingSource::System => "System", } .to_string() }
#[path = "without_options/with_monitor.rs"] pub mod with_monitor; test_stdout!(without_monitor_returns_true, "true\n");
use super::heuristics::*; use super::types::*; use crate::game::*; pub fn minimax(game: &Game, depth: usize, maximizing_player: Player, ai_config: &AIConfig) -> AlgorithmRes { if depth == ai_config.tree_depth || game.game_over() { let eval = evaluate_game_state(&game, maximizing_player, &ai_config); return AlgorithmRes { best_move: None, eval, nodes_visited: 0 } } if game.current_player() == maximizing_player { let mut max_eval = -f32::INFINITY; let mut max_eval_move = 0usize; let mut nodes_visited = 0usize; for player_move in 1..7 { let mut game_clone = game.clone(); if game_clone.should_skip_next_move() { game_clone.skip_turn() } else if game_clone.turn(player_move) == None { // invalid move continue; } let res = minimax(&game_clone, depth + 1, maximizing_player, ai_config); nodes_visited += res.nodes_visited + 1; if res.eval > max_eval { max_eval = res.eval; max_eval_move = player_move; }; } return if depth == 0 { AlgorithmRes { best_move: Some(max_eval_move), eval: max_eval, nodes_visited } } else { AlgorithmRes { best_move: None, eval: max_eval, nodes_visited } }; } let mut min_eval = f32::INFINITY; let mut nodes_visited = 0usize; for player_move in 1..7 { let mut game_clone = game.clone(); if game_clone.should_skip_next_move() { game_clone.skip_turn() } else if game_clone.turn(player_move) == None { // invalid move continue; } let res = minimax(&game_clone, depth + 1, maximizing_player, ai_config); nodes_visited += res.nodes_visited + 1; if res.eval < min_eval { min_eval = res.eval; }; } return AlgorithmRes { best_move: None, eval: min_eval, nodes_visited } }
use winapi::shared::windef::HWND; use winapi::shared::minwindef::{WPARAM, LPARAM}; use winapi::um::winuser::{LBS_MULTIPLESEL, LBS_NOSEL, WS_VISIBLE, WS_DISABLED, WS_TABSTOP}; use crate::win32::window_helper as wh; use crate::win32::base_helper::{to_utf16, from_utf16, check_hwnd}; use crate::{Font, NwgError}; use super::{ControlBase, ControlHandle}; use std::cell::{Ref, RefMut, RefCell}; use std::fmt::Display; use std::ops::Range; use std::mem; const NOT_BOUND: &'static str = "ListBox is not yet bound to a winapi object"; const BAD_HANDLE: &'static str = "INTERNAL ERROR: ListBox handle is not HWND!"; bitflags! { /** The listbox flags * NONE: No flags. Equivalent to a invisible listbox. * VISIBLE: The listbox is immediatly visible after creation * DISABLED: The listbox cannot be interacted with by the user. It also has a grayed out look. * MULTI_SELECT: It is possible for the user to select more than 1 item at a time * NO_SELECT: It is impossible for the user to select the listbox items * TAB_STOP: The control can be selected using tab navigation */ pub struct ListBoxFlags: u32 { const NONE = 0; const VISIBLE = WS_VISIBLE; const DISABLED = WS_DISABLED; const MULTI_SELECT = LBS_MULTIPLESEL; const NO_SELECT = LBS_NOSEL; const TAB_STOP = WS_TABSTOP; } } /** A list box is a control window that contains a simple list of items from which the user can choose. Requires the `list-box` feature. **Builder parameters:** * `parent`: **Required.** The listbox parent container. * `size`: The listbox size. * `position`: The listbox position. * `enabled`: If the listbox can be used by the user. It also has a grayed out look if disabled. * `focus`: The control receive focus after being created * `flags`: A combination of the ListBoxFlags values. * `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi * `font`: The font used for the listbox text * `collection`: The default collections of the listbox * `selected_index`: The default selected index in the listbox collection * `multi_selection`: The collections of indices to set as selected in a multi selection listbox **Control events:** * `OnListBoxSelect`: When the current listbox selection is changed * `OnListBoxDoubleClick`: When a listbox item is clicked twice rapidly * `MousePress(_)`: Generic mouse press events on the listbox * `OnMouseMove`: Generic mouse mouse event * `OnMouseWheel`: Generic mouse wheel event ```rust use native_windows_gui as nwg; fn build_listbox(listb: &mut nwg::ListBox<&'static str>, window: &nwg::Window, font: &nwg::Font) { nwg::ListBox::builder() .flags(nwg::ListBoxFlags::VISIBLE | nwg::ListBoxFlags::MULTI_SELECT) .collection(vec!["Hello", "World", "!!!!"]) .multi_selection(vec![0, 1, 2]) .font(Some(font)) .parent(window) .build(listb); } ``` */ #[derive(Default)] pub struct ListBox<D: Display+Default> { pub handle: ControlHandle, collection: RefCell<Vec<D>> } impl<D: Display+Default> ListBox<D> { pub fn builder<'a>() -> ListBoxBuilder<'a, D> { ListBoxBuilder { size: (100, 300), position: (0, 0), enabled: true, focus: false, flags: None, ex_flags: 0, font: None, collection: None, selected_index: None, multi_selection: Vec::new(), parent: None } } /// Add a new item to the listbox. Sort the collection if the listbox is sorted. pub fn push(&self, item: D) { use winapi::um::winuser::LB_ADDSTRING; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let display = format!("{}", item); let display_os = to_utf16(&display); unsafe { wh::send_message(handle, LB_ADDSTRING, 0, mem::transmute(display_os.as_ptr())); } self.collection.borrow_mut().push(item); } /// Insert an item in the collection and the control. /// /// SPECIAL behaviour! If index is `std::usize::MAX`, the item is added at the end of the collection. /// The method will still panic if `index > len` with every other values. pub fn insert(&self, index: usize, item: D) { use winapi::um::winuser::LB_INSERTSTRING; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let display = format!("{}", item); let display_os = to_utf16(&display); let mut col = self.collection.borrow_mut(); if index == std::usize::MAX { col.push(item); } else { col.insert(index, item); } unsafe { wh::send_message(handle, LB_INSERTSTRING, index, mem::transmute(display_os.as_ptr())); } } /// Remove the item at the selected index and returns it. /// Panic of the index is out of bounds pub fn remove(&self, index: usize) -> D { use winapi::um::winuser::LB_DELETESTRING; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_DELETESTRING, index as WPARAM, 0); let mut col_ref = self.collection.borrow_mut(); col_ref.remove(index) } /// Return the index of the currencty selected item for single value list box. /// Return `None` if no item is selected. pub fn selection(&self) -> Option<usize> { use winapi::um::winuser::{LB_GETCURSEL, LB_ERR}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let index = wh::send_message(handle, LB_GETCURSEL , 0, 0); if index == LB_ERR { None } else { Some(index as usize) } } /// Return the number of selected item in the list box /// Returns 0 for single select list box pub fn multi_selection_len(&self) -> usize { use winapi::um::winuser::{LB_GETSELCOUNT, LB_ERR}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); match wh::send_message(handle, LB_GETSELCOUNT, 0, 0) { LB_ERR => 0, value => value as usize } } /// Return a list index /// Returns an empty vector for single select list box. pub fn multi_selection(&self) -> Vec<usize> { use winapi::um::winuser::{LB_GETSELCOUNT, LB_GETSELITEMS, LB_ERR}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let select_count = match wh::send_message(handle, LB_GETSELCOUNT, 0, 0) { LB_ERR => usize::max_value(), value => value as usize }; if select_count == usize::max_value() || usize::max_value() == 0 { return Vec::new(); } let mut indices_buffer: Vec<u32> = Vec::with_capacity(select_count); unsafe { indices_buffer.set_len(select_count) }; wh::send_message( handle, LB_GETSELITEMS, select_count as WPARAM, indices_buffer.as_mut_ptr() as LPARAM ); indices_buffer.into_iter().map(|i| i as usize).collect() } /// Return the display value of the currenctly selected item for single value /// Return `None` if no item is selected. This reads the visual value. pub fn selection_string(&self) -> Option<String> { use winapi::um::winuser::{LB_GETCURSEL, LB_GETTEXTLEN, LB_GETTEXT, LB_ERR}; use winapi::shared::ntdef::WCHAR; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let index = wh::send_message(handle, LB_GETCURSEL, 0, 0); if index == LB_ERR { None } else { let index = index as usize; let length = (wh::send_message(handle, LB_GETTEXTLEN, index, 0) as usize) + 1; // +1 for the terminating null character let mut buffer: Vec<WCHAR> = Vec::with_capacity(length); unsafe { buffer.set_len(length); wh::send_message(handle, LB_GETTEXT, index, mem::transmute(buffer.as_ptr())); } Some(from_utf16(&buffer)) } } /// Set the currently selected item in the list box for single value list box. /// Does nothing if the index is out of bound /// If the value is None, remove the selected value pub fn set_selection(&self, index: Option<usize>) { use winapi::um::winuser::LB_SETCURSEL; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let index = index.unwrap_or(-1isize as usize); wh::send_message(handle, LB_SETCURSEL, index, 0); } /// Select the item as index `index` in a multi item list box pub fn multi_add_selection(&self, index: usize) { use winapi::um::winuser::LB_SETSEL; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_SETSEL, 1, index as LPARAM); } /// Unselect the item as index `index` in a multi item list box pub fn multi_remove_selection(&self, index: usize) { use winapi::um::winuser::LB_SETSEL; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_SETSEL, 0, index as LPARAM); } /// Unselect every item in the list box pub fn unselect_all(&self) { use winapi::um::winuser::LB_SETSEL; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_SETSEL, 0, -1); } /// Select every item in the list box pub fn select_all(&self) { use winapi::um::winuser::LB_SETSEL; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_SETSEL, 1, -1); } /// Select a range of items in a multi list box pub fn multi_select_range(&self, range: Range<usize>) { use winapi::um::winuser::LB_SELITEMRANGEEX; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let start = range.start as WPARAM; let end = range.end as LPARAM; wh::send_message(handle, LB_SELITEMRANGEEX, start, end); } /// Unselect a range of items in a multi list box pub fn multi_unselect_range(&self, range: Range<usize>) { use winapi::um::winuser::LB_SELITEMRANGEEX; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let start = range.start as LPARAM; let end = range.end as WPARAM; wh::send_message(handle, LB_SELITEMRANGEEX, end, start); } /// Search an item that begins by the value and select the first one found. /// The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters. /// Return the index of the selected string or None if the search was not successful pub fn set_selection_string(&self, value: &str) -> Option<usize> { use winapi::um::winuser::{LB_SELECTSTRING, LB_ERR}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let os_string = to_utf16(value); unsafe { let index = wh::send_message(handle, LB_SELECTSTRING, 0, mem::transmute(os_string.as_ptr())); if index == LB_ERR { None } else { Some(index as usize) } } } /// Check if the item at `index` is selected by the user /// Return `false` if the index is out of range. pub fn selected(&self, index: usize) -> bool { use winapi::um::winuser::LB_GETSEL; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_GETSEL, index as WPARAM, 0) > 0 } /// Update the visual of the control with the inner collection. /// This rebuild every item in the list box and can take some time on big collections. pub fn sync(&self) { use winapi::um::winuser::{LB_ADDSTRING, LB_INITSTORAGE}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); self.clear_inner(handle); let item_count = self.collection.borrow().len(); wh::send_message(handle, LB_INITSTORAGE, item_count as WPARAM, (10*item_count) as LPARAM); for item in self.collection.borrow().iter() { let display = format!("{}", item); let display_os = to_utf16(&display); unsafe { wh::send_message(handle, LB_ADDSTRING, 0, mem::transmute(display_os.as_ptr())); } } } /// Set the item collection of the list box. Return the old collection pub fn set_collection(&self, mut col: Vec<D>) -> Vec<D> { use winapi::um::winuser::LB_ADDSTRING; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); self.clear_inner(handle); for item in col.iter() { let display = format!("{}", item); let display_os = to_utf16(&display); unsafe { wh::send_message(handle, LB_ADDSTRING, 0, mem::transmute(display_os.as_ptr())); } } let mut col_ref = self.collection.borrow_mut(); mem::swap::<Vec<D>>(&mut col_ref, &mut col); col } /// Clears the control and free the underlying collection. Same as `set_collection(Vec::new())` pub fn clear(&self) { self.set_collection(Vec::new()); } /// Return the number of items in the control. NOT the inner rust collection pub fn len(&self) -> usize { use winapi::um::winuser::LB_GETCOUNT; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); wh::send_message(handle, LB_GETCOUNT, 0, 0) as usize } // // Common control functions // /// Return the font of the control pub fn font(&self) -> Option<Font> { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let font_handle = wh::get_window_font(handle); if font_handle.is_null() { None } else { Some(Font { handle: font_handle }) } } /// Set the font of the control pub fn set_font(&self, font: Option<&Font>) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); } } /// Return true if the control currently has the keyboard focus pub fn focus(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_focus(handle) } } /// Set the keyboard focus on the button. pub fn set_focus(&self) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_focus(handle); } } /// Return true if the control user can interact with the control, return false otherwise pub fn enabled(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_enabled(handle) } } /// Enable or disable the control pub fn set_enabled(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_enabled(handle, v) } } /// Return true if the control is visible to the user. Will return true even if the /// control is outside of the parent client view (ex: at the position (10000, 10000)) pub fn visible(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_visibility(handle) } } /// Show or hide the control to the user pub fn set_visible(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_visibility(handle, v) } } /// Return the size of the button in the parent window pub fn size(&self) -> (u32, u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_size(handle) } } /// Set the size of the button in the parent window pub fn set_size(&self, x: u32, y: u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_size(handle, x, y, false) } } /// Return the position of the button in the parent window pub fn position(&self) -> (i32, i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_position(handle) } } /// Set the position of the button in the parent window pub fn set_position(&self, x: i32, y: i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_position(handle, x, y) } } /// Get read-only access to the inner collection of the list box /// This call refcell.borrow under the hood. Be sure to drop the value before /// calling other list box methods pub fn collection(&self) -> Ref<Vec<D>> { self.collection.borrow() } /// Get mutable access to the inner collection of the list box. Does not update the visual /// control. Call `sync` to update the view. This call refcell.borrow_mut under the hood. /// Be sure to drop the value before calling other list box methods pub fn collection_mut(&self) -> RefMut<Vec<D>> { self.collection.borrow_mut() } /// Winapi class name used during control creation pub fn class_name(&self) -> &'static str { "ListBox" } /// Winapi base flags used during window creation pub fn flags(&self) -> u32 { WS_VISIBLE | WS_TABSTOP } /// Winapi flags required by the control pub fn forced_flags(&self) -> u32 { use winapi::um::winuser::{LBS_HASSTRINGS, WS_BORDER, WS_VSCROLL, LBS_NOTIFY, WS_CHILD}; LBS_HASSTRINGS | LBS_NOTIFY | WS_BORDER | WS_CHILD | WS_VSCROLL } /// Remove all value displayed in the control without touching the rust collection fn clear_inner(&self, handle: HWND) { use winapi::um::winuser::LB_RESETCONTENT; wh::send_message(handle, LB_RESETCONTENT, 0, 0); } } impl<D: Display+Default> Drop for ListBox<D> { fn drop(&mut self) { self.handle.destroy(); } } pub struct ListBoxBuilder<'a, D: Display+Default> { size: (i32, i32), position: (i32, i32), enabled: bool, focus: bool, flags: Option<ListBoxFlags>, ex_flags: u32, font: Option<&'a Font>, collection: Option<Vec<D>>, selected_index: Option<usize>, multi_selection: Vec<usize>, parent: Option<ControlHandle> } impl<'a, D: Display+Default> ListBoxBuilder<'a, D> { pub fn flags(mut self, flags: ListBoxFlags) -> ListBoxBuilder<'a, D> { self.flags = Some(flags); self } pub fn ex_flags(mut self, flags: u32) -> ListBoxBuilder<'a, D> { self.ex_flags = flags; self } pub fn size(mut self, size: (i32, i32)) -> ListBoxBuilder<'a, D> { self.size = size; self } pub fn position(mut self, pos: (i32, i32)) -> ListBoxBuilder<'a, D> { self.position = pos; self } pub fn font(mut self, font: Option<&'a Font>) -> ListBoxBuilder<'a, D> { self.font = font; self } pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> ListBoxBuilder<'a, D> { self.parent = Some(p.into()); self } pub fn collection(mut self, collection: Vec<D>) -> ListBoxBuilder<'a, D> { self.collection = Some(collection); self } pub fn selected_index(mut self, index: Option<usize>) -> ListBoxBuilder<'a, D> { self.selected_index = index; self } pub fn multi_selection(mut self, select: Vec<usize>) -> ListBoxBuilder<'a, D> { self.multi_selection = select; self } pub fn enabled(mut self, enabled: bool) -> ListBoxBuilder<'a, D> { self.enabled = enabled; self } pub fn focus(mut self, focus: bool) -> ListBoxBuilder<'a, D> { self.focus = focus; self } pub fn build(self, out: &mut ListBox<D>) -> Result<(), NwgError> { let flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags()); let parent = match self.parent { Some(p) => Ok(p), None => Err(NwgError::no_parent("ListBox")) }?; *out = Default::default(); out.handle = ControlBase::build_hwnd() .class_name(out.class_name()) .forced_flags(out.forced_flags()) .flags(flags) .ex_flags(self.ex_flags) .size(self.size) .position(self.position) .parent(Some(parent)) .build()?; if self.font.is_some() { out.set_font(self.font); } else { out.set_font(Font::global_default().as_ref()); } if let Some(col) = self.collection { out.set_collection(col); } if flags & LBS_MULTIPLESEL == LBS_MULTIPLESEL { for i in self.multi_selection { out.multi_add_selection(i); } } else { out.set_selection(self.selected_index); } if self.focus { out.set_focus(); } if !self.enabled { out.set_enabled(self.enabled); } Ok(()) } } impl<D: Display+Default> PartialEq for ListBox<D> { fn eq(&self, other: &Self) -> bool { self.handle == other.handle } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Comparator control/status register"] pub comp_c1csr: COMP_C1CSR, #[doc = "0x04 - Comparator control/status register"] pub comp_c2csr: COMP_C2CSR, #[doc = "0x08 - Comparator control/status register"] pub comp_c3csr: COMP_C3CSR, #[doc = "0x0c - Comparator control/status register"] pub comp_c4csr: COMP_C4CSR, } #[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c1csr](comp_c1csr) module"] pub type COMP_C1CSR = crate::Reg<u32, _COMP_C1CSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _COMP_C1CSR; #[doc = "`read()` method returns [comp_c1csr::R](comp_c1csr::R) reader structure"] impl crate::Readable for COMP_C1CSR {} #[doc = "`write(|w| ..)` method takes [comp_c1csr::W](comp_c1csr::W) writer structure"] impl crate::Writable for COMP_C1CSR {} #[doc = "Comparator control/status register"] pub mod comp_c1csr; #[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c2csr](comp_c2csr) module"] pub type COMP_C2CSR = crate::Reg<u32, _COMP_C2CSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _COMP_C2CSR; #[doc = "`read()` method returns [comp_c2csr::R](comp_c2csr::R) reader structure"] impl crate::Readable for COMP_C2CSR {} #[doc = "`write(|w| ..)` method takes [comp_c2csr::W](comp_c2csr::W) writer structure"] impl crate::Writable for COMP_C2CSR {} #[doc = "Comparator control/status register"] pub mod comp_c2csr; #[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c3csr](comp_c3csr) module"] pub type COMP_C3CSR = crate::Reg<u32, _COMP_C3CSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _COMP_C3CSR; #[doc = "`read()` method returns [comp_c3csr::R](comp_c3csr::R) reader structure"] impl crate::Readable for COMP_C3CSR {} #[doc = "`write(|w| ..)` method takes [comp_c3csr::W](comp_c3csr::W) writer structure"] impl crate::Writable for COMP_C3CSR {} #[doc = "Comparator control/status register"] pub mod comp_c3csr; #[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c4csr](comp_c4csr) module"] pub type COMP_C4CSR = crate::Reg<u32, _COMP_C4CSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _COMP_C4CSR; #[doc = "`read()` method returns [comp_c4csr::R](comp_c4csr::R) reader structure"] impl crate::Readable for COMP_C4CSR {} #[doc = "`write(|w| ..)` method takes [comp_c4csr::W](comp_c4csr::W) writer structure"] impl crate::Writable for COMP_C4CSR {} #[doc = "Comparator control/status register"] pub mod comp_c4csr;
//! A universal means of representing location in a Falcon program //! //! We have two basic types of locations in Falcon: //! //! `RefProgramLocation`, and its companion `RefFunctionLocation`. These are program locations, //! "Applied," to a program. //! //! `ProgramLocation`, and its companion, `FunctionLocation`. These are program locations //! independent of a program. //! //! We will normally deal with `RefProgramLocation`. However, as `RefProgramLocation` has a //! lifetime dependent on a specific `Program`, it can sometimes to be difficult to use. //! Therefor, we have `ProgramLocation`, which is an Owned type in its own right with no //! references. use crate::il::*; use crate::Error; use serde::{Deserialize, Serialize}; use std::fmt; /// A location applied to a `Program`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct RefProgramLocation<'p> { function: &'p Function, function_location: RefFunctionLocation<'p>, } impl<'p> RefProgramLocation<'p> { /// Create a new `RefProgramLocation` in the given `Program`. pub fn new( function: &'p Function, function_location: RefFunctionLocation<'p>, ) -> RefProgramLocation<'p> { RefProgramLocation { function, function_location, } } /// Create a new `RefProgramLocation` in the given `Program` by finding the /// first `Instruction` with the given address. pub fn from_address(program: &'p Program, address: u64) -> Option<RefProgramLocation<'p>> { // We do this in passes // Start by finding the function with the closest address to the target // address let mut function = None; for f in program.functions() { if f.address() > address { continue; } if function.is_none() { function = Some(f); continue; } let ff = function.unwrap(); if f.address() > ff.address() { function = Some(f); } } if let Some(function) = function { for block in function.blocks() { for instruction in block.instructions() { if instruction.address().map(|a| a == address).unwrap_or(false) { return Some(RefProgramLocation::new( function, RefFunctionLocation::Instruction(block, instruction), )); } } } } // Exhaustive search for function in program.functions() { for block in function.blocks() { for instruction in block.instructions() { if let Some(iaddress) = instruction.address() { if iaddress == address { return Some(RefProgramLocation::new( function, RefFunctionLocation::Instruction(block, instruction), )); } } } } } None } /// Create a new `RefProgramLocation` in the given `Program` by finding the /// first `Instruction` in the given function. pub fn from_function(function: &Function) -> Option<Result<RefProgramLocation, Error>> { function.control_flow_graph().entry().map(|entry| { function.block(entry).map(|block| { RefProgramLocation::new( function, block .instructions() .first() .map(|instruction| RefFunctionLocation::Instruction(block, instruction)) .unwrap_or(RefFunctionLocation::EmptyBlock(block)), ) }) }) } /// Get the function for this `RefProgramLocation`. pub fn function(&self) -> &Function { self.function } /// Get the `RefFunctionLocation` for this `RefProgramLocation` pub fn function_location(&self) -> &RefFunctionLocation { &self.function_location } /// If this `RefProgramLocation` references a `Block`, get that `Block`. pub fn block(&self) -> Option<&Block> { self.function_location.block() } /// If this `RefProgramLocation` references an `Instruction`, get that /// `Instruction`. pub fn instruction(&self) -> Option<&Instruction> { self.function_location.instruction() } /// If this `RefProgramLocation` references an `Edge`, get that `Edge` pub fn edge(&self) -> Option<&Edge> { self.function_location.edge() } /// If this `RefProgramLocation` is referencing an `Instruction` which has /// an address set, return that address. pub fn address(&self) -> Option<u64> { if let Some(instruction) = self.function_location.instruction() { return instruction.address(); } None } /// Apply this `RefProgramLocation` to another `Program`. /// /// This works by locating the location in the other `Program` based on /// `Function`, `Block`, and `Instruction` indices. pub fn migrate<'m>(&self, program: &'m Program) -> Result<RefProgramLocation<'m>, Error> { let function = program .function(self.function().index().unwrap()) .ok_or_else(|| { Error::FalconInternal(format!( "Could not find function {}", self.function.index().unwrap() )) })?; let function_location = match self.function_location { RefFunctionLocation::Instruction(block, instruction) => { let block = function.block(block.index())?; let instruction = block.instruction(instruction.index()).ok_or_else(|| { Error::FalconInternal(format!( "Could not find function {}", self.function.index().unwrap() )) })?; RefFunctionLocation::Instruction(block, instruction) } RefFunctionLocation::Edge(edge) => { let edge = function.edge(edge.head(), edge.tail())?; RefFunctionLocation::Edge(edge) } RefFunctionLocation::EmptyBlock(block) => { let block = function.block(block.index())?; RefFunctionLocation::EmptyBlock(block) } }; Ok(RefProgramLocation { function, function_location, }) } fn instruction_backward( &self, block: &'p Block, instruction: &Instruction, ) -> Result<Vec<RefProgramLocation<'p>>, Error> { let instructions = block.instructions(); for i in (0..instructions.len()).rev() { if instructions[i].index() == instruction.index() { if i > 0 { let instruction = &instructions[i - 1]; return Ok(vec![RefProgramLocation::new( self.function, RefFunctionLocation::Instruction(block, instruction), )]); } let edges = self.function.control_flow_graph().edges_in(block.index())?; let mut locations = Vec::new(); for edge in edges { locations.push(RefProgramLocation::new( self.function, RefFunctionLocation::Edge(edge), )); } return Ok(locations); } } Err(format!( "Could not find instruction {} in block {} in function {:?}", instruction.index(), block.index(), self.function.index() ) .into()) } fn edge_backward(&self, edge: &'p Edge) -> Result<Vec<RefProgramLocation<'p>>, Error> { let block = self.function.block(edge.head())?; let instructions = block.instructions(); if instructions.is_empty() { Ok(vec![RefProgramLocation::new( self.function, RefFunctionLocation::EmptyBlock(block), )]) } else { Ok(vec![RefProgramLocation::new( self.function, RefFunctionLocation::Instruction(block, instructions.last().unwrap()), )]) } } fn empty_block_backward(&self, block: &'p Block) -> Result<Vec<RefProgramLocation<'p>>, Error> { let edges = self.function.control_flow_graph().edges_in(block.index())?; let mut locations = Vec::new(); for edge in edges { locations.push(RefProgramLocation::new( self.function, RefFunctionLocation::Edge(edge), )); } Ok(locations) } fn instruction_forward( &self, block: &'p Block, instruction: &Instruction, ) -> Result<Vec<RefProgramLocation<'p>>, Error> { let instructions = block.instructions(); for i in 0..instructions.len() { // We found the instruction. if instructions[i].index() == instruction.index() { // Is there another instruction in this block? if i + 1 < instructions.len() { // Return the next instruction let instruction = &instructions[i + 1]; return Ok(vec![RefProgramLocation::new( self.function, RefFunctionLocation::Instruction(block, instruction), )]); } // No next instruction, return edges out of the block let edges = self .function .control_flow_graph() .edges_out(block.index())?; let mut locations = Vec::new(); for edge in edges { locations.push(RefProgramLocation::new( self.function, RefFunctionLocation::Edge(edge), )); } return Ok(locations); } } Err(format!( "Could not find instruction {} in block {} in function {:?}", instruction.index(), block.index(), self.function.index() ) .into()) } fn edge_forward(&self, edge: &'p Edge) -> Result<Vec<RefProgramLocation<'p>>, Error> { let block = self.function.block(edge.tail())?; let instructions = block.instructions(); if instructions.is_empty() { Ok(vec![RefProgramLocation::new( self.function, RefFunctionLocation::EmptyBlock(block), )]) } else { Ok(vec![RefProgramLocation::new( self.function, RefFunctionLocation::Instruction(block, &instructions[0]), )]) } } fn empty_block_forward(&self, block: &'p Block) -> Result<Vec<RefProgramLocation<'p>>, Error> { let edges = self .function .control_flow_graph() .edges_out(block.index())?; let mut locations = Vec::new(); for edge in edges { locations.push(RefProgramLocation::new( self.function, RefFunctionLocation::Edge(edge), )); } Ok(locations) } /// Advance the `RefProgramLocation` forward. /// /// This does _not_ follow targets of `Operation::Brc`. pub fn forward(&self) -> Result<Vec<RefProgramLocation<'p>>, Error> { match self.function_location { RefFunctionLocation::Instruction(block, instruction) => { self.instruction_forward(block, instruction) } RefFunctionLocation::Edge(edge) => self.edge_forward(edge), RefFunctionLocation::EmptyBlock(block) => self.empty_block_forward(block), } } /// Advance the `RefProgramLocation` backward. /// /// This does _not_ follow targets of `Operation::Brc`. pub fn backward(&self) -> Result<Vec<RefProgramLocation<'p>>, Error> { match self.function_location { RefFunctionLocation::Instruction(block, instruction) => { self.instruction_backward(block, instruction) } RefFunctionLocation::Edge(edge) => self.edge_backward(edge), RefFunctionLocation::EmptyBlock(block) => self.empty_block_backward(block), } } } impl<'f> fmt::Display for RefProgramLocation<'f> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.function.index() { Some(index) => write!(f, "0x{:x}:{}", index, self.function_location), None => write!(f, "{}", self.function_location), } } } /// A location applied to a `Function`. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum RefFunctionLocation<'f> { Instruction(&'f Block, &'f Instruction), Edge(&'f Edge), EmptyBlock(&'f Block), } impl<'f> RefFunctionLocation<'f> { /// If this `RefFunctionLocation` references a `Block`, get that `Block`. pub fn block(&self) -> Option<&Block> { match *self { RefFunctionLocation::Instruction(block, _) => Some(block), RefFunctionLocation::EmptyBlock(block) => Some(block), _ => None, } } /// If this `RefFunctionLocation` references an `Instruction`, get that /// `Instruction`. pub fn instruction(&self) -> Option<&Instruction> { match *self { RefFunctionLocation::Instruction(_, instruction) => Some(instruction), _ => None, } } /// If this `RefFunctionLocation` references an `Edge`, get that `Edge`. pub fn edge(&self) -> Option<&Edge> { match *self { RefFunctionLocation::Edge(edge) => Some(edge), _ => None, } } /// Quickly turn this into a `RefProgramLocation` pub fn program_location(self, function: &'f Function) -> RefProgramLocation<'f> { RefProgramLocation::new(function, self) } } impl<'f> fmt::Display for RefFunctionLocation<'f> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RefFunctionLocation::Instruction(block, ref instruction) => { write!(f, "0x{:x}:{}", block.index(), instruction) } RefFunctionLocation::Edge(ref edge) => edge.fmt(f), RefFunctionLocation::EmptyBlock(ref empty_block) => empty_block.fmt(f), } } } /// A location independent of any specific instance of `Program`. #[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] pub struct ProgramLocation { function_index: Option<usize>, function_location: FunctionLocation, } impl ProgramLocation { /// Create a new `ProgramLocation` from a function index and `FunctionLocation` pub fn new( function_index: Option<usize>, function_location: FunctionLocation, ) -> ProgramLocation { ProgramLocation { function_index, function_location, } } /// "Apply" this `ProgramLocation` to a `Program`, returning a /// `RefProgramLocation`. pub fn apply<'p>(&self, program: &'p Program) -> Result<RefProgramLocation<'p>, Error> { if self.function_index.is_none() { return Err(Error::ProgramLocationApplication); } let function_index = self .function_index .ok_or(Error::ProgramLocationApplication)?; let function = program .function(function_index) .ok_or(Error::ProgramLocationApplication)?; let function_location = self.function_location.apply(function)?; Ok(RefProgramLocation::new(function, function_location)) } /// Get the `FunctionLocation` for this `ProgramLocation` pub fn function_location(&self) -> &FunctionLocation { &self.function_location } /// If this `ProgramLocation` has a valid `Block` target, return the index /// of that `Block`. pub fn block_index(&self) -> Option<usize> { self.function_location.block_index() } /// If this `ProgramLocation` has a valid `Instruction` target, return the /// index of that `Instruction` pub fn instruction_index(&self) -> Option<usize> { self.function_location.instruction_index() } } impl<'p> From<RefProgramLocation<'p>> for ProgramLocation { fn from(program_location: RefProgramLocation) -> ProgramLocation { ProgramLocation { function_index: program_location.function().index(), function_location: program_location.function_location.into(), } } } impl fmt::Display for ProgramLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.function_index { Some(function_index) => write!(f, "0x{:x}:{}", function_index, self.function_location), None => write!(f, "{}", self.function_location), } } } /// A location indepdent of any specific instance of `Function`. #[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] pub enum FunctionLocation { Instruction(usize, usize), Edge(usize, usize), EmptyBlock(usize), } impl FunctionLocation { /// "Apply" this `FunctionLocation` to a `Function`, returning a /// `RefFunctionLocation`. pub fn apply<'f>(&self, function: &'f Function) -> Result<RefFunctionLocation<'f>, Error> { match *self { FunctionLocation::Instruction(block_index, instruction_index) => { let block = function .block(block_index) .map_err(|_| Error::FunctionLocationApplication)?; let instruction = block .instruction(instruction_index) .ok_or(Error::FunctionLocationApplication)?; Ok(RefFunctionLocation::Instruction(block, instruction)) } FunctionLocation::Edge(head, tail) => { let edge = function .edge(head, tail) .map_err(|_| Error::FunctionLocationApplication)?; Ok(RefFunctionLocation::Edge(edge)) } FunctionLocation::EmptyBlock(block_index) => { let block = function .block(block_index) .map_err(|_| Error::FunctionLocationApplication)?; Ok(RefFunctionLocation::EmptyBlock(block)) } } } /// If this `FunctionLocation` has a valid `Block` target, return the index /// of that `Instruction`. pub fn block_index(&self) -> Option<usize> { match *self { FunctionLocation::Instruction(block_index, _) => Some(block_index), FunctionLocation::EmptyBlock(block_index) => Some(block_index), _ => None, } } /// If this `FunctionLocation` has a valid `Instruction` target, return the /// index of that `Instruction`. pub fn instruction_index(&self) -> Option<usize> { match *self { FunctionLocation::Instruction(_, instruction_index) => Some(instruction_index), _ => None, } } } impl<'f> From<RefFunctionLocation<'f>> for FunctionLocation { fn from(function_location: RefFunctionLocation) -> FunctionLocation { match function_location { RefFunctionLocation::Instruction(block, instruction) => { FunctionLocation::Instruction(block.index(), instruction.index()) } RefFunctionLocation::Edge(edge) => FunctionLocation::Edge(edge.head(), edge.tail()), RefFunctionLocation::EmptyBlock(block) => FunctionLocation::EmptyBlock(block.index()), } } } impl fmt::Display for FunctionLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { FunctionLocation::Instruction(block_index, instruction_index) => { write!(f, "0x{:X}:{:02X}", block_index, instruction_index) } FunctionLocation::Edge(head_index, tail_index) => { write!(f, "(0x{:X}->0x{:X})", head_index, tail_index) } FunctionLocation::EmptyBlock(block_index) => write!(f, "0x{:X}", block_index), } } }
#![allow(non_snake_case)] #![cfg(test)] use problem1::{distinct, filter, sum}; // use problem2::mat_mult; // use problem3::sieve; // use problem4::{hanoi, Peg}; // // Problem 1 // // Part 1 #[test] fn Can_compute_sum_on_empty_slice() { let array = []; let default = 10; let res = sum(&array, default); assert_eq!(res, default); } #[test] fn Can_compute_sum_on_one_element_slice() { let array = [1]; let default = 10; let res = sum(&array, default); assert_eq!(res, 11); } #[test] fn Can_compute_sum() { let array = [1, 2, 3, 4, 5]; let res = sum(&array, 0); assert_eq!(res, 15); } #[test] fn Can_distinct_items() { let vs = vec![1, 2, 2, 3, 4, 1]; let actual = distinct(&vs); assert_eq!(actual, vec![1, 2, 3, 4]); } #[test] fn test_filter_small() { fn even_predicate(x: i32) -> bool { (x % 2) == 0 } let vs = vec![1, 2, 3, 4, 5]; let actual = filter(&vs, &even_predicate); let expected = vec![2, 4]; assert_eq!(actual, expected); } // // // // Problem 2 // // // #[test] // fn test_mat_mult_identity() { // let mut mat1 = vec![vec![0.;3]; 3]; // for i in 0..mat1.len() { // mat1[i][i] = 1.; // } // let mat2 = vec![vec![5.;3]; 3]; // let result = mat_mult(&mat1, &mat2); // for i in 0..result.len() { // for j in 0..result[i].len() { // assert_eq!(result[i][j], mat2[i][j]); // } // } // } // // // // Problem 3 // // // #[test] // fn test_sieve_basic() { // assert_eq!(vec![2,3,5,7,11], sieve(12)); // } // // // // Problem 4 // // // #[test] // fn test_hanoi_1_disks() { // let result = hanoi(1, Peg::A, Peg::B, Peg::C); // assert_eq!(vec![(Peg::A, Peg::C)], result); // assert_eq!(1, result.len()); // }
use sea_orm::prelude::*; use serde::{Deserialize, Serialize}; #[derive(EnumIter, DeriveActiveEnum)] #[sea_orm(rs_type = "String", db_type = "Text")] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq)] pub enum Feed { #[sea_orm(string_value = "Category")] Category, #[sea_orm(string_value = "Tag")] Tag, }
use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; #[derive(Debug)] struct Rule { min: usize, max: usize, check_letter: char } fn main() { //test(); if let Ok(lines) = read_lines("./input") { let mut count = 0; for line in lines { if let Ok(rule_password) = line { let (rule, password) = parse_rule_password(rule_password.trim()); if is_valid2(&rule, password) { count += 1; } } } println!("{}", count); } } fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } fn parse_rule_password(rule_password_pair: &str) -> (Rule, &str) { let splits = rule_password_pair.split(':').collect::<Vec<&str>>(); let rule_description = splits[0].trim(); let check_letter = rule_description.chars().last().expect("Could find not check letter"); let min_max = rule_description.split('-').collect::<Vec<&str>>(); let min: usize = min_max[0].trim().parse().expect("Min has to be a number"); let max: usize = min_max[1].split(' ').collect::<Vec<&str>>()[0].parse().expect("Max has to be a number"); let password = splits[1].trim(); let rule = Rule { min, max, check_letter }; (rule, password) } fn is_valid(rule: &Rule, password: &str) -> bool { let count = password.matches(rule.check_letter).collect::<Vec<&str>>().len(); count <= rule.max && count >= rule.min } fn is_valid2(rule: &Rule, password: &str) -> bool { // rules are not 0-indexed let min = rule.min - 1; let max = rule.max - 1; let chars = password.chars().collect::<Vec<char>>(); if chars[min] == rule.check_letter && chars[max] == rule.check_letter { return false; } chars[min] == rule.check_letter || chars[max] == rule.check_letter } fn test() { let data = vec!("1-3 a: abcde","1-3 b: cdefg","2-9 c: ccccccccc"); let mut count = 0; for rule_password in data { let (rule, password) = parse_rule_password(rule_password); let is_valid = is_valid2(&rule, password); println!("{}", is_valid); if is_valid { count += 1; } println!("{:?} {} is valid: {}, count {}", rule, password, is_valid, count); } }
#[doc = "Writer for register ICACHE_FCR"] pub type W = crate::W<u32, super::ICACHE_FCR>; #[doc = "Register ICACHE_FCR `reset()`'s with value 0"] impl crate::ResetValue for super::ICACHE_FCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CBSYENDF`"] pub struct CBSYENDF_W<'a> { w: &'a mut W, } impl<'a> CBSYENDF_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 = "Write proxy for field `CERRF`"] pub struct CERRF_W<'a> { w: &'a mut W, } impl<'a> CERRF_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 } } impl W { #[doc = "Bit 1 - CBSYENDF"] #[inline(always)] pub fn cbsyendf(&mut self) -> CBSYENDF_W { CBSYENDF_W { w: self } } #[doc = "Bit 2 - CERRF"] #[inline(always)] pub fn cerrf(&mut self) -> CERRF_W { CERRF_W { w: self } } }
mod retina_map; use self::retina_map::generate_retina_map; use gfx; use gfx::traits::FactoryExt; use gfx::Factory; use gfx_device_gl::CommandBuffer; use gfx_device_gl::Resources; use crate::devices::*; use crate::pipeline::*; gfx_defines! { pipeline pipe { u_stereo: gfx::Global<i32> = "u_stereo", u_resolution: gfx::Global<[f32; 2]> = "u_resolution", u_gaze: gfx::Global<[f32; 2]> = "u_gaze", s_source: gfx::TextureSampler<[f32; 4]> = "s_color", s_retina: gfx::TextureSampler<[f32; 4]> = "s_retina", rt_color: gfx::RenderTarget<ColorFormat> = "rt_color", } } pub struct Retina { pso: gfx::PipelineState<Resources, pipe::Meta>, pso_data: pipe::Data<Resources>, } impl Retina { pub fn new(factory: &mut gfx_device_gl::Factory) -> Retina { let pso = factory .create_pipeline_simple( &include_glsl!("../shader.vert"), &include_glsl!("shader.frag"), pipe::new(), ) .unwrap(); let rgba_white = vec![255; 4].into_boxed_slice(); let (_, mask_view) = load_texture_from_bytes(factory, rgba_white, 1, 1).unwrap(); let sampler = factory.create_sampler_linear(); let (_, src, dst) = factory.create_render_target(1, 1).unwrap(); Retina { pso, pso_data: pipe::Data { u_stereo: 0, u_resolution: [1.0, 1.0], u_gaze: [0.0, 0.0], s_source: (src, sampler.clone()), s_retina: (mask_view, sampler), rt_color: dst, }, } } } impl Pass for Retina { fn update_io( &mut self, target: &DeviceTarget, _target_size: (u32, u32), source: &DeviceSource, source_sampler: &gfx::handle::Sampler<Resources>, source_size: (u32, u32), stereo: bool, ) { self.pso_data.u_stereo = if stereo { 1 } else { 0 }; self.pso_data.rt_color = target.clone(); match source { DeviceSource::Rgb { rgba8 } => { self.pso_data.s_source = (rgba8.clone(), source_sampler.clone()); } DeviceSource::RgbDepth { rgba8, d: _ } => { self.pso_data.s_source = (rgba8.clone(), source_sampler.clone()); } DeviceSource::Yuv { .. } => panic!("Unsupported source"), } self.pso_data.u_resolution = [source_size.0 as f32, source_size.1 as f32]; } fn update_params(&mut self, factory: &mut gfx_device_gl::Factory, params: &ValueMap) { // update retina map self.pso_data.s_retina = if let Some(Value::Image(retina_map_path)) = params.get("retina_map_path") { println!("[retina] using map {:?}", retina_map_path); let (_, retinamap_view) = load_texture(factory, load(retina_map_path)).unwrap(); let sampler = self.pso_data.s_retina.clone().1; (retinamap_view, sampler) } else { println!("[retina] generating map"); let retina_resolution = ( self.pso_data.u_resolution[0] as u32, self.pso_data.u_resolution[1] as u32, ); let retina_map = generate_retina_map(retina_resolution, &params); let (_, retinamap_view) = load_texture_from_bytes( factory, retina_map, retina_resolution.0, retina_resolution.1, ) .unwrap(); (retinamap_view, self.pso_data.s_retina.clone().1) }; } fn render(&mut self, encoder: &mut gfx::Encoder<Resources, CommandBuffer>, gaze: &DeviceGaze) { self.pso_data.u_gaze = [gaze.x, gaze.y]; encoder.draw(&gfx::Slice::from_vertex_count(6), &self.pso, &self.pso_data); } }
use crate::structs::message_types::{parse_dhcpv6_message_type, DHCPv6MessageType}; use crate::structs::options::{parse_dhcpv6_options, DHCPv6Option}; use nom::number::complete::{be_u24, be_u8}; use nom::sequence::tuple; use nom::IResult; use std::net::Ipv6Addr; use crate::utils::parse_ipv6_address; #[derive(Debug, Clone, PartialEq)] pub enum DHCPv6Header<'a> { ClientServer { message_type: DHCPv6MessageType, transaction_id: u32, options: Vec<DHCPv6Option<'a>>, }, RelayAgentServer { message_type: DHCPv6MessageType, hop_count: u8, link_address: Ipv6Addr, peer_address: Ipv6Addr, options: Vec<DHCPv6Option<'a>>, }, } fn parse_dhcpv6_header_client_server( input: &[u8], message_type: DHCPv6MessageType, ) -> IResult<&[u8], DHCPv6Header> { let (rest, (transaction_id, options)) = tuple((be_u24, parse_dhcpv6_options))(input)?; Ok(( rest, DHCPv6Header::ClientServer { message_type, transaction_id, options, }, )) } fn parse_dhcpv6_header_relay_agent_server( input: &[u8], message_type: DHCPv6MessageType, ) -> IResult<&[u8], DHCPv6Header> { let (rest, (hop_count, link_address, peer_address, options)) = tuple(( be_u8, parse_ipv6_address, parse_ipv6_address, parse_dhcpv6_options, ))(input)?; Ok(( rest, DHCPv6Header::RelayAgentServer { message_type, hop_count, link_address, peer_address, options, }, )) } pub fn parse_dhcpv6_header(input: &[u8]) -> IResult<&[u8], DHCPv6Header> { let (rest, message_type) = parse_dhcpv6_message_type(input)?; match message_type { DHCPv6MessageType::RelayForw | DHCPv6MessageType::RelayRepl => { parse_dhcpv6_header_relay_agent_server(rest, message_type) } _ => parse_dhcpv6_header_client_server(rest, message_type), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_valid_dhcpv6_header() { let input = b"\x01\x00\x00\x01\x00\x01\x00\x04toto"; assert_eq!( parse_dhcpv6_header(&input[..]), Ok(( &b""[..], DHCPv6Header::ClientServer { message_type: DHCPv6MessageType::Solicit, transaction_id: 1, options: vec![DHCPv6Option::CliendID { duid: &b"toto"[..] }] } )) ); } }
use std::path::PathBuf; use std::str::FromStr; use clap::ArgMatches; use crate::config::options::{invalid_value, required_option_missing}; use crate::config::{OptionInfo, ParseOption}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum LdImpl { Lld, } impl FromStr for LdImpl { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "lld" => Ok(Self::Lld), _ => Err(()), } } } impl ParseOption for LdImpl { fn parse_option<'a>(info: &OptionInfo, matches: &ArgMatches<'a>) -> clap::Result<Self> { matches.value_of(info.name).map_or_else( || Err(required_option_missing(info)), |s| { Self::from_str(s) .map_err(|_| invalid_value(info, "expected valid gcc-ld implementation")) }, ) } } /// The linker plugin to use #[derive(Debug, Clone, PartialEq, Hash)] pub enum LinkerPluginLto { Plugin(PathBuf), Auto, Disabled, } impl Default for LinkerPluginLto { fn default() -> Self { Self::Auto } } impl LinkerPluginLto { pub fn enabled(&self) -> bool { match *self { Self::Plugin(_) | Self::Auto => true, Self::Disabled => false, } } } impl From<&str> for LinkerPluginLto { fn from(s: &str) -> Self { match s { "" => Self::default(), "false" | "disabled" => Self::Disabled, path => Self::Plugin(PathBuf::from(path)), } } } impl ParseOption for LinkerPluginLto { fn parse_option<'a>(info: &OptionInfo, matches: &ArgMatches<'a>) -> clap::Result<Self> { Ok(matches .value_of(info.name) .map(Self::from) .unwrap_or(Self::Auto)) } } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum WasiExecModel { Command, Reactor, } impl FromStr for WasiExecModel { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "command" => Ok(Self::Command), "reactor" => Ok(Self::Reactor), _ => Err(()), } } } impl ParseOption for WasiExecModel { fn parse_option<'a>(info: &OptionInfo, matches: &ArgMatches<'a>) -> clap::Result<Self> { matches.value_of(info.name).map_or_else( || Err(required_option_missing(info)), |s| Self::from_str(s).map_err(|_| invalid_value(info, "invalid wasi exec model")), ) } }
use std::ops::{Deref, DerefMut}; pub fn copy_memory(input: &[u8], out: &mut [u8]) -> usize { for count in 0..input.len() {out[count] = input[count];} input.len() } /// Toggle is similar to Option, except that even in the Off/"None" case, there is still /// an owned allocated inner object. This is useful for holding onto pre-allocated objects /// that can be toggled as enabled. pub struct Toggle<T> { inner: T, on: bool, } impl<T> Toggle<T> { pub fn on(inner: T) -> Self { Self { inner: inner, on: true } } pub fn off(inner: T) -> Self { Self { inner: inner, on: false } } pub fn into_inner(self) -> T { self.inner } pub fn enable(&mut self) { self.on = true; } pub fn is_on(&self) -> bool { self.on } pub fn as_option_ref(&self) -> Option<&T> { if self.on { Some(&self.inner) } else { None } } } impl<T> Deref for Toggle<T> { type Target = T; fn deref(&self) -> &T { &self.inner } } impl<T> DerefMut for Toggle<T> { fn deref_mut(&mut self) -> &mut T { &mut self.inner } } #[cfg(not(feature = "nightly"))] pub trait TryInto<T>: Sized { type Error; fn try_into(self) -> Result<T, Self::Error>; } #[cfg(not(feature = "nightly"))] pub trait TryFrom<T>: Sized { type Error; fn try_from(value: T) -> Result<Self, Self::Error>; } #[cfg(not(feature = "nightly"))] impl<T, U> TryInto<U> for T where U: TryFrom<T> { type Error = U::Error; fn try_into(self) -> Result<U, U::Error> { U::try_from(self) } }
use std::fs; fn main() { part1(); part2(); } fn part1() { let map = fs::read_to_string("./input").expect("Couldn't open input"); let slope = (3,1); println!("part1: hit {} trees", hit_trees(&map as &str, slope)); } fn part2() { let map = fs::read_to_string("./input").expect("Couldn't open input"); let slopes = [(1,1), (3,1), (5,1), (7,1), (1,2)]; for slope in slopes.iter() { println!("part2: hit {} trees", hit_trees(&map as &str, *slope)); } } fn hit_trees(map: &str, slope: (i32, i32)) -> i32 { let mut trees = 0; let rows = map.lines().collect::<Vec<&str>>(); let height = rows.len() as i32; let width = rows[0].trim().len() as i32; let mut sled_pos = (0,0); loop { if sled_pos.0 + slope.0 >= width { sled_pos.0 = sled_pos.0 + slope.0 - width; } else { sled_pos.0 = sled_pos.0 + slope.0; } sled_pos = (sled_pos.0, sled_pos.1 + slope.1); if sled_pos.1 >= height { // off the bottom of the map break; } let line = rows[sled_pos.1 as usize].trim(); if line.chars().collect::<Vec<char>>()[sled_pos.0 as usize] == '#' { trees += 1; } } trees } fn test() { let test_map = "..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#"; println!("hit {} trees", hit_trees(test_map, (3,1))); }
#[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::_3_INTEN { #[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 PWM_3_INTEN_INTCNTZEROR { bits: bool, } impl PWM_3_INTEN_INTCNTZEROR { #[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 _PWM_3_INTEN_INTCNTZEROW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_INTCNTZEROW<'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 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_INTCNTLOADR { bits: bool, } impl PWM_3_INTEN_INTCNTLOADR { #[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 _PWM_3_INTEN_INTCNTLOADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_INTCNTLOADW<'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 PWM_3_INTEN_INTCMPAUR { bits: bool, } impl PWM_3_INTEN_INTCMPAUR { #[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 _PWM_3_INTEN_INTCMPAUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_INTCMPAUW<'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 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_INTCMPADR { bits: bool, } impl PWM_3_INTEN_INTCMPADR { #[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 _PWM_3_INTEN_INTCMPADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_INTCMPADW<'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 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_INTCMPBUR { bits: bool, } impl PWM_3_INTEN_INTCMPBUR { #[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 _PWM_3_INTEN_INTCMPBUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_INTCMPBUW<'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 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_INTCMPBDR { bits: bool, } impl PWM_3_INTEN_INTCMPBDR { #[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 _PWM_3_INTEN_INTCMPBDW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_INTCMPBDW<'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 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_TRCNTZEROR { bits: bool, } impl PWM_3_INTEN_TRCNTZEROR { #[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 _PWM_3_INTEN_TRCNTZEROW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_TRCNTZEROW<'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 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_TRCNTLOADR { bits: bool, } impl PWM_3_INTEN_TRCNTLOADR { #[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 _PWM_3_INTEN_TRCNTLOADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_TRCNTLOADW<'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 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_TRCMPAUR { bits: bool, } impl PWM_3_INTEN_TRCMPAUR { #[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 _PWM_3_INTEN_TRCMPAUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_TRCMPAUW<'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 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_TRCMPADR { bits: bool, } impl PWM_3_INTEN_TRCMPADR { #[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 _PWM_3_INTEN_TRCMPADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_TRCMPADW<'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 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_TRCMPBUR { bits: bool, } impl PWM_3_INTEN_TRCMPBUR { #[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 _PWM_3_INTEN_TRCMPBUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_TRCMPBUW<'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 << 12); self.w.bits |= ((value as u32) & 1) << 12; self.w } } #[doc = r"Value of the field"] pub struct PWM_3_INTEN_TRCMPBDR { bits: bool, } impl PWM_3_INTEN_TRCMPBDR { #[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 _PWM_3_INTEN_TRCMPBDW<'a> { w: &'a mut W, } impl<'a> _PWM_3_INTEN_TRCMPBDW<'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 << 13); self.w.bits |= ((value as u32) & 1) << 13; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Interrupt for Counter=0"] #[inline(always)] pub fn pwm_3_inten_intcntzero(&self) -> PWM_3_INTEN_INTCNTZEROR { let bits = ((self.bits >> 0) & 1) != 0; PWM_3_INTEN_INTCNTZEROR { bits } } #[doc = "Bit 1 - Interrupt for Counter=PWMnLOAD"] #[inline(always)] pub fn pwm_3_inten_intcntload(&self) -> PWM_3_INTEN_INTCNTLOADR { let bits = ((self.bits >> 1) & 1) != 0; PWM_3_INTEN_INTCNTLOADR { bits } } #[doc = "Bit 2 - Interrupt for Counter=PWMnCMPA Up"] #[inline(always)] pub fn pwm_3_inten_intcmpau(&self) -> PWM_3_INTEN_INTCMPAUR { let bits = ((self.bits >> 2) & 1) != 0; PWM_3_INTEN_INTCMPAUR { bits } } #[doc = "Bit 3 - Interrupt for Counter=PWMnCMPA Down"] #[inline(always)] pub fn pwm_3_inten_intcmpad(&self) -> PWM_3_INTEN_INTCMPADR { let bits = ((self.bits >> 3) & 1) != 0; PWM_3_INTEN_INTCMPADR { bits } } #[doc = "Bit 4 - Interrupt for Counter=PWMnCMPB Up"] #[inline(always)] pub fn pwm_3_inten_intcmpbu(&self) -> PWM_3_INTEN_INTCMPBUR { let bits = ((self.bits >> 4) & 1) != 0; PWM_3_INTEN_INTCMPBUR { bits } } #[doc = "Bit 5 - Interrupt for Counter=PWMnCMPB Down"] #[inline(always)] pub fn pwm_3_inten_intcmpbd(&self) -> PWM_3_INTEN_INTCMPBDR { let bits = ((self.bits >> 5) & 1) != 0; PWM_3_INTEN_INTCMPBDR { bits } } #[doc = "Bit 8 - Trigger for Counter=0"] #[inline(always)] pub fn pwm_3_inten_trcntzero(&self) -> PWM_3_INTEN_TRCNTZEROR { let bits = ((self.bits >> 8) & 1) != 0; PWM_3_INTEN_TRCNTZEROR { bits } } #[doc = "Bit 9 - Trigger for Counter=PWMnLOAD"] #[inline(always)] pub fn pwm_3_inten_trcntload(&self) -> PWM_3_INTEN_TRCNTLOADR { let bits = ((self.bits >> 9) & 1) != 0; PWM_3_INTEN_TRCNTLOADR { bits } } #[doc = "Bit 10 - Trigger for Counter=PWMnCMPA Up"] #[inline(always)] pub fn pwm_3_inten_trcmpau(&self) -> PWM_3_INTEN_TRCMPAUR { let bits = ((self.bits >> 10) & 1) != 0; PWM_3_INTEN_TRCMPAUR { bits } } #[doc = "Bit 11 - Trigger for Counter=PWMnCMPA Down"] #[inline(always)] pub fn pwm_3_inten_trcmpad(&self) -> PWM_3_INTEN_TRCMPADR { let bits = ((self.bits >> 11) & 1) != 0; PWM_3_INTEN_TRCMPADR { bits } } #[doc = "Bit 12 - Trigger for Counter=PWMnCMPB Up"] #[inline(always)] pub fn pwm_3_inten_trcmpbu(&self) -> PWM_3_INTEN_TRCMPBUR { let bits = ((self.bits >> 12) & 1) != 0; PWM_3_INTEN_TRCMPBUR { bits } } #[doc = "Bit 13 - Trigger for Counter=PWMnCMPB Down"] #[inline(always)] pub fn pwm_3_inten_trcmpbd(&self) -> PWM_3_INTEN_TRCMPBDR { let bits = ((self.bits >> 13) & 1) != 0; PWM_3_INTEN_TRCMPBDR { 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 0 - Interrupt for Counter=0"] #[inline(always)] pub fn pwm_3_inten_intcntzero(&mut self) -> _PWM_3_INTEN_INTCNTZEROW { _PWM_3_INTEN_INTCNTZEROW { w: self } } #[doc = "Bit 1 - Interrupt for Counter=PWMnLOAD"] #[inline(always)] pub fn pwm_3_inten_intcntload(&mut self) -> _PWM_3_INTEN_INTCNTLOADW { _PWM_3_INTEN_INTCNTLOADW { w: self } } #[doc = "Bit 2 - Interrupt for Counter=PWMnCMPA Up"] #[inline(always)] pub fn pwm_3_inten_intcmpau(&mut self) -> _PWM_3_INTEN_INTCMPAUW { _PWM_3_INTEN_INTCMPAUW { w: self } } #[doc = "Bit 3 - Interrupt for Counter=PWMnCMPA Down"] #[inline(always)] pub fn pwm_3_inten_intcmpad(&mut self) -> _PWM_3_INTEN_INTCMPADW { _PWM_3_INTEN_INTCMPADW { w: self } } #[doc = "Bit 4 - Interrupt for Counter=PWMnCMPB Up"] #[inline(always)] pub fn pwm_3_inten_intcmpbu(&mut self) -> _PWM_3_INTEN_INTCMPBUW { _PWM_3_INTEN_INTCMPBUW { w: self } } #[doc = "Bit 5 - Interrupt for Counter=PWMnCMPB Down"] #[inline(always)] pub fn pwm_3_inten_intcmpbd(&mut self) -> _PWM_3_INTEN_INTCMPBDW { _PWM_3_INTEN_INTCMPBDW { w: self } } #[doc = "Bit 8 - Trigger for Counter=0"] #[inline(always)] pub fn pwm_3_inten_trcntzero(&mut self) -> _PWM_3_INTEN_TRCNTZEROW { _PWM_3_INTEN_TRCNTZEROW { w: self } } #[doc = "Bit 9 - Trigger for Counter=PWMnLOAD"] #[inline(always)] pub fn pwm_3_inten_trcntload(&mut self) -> _PWM_3_INTEN_TRCNTLOADW { _PWM_3_INTEN_TRCNTLOADW { w: self } } #[doc = "Bit 10 - Trigger for Counter=PWMnCMPA Up"] #[inline(always)] pub fn pwm_3_inten_trcmpau(&mut self) -> _PWM_3_INTEN_TRCMPAUW { _PWM_3_INTEN_TRCMPAUW { w: self } } #[doc = "Bit 11 - Trigger for Counter=PWMnCMPA Down"] #[inline(always)] pub fn pwm_3_inten_trcmpad(&mut self) -> _PWM_3_INTEN_TRCMPADW { _PWM_3_INTEN_TRCMPADW { w: self } } #[doc = "Bit 12 - Trigger for Counter=PWMnCMPB Up"] #[inline(always)] pub fn pwm_3_inten_trcmpbu(&mut self) -> _PWM_3_INTEN_TRCMPBUW { _PWM_3_INTEN_TRCMPBUW { w: self } } #[doc = "Bit 13 - Trigger for Counter=PWMnCMPB Down"] #[inline(always)] pub fn pwm_3_inten_trcmpbd(&mut self) -> _PWM_3_INTEN_TRCMPBDW { _PWM_3_INTEN_TRCMPBDW { w: self } } }
use chrono::prelude::*; use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation}; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct Claims { pub sub: String, pub company: String, #[serde(with = "jwt_numeric_date")] pub exp: DateTime<Utc>, } impl Claims { pub fn new(sub: String, company: String, exp: DateTime<Utc>) -> Self { let exp = exp .date() .and_hms_milli(exp.hour(), exp.minute(), exp.second(), 0); Self { sub, company, exp } } } mod jwt_numeric_date { use chrono::{DateTime, TimeZone, Utc}; use serde::{self, Deserialize, Deserializer, Serializer}; /// Serializes a DateTime<Utc> to a Unix timestamp (milliseconds since 1970/1/1T00:00:00T) pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let timestamp = date.timestamp(); serializer.serialize_i64(timestamp) } /// Attempts to deserialize an i64 and use as a Unix timestamp pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error> where D: Deserializer<'de>, { Utc.timestamp_opt(i64::deserialize(deserializer)?, 0) .single() // If there are multiple or no valid DateTimes from timestamp, return None .ok_or_else(|| serde::de::Error::custom("invalid Unix timestamp value")) } } pub fn validate_token(token: &String) -> Result<bool, Box<dyn std::error::Error>> { let secret = &std::env::var("JWT_SECRET").expect("JWT SECRET not set"); let _token_data = jsonwebtoken::decode::<Claims>( &token, &DecodingKey::from_secret(secret.as_ref()), &Validation::default(), )?; Ok(true) } pub fn decode_token(token: &String) -> String { let secret = &std::env::var("JWT_SECRET").expect("JWT SECRET not set"); let token_data = jsonwebtoken::decode::<Claims>( &token, &DecodingKey::from_secret(secret.as_ref()), &Validation::default(), ) .unwrap(); token_data.claims.company } pub fn create_token(user: &String, duration: i64) -> Result<String, Box<dyn std::error::Error>> { let sub = "user".to_string(); let company = user.to_string(); let exp = Utc::now() + chrono::Duration::days(duration); let secret = &std::env::var("JWT_SECRET").expect("JWT SECRET not set"); let claims = Claims::new(sub, company, exp); let token = jsonwebtoken::encode( &Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref()), )?; Ok(token) }
use super::Request; use crate::error::NotpResult; use crate::store::DataStore; pub(crate) fn delete<T: DataStore>(request: Request<'_, T>) -> NotpResult<()> { let store = request.store; let name = request.key.unwrap_or_default(); store.delete(String::from(name)) } #[cfg(test)] mod tests { use super::{ delete, Request, }; use crate::operations::add::add; use crate::store::{ kv_store::SecretStore, DataStore as DataStoreTrait, }; use crate::util::{ create_folder, remove_folder, }; fn kv_init<'a>( key: Option<&'a str>, enc: &str, path: Option<&'a str>, store: Option<&'a str>, ) -> Request<'a, SecretStore> { #[cfg(feature = "kv-store")] let store: SecretStore = DataStoreTrait::new(path, store) .expect("Could not create DataStore"); let mc = new_magic_crypt!(enc, 256); Request::new(key, store, Some(mc)) } #[test] fn should_delete_data() { let path = "TestDeleteData"; let _ = create_folder(path); add(kv_init( Some("TestDeleteData"), "TestKey", Some(path), Some("Test"), )) .ok(); let r = delete(kv_init( Some("TestDeleteData"), "TestKey", Some(path), Some("Test"), )); assert!(r.is_ok()); delete(kv_init( Some("TestGetData"), "TestKey", Some(path), Some("Test"), )) .ok(); remove_folder(path).ok(); } }
#[allow(unused_imports)] use proconio::{marker::*, *}; #[fastout] fn main() { input! { n: i32, } println!("{}", n * n); }
//! This module contains the definition of a "FieldList" a set of //! records of (field_name, field_type, last_timestamp) and code to //! pull them from RecordBatches use std::{collections::BTreeMap, sync::Arc}; use arrow::{ self, array::TimestampNanosecondArray, datatypes::{DataType, SchemaRef}, record_batch::RecordBatch, }; use schema::TIME_COLUMN_NAME; use snafu::{ensure, ResultExt, Snafu}; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display( "Internal error converting to FieldList. No time column in schema: {:?}. {}", schema, source ))] InternalNoTimeColumn { schema: SchemaRef, source: arrow::error::ArrowError, }, #[snafu(display( "Inconsistent data type for field '{}': found both '{:?}' and '{:?}'", field_name, data_type1, data_type2 ))] InconsistentFieldType { field_name: String, data_type1: DataType, data_type2: DataType, }, } pub type Result<T, E = Error> = std::result::Result<T, E>; /// Represents a single Field (column)'s metadata: Name, data_type, /// and most recent (last) timestamp. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Field { pub name: String, pub data_type: DataType, pub last_timestamp: i64, } /// A list of `Fields` #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct FieldList { pub fields: Vec<Field>, } /// Trait to convert RecordBatch'y things into `FieldLists`. Assumes /// that the input RecordBatch es can each have a single string /// column. pub trait IntoFieldList { /// Convert this thing into a fieldlist fn into_fieldlist(self) -> Result<FieldList>; } /// Converts record batches into FieldLists impl IntoFieldList for Vec<RecordBatch> { fn into_fieldlist(self) -> Result<FieldList> { if self.is_empty() { return Ok(FieldList::default()); } // For each field in the schema (except time) for all rows // that are non-null, update the current most-recent timestamp // seen let arrow_schema = self[0].schema(); let time_column_index = arrow_schema.index_of(TIME_COLUMN_NAME).with_context(|_| { InternalNoTimeColumnSnafu { schema: Arc::clone(&arrow_schema), } })?; // key: fieldname, value: highest value of time column we have seen let mut field_times = BTreeMap::new(); for batch in self { let time_column = batch .column(time_column_index) .as_any() .downcast_ref::<TimestampNanosecondArray>() .expect("Downcasting time to TimestampNanosecondArray"); for (column_index, arrow_field) in arrow_schema.fields().iter().enumerate() { if column_index == time_column_index { continue; } let array = batch.column(column_index); // walk each value in array, looking for non-null values let mut max_ts: Option<i64> = None; for i in 0..batch.num_rows() { if !array.is_null(i) { let cur_ts = time_column.value(i); max_ts = max_ts.map(|ts| std::cmp::max(ts, cur_ts)).or(Some(cur_ts)); } } if let Some(max_ts) = max_ts { if let Some(ts) = field_times.get_mut(arrow_field.name()) { *ts = std::cmp::max(max_ts, *ts); } else { field_times.insert(arrow_field.name().to_string(), max_ts); } } } } let fields = arrow_schema .fields() .iter() .filter_map(|arrow_field| { let field_name = arrow_field.name(); if field_name == TIME_COLUMN_NAME { None } else { field_times.get(field_name).map(|ts| Field { name: field_name.to_string(), data_type: arrow_field.data_type().clone(), last_timestamp: *ts, }) } }) .collect(); Ok(FieldList { fields }) } } /// Merge several FieldLists into a single field list, merging the /// entries appropriately // Clippy gets confused and tells me that I should be using Self // instead of Vec even though the type of Vec being created is different #[allow(clippy::use_self)] impl IntoFieldList for Vec<FieldList> { fn into_fieldlist(self) -> Result<FieldList> { if self.is_empty() { return Ok(FieldList::default()); } // otherwise merge the fields together let mut field_map = BTreeMap::<String, Field>::new(); // iterate over all fields let field_iter = self.into_iter().flat_map(|f| f.fields.into_iter()); for new_field in field_iter { if let Some(existing_field) = field_map.get_mut(&new_field.name) { ensure!( existing_field.data_type == new_field.data_type, InconsistentFieldTypeSnafu { field_name: new_field.name, data_type1: existing_field.data_type.clone(), data_type2: new_field.data_type, } ); existing_field.last_timestamp = std::cmp::max(existing_field.last_timestamp, new_field.last_timestamp); } // no entry for field yet else { field_map.insert(new_field.name.clone(), new_field); } } let mut fields = field_map.into_values().collect::<Vec<_>>(); fields.sort_by(|a, b| a.name.cmp(&b.name)); Ok(FieldList { fields }) } } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; use arrow::array::ArrayRef; use arrow::{ array::{Int64Array, StringArray}, datatypes::{DataType as ArrowDataType, Field as ArrowField, Schema}, }; use schema::TIME_DATA_TYPE; #[test] fn test_convert_single_batch() { let schema = Arc::new(Schema::new(vec![ ArrowField::new("string_field", ArrowDataType::Utf8, true), ArrowField::new("time", TIME_DATA_TYPE(), true), ])); let string_array: ArrayRef = Arc::new(StringArray::from(vec!["foo", "bar", "baz", "foo"])); let timestamp_array: ArrayRef = Arc::new(TimestampNanosecondArray::from_iter_values(vec![ 1000, 2000, 3000, 4000, ])); let actual = do_conversion( Arc::clone(&schema), vec![vec![string_array, timestamp_array]], ) .expect("convert correctly"); let expected = FieldList { fields: vec![Field { name: "string_field".into(), data_type: ArrowDataType::Utf8, last_timestamp: 4000, }], }; assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); // expect same even if the timestamp order is different let string_array: ArrayRef = Arc::new(StringArray::from(vec!["foo", "bar", "baz", "foo"])); let timestamp_array: ArrayRef = Arc::new(TimestampNanosecondArray::from_iter_values(vec![ 1000, 4000, 2000, 3000, ])); let actual = do_conversion(schema, vec![vec![string_array, timestamp_array]]) .expect("convert correctly"); assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); } #[test] fn test_convert_two_batches() { let schema = Arc::new(Schema::new(vec![ ArrowField::new("string_field", ArrowDataType::Utf8, true), ArrowField::new("time", TIME_DATA_TYPE(), true), ])); let string_array1: ArrayRef = Arc::new(StringArray::from(vec!["foo", "bar"])); let timestamp_array1: ArrayRef = Arc::new(TimestampNanosecondArray::from_iter_values(vec![1000, 3000])); let string_array2: ArrayRef = Arc::new(StringArray::from(vec!["foo", "foo"])); let timestamp_array2: ArrayRef = Arc::new(TimestampNanosecondArray::from_iter_values(vec![1000, 4000])); let actual = do_conversion( schema, vec![ vec![string_array1, timestamp_array1], vec![string_array2, timestamp_array2], ], ) .expect("convert correctly"); let expected = FieldList { fields: vec![Field { name: "string_field".into(), data_type: ArrowDataType::Utf8, last_timestamp: 4000, }], }; assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); } #[test] fn test_convert_all_nulls() { let schema = Arc::new(Schema::new(vec![ ArrowField::new("string_field", ArrowDataType::Utf8, true), ArrowField::new("time", TIME_DATA_TYPE(), true), ])); // string array has no actual values, so should not be returned as a field let string_array: ArrayRef = Arc::new(StringArray::from(vec![None::<&str>, None, None, None])); let timestamp_array: ArrayRef = Arc::new(TimestampNanosecondArray::from_iter_values(vec![ 1000, 2000, 3000, 4000, ])); let actual = do_conversion(schema, vec![vec![string_array, timestamp_array]]) .expect("convert correctly"); let expected = FieldList { fields: vec![] }; assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); } // test three columns, with different data types and null #[test] fn test_multi_column_multi_datatype() { let schema = Arc::new(Schema::new(vec![ ArrowField::new("string_field", ArrowDataType::Utf8, true), ArrowField::new("int_field", ArrowDataType::Int64, true), ArrowField::new("time", TIME_DATA_TYPE(), true), ])); let string_array: ArrayRef = Arc::new(StringArray::from(vec!["foo", "bar", "baz", "foo"])); let int_array: ArrayRef = Arc::new(Int64Array::from(vec![Some(10), Some(20), Some(30), None])); let timestamp_array: ArrayRef = Arc::new(TimestampNanosecondArray::from_iter_values(vec![ 1000, 2000, 3000, 4000, ])); let expected = FieldList { fields: vec![ Field { name: "string_field".into(), data_type: ArrowDataType::Utf8, last_timestamp: 4000, }, Field { name: "int_field".into(), data_type: ArrowDataType::Int64, last_timestamp: 3000, }, ], }; let actual = do_conversion(schema, vec![vec![string_array, int_array, timestamp_array]]) .expect("conversion successful"); assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); } fn do_conversion(schema: SchemaRef, value_arrays: Vec<Vec<ArrayRef>>) -> Result<FieldList> { let batches = value_arrays .into_iter() .map(|arrays| { RecordBatch::try_new(Arc::clone(&schema), arrays).expect("created new record batch") }) .collect::<Vec<_>>(); batches.into_fieldlist() } #[test] fn test_merge_field_list() { let field1 = Field { name: "one".into(), data_type: ArrowDataType::Utf8, last_timestamp: 4000, }; let field2 = Field { name: "two".into(), data_type: ArrowDataType::Int64, last_timestamp: 3000, }; let l1 = FieldList { fields: vec![field1, field2.clone()], }; let actual = vec![l1.clone()].into_fieldlist().unwrap(); let expected = l1.clone(); assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); let field1_later = Field { name: "one".into(), data_type: ArrowDataType::Utf8, last_timestamp: 5000, }; // use something that has a later timestamp and expect the later one takes // precedence let l2 = FieldList { fields: vec![field1_later.clone()], }; let actual = vec![l1.clone(), l2.clone()].into_fieldlist().unwrap(); let expected = FieldList { fields: vec![field1_later, field2], }; assert_eq!( expected, actual, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); // Now, try to add a field that has a different type let field1_new_type = Field { name: "one".into(), data_type: ArrowDataType::Int64, last_timestamp: 5000, }; // use something that has a later timestamp and expect the later one takes // precedence let l3 = FieldList { fields: vec![field1_new_type], }; let actual = vec![l1, l2, l3].into_fieldlist(); let actual_error = actual.expect_err("should be an error").to_string(); let expected_error = "Inconsistent data type for field 'one': found both 'Utf8' and 'Int64'"; assert!( actual_error.contains(expected_error), "Can not find expected '{expected_error}' in actual '{actual_error}'" ); } }
fn main() { println!("Hello to carol printer!"); let header = [ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eight", "ninth", "10th", "11th", "12th", ]; let lyrics = [ "A partridge in a pear tree", "Two turtle doves, and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "10 lords a-leaping", "11 pipers piping", "12 drummers drumming", ]; for i in 0..12 { println!( "On the {} day of Christmas my true love sent to me", header[i] ); for line in (0..(i + 1)).rev() { println!("{}", lyrics[line]); } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Functions in libc that haven't made it into nix yet use libc; use std::os::unix::io::RawFd; use nix::fcntl::{open, OFlag}; use nix::sys::stat::Mode; use nix::unistd::{close, write}; use super::super::super::qlib::common::*; use super::super::super::qlib::cstring::*; #[inline] pub fn lsetxattr( path: &CString, name: &CString, value: &CString, len: usize, flags: i32, ) -> Result<()> { let res = unsafe { libc::lsetxattr( path.Ptr() as *const libc::c_char, name.Ptr() as *const libc::c_char, value.Ptr() as *const libc::c_void, len, flags, ) }; return Error::MapRes(res as i32); } #[inline] pub fn fchdir(fd: RawFd) -> Result<()> { let res = unsafe { libc::fchdir(fd) }; return Error::MapRes(res as i32); } #[inline] pub fn setgroups(gids: &[libc::gid_t]) -> Result<()> { let res = unsafe { libc::setgroups(gids.len(), gids.as_ptr()) }; return Error::MapRes(res as i32); } #[inline] pub fn setrlimit( resource: libc::c_int, soft: libc::c_ulonglong, hard: libc::c_ulonglong, ) -> Result<()> { let rlim = &libc::rlimit { rlim_cur: soft, rlim_max: hard, }; let res = unsafe { libc::setrlimit(resource as u32, rlim) }; return Error::MapRes(res as i32); } #[inline] pub fn clearenv() -> Result<()> { let res = unsafe { libc::clearenv() }; return Error::MapRes(res as i32); } #[cfg(target_env = "gnu")] #[inline] pub fn putenv(string: &CString) -> Result<()> { // NOTE: gnue takes ownership of the string so we pass it // with into_raw. // This prevents the string to be de-allocated. // According to // https://www.gnu.org/software/libc/manual/html_node/Environment-Access.html // the variable will be accessable from the exec'd program // throughout its lifetime, as such this is not going to be re-claimed // and will show up as leak in valgrind and friends. let ptr = string.Ptr(); let res = unsafe { libc::putenv(ptr as *mut libc::c_char) }; return Error::MapRes(res as i32); } #[cfg(not(target_env = "gnu"))] pub fn putenv(string: &CString) -> Result<()> { let res = unsafe { libc::putenv(string.as_ptr() as *mut libc::c_char) }; return Error::MapRes(res as i32); } const EXEC_PATH: &'static str = "/proc/self/attr/exec"; pub fn setexeccon(label: &str) -> Result<()> { let fd = open(EXEC_PATH, OFlag::O_RDWR, Mode::empty()).map_err(|e| Error::IOError(format!("setexeccon error is {:?}", e)))?; defer!(close(fd).unwrap()); write(fd, label.as_bytes()).map_err(|e| Error::IOError(format!("setexeccon error is {:?}", e)))?; Ok(()) } const XATTR_NAME: &'static str = "security.selinux"; pub fn setfilecon(file: &str, label: &str) -> Result<()> { let path = CString::New(file); let name = CString::New(XATTR_NAME); let value = CString::New(label); lsetxattr(&path, &name, &value, label.len(), 0)?; Ok(()) }
/** * Calculate the "hamming" distance between two strings and return as a Result */ pub fn hamming_distance(a: &str, b: &str) -> Result<i32, i32> { // Basic error handling if a.len() != b.len() { return Err(0); } let mut ham_count = 0; for (key, character) in a.chars().enumerate() { // Compare each character to the equivalent position in b if character != b.chars().nth(key).unwrap() { ham_count += 1; } } Ok(ham_count) }
use crate::{ sr::constants::Constant, sr::instructions, sr::ops::{self, Op}, sr::storage::*, sr::types::Type, }; #[derive(Debug)] pub struct EntryPoint { pub execution_model: spirv::ExecutionModel, pub function: Token<Function>, pub name: String, //pub interface: Vec<spirv::Word>, } #[derive(Debug)] pub struct Block { pub arguments: Vec<Token<Type>>, pub ops: Vec<Token<Op>>, pub terminator: ops::Terminator, } /// Jump destination parameters. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Jump { /// The block to jump to. pub block: Token<Block>, /// The argument values corresponding to the block arguments. pub arguments: Vec<Token<Op>>, } pub struct Function { pub control: spirv::FunctionControl, /// Function result type. pub result: Token<Type>, /// Function parameters. pub parameters: Vec<Token<Type>>, /// All blocks in this function. pub blocks: Storage<Block>, /// The first block of this function. pub start_block: Token<Block>, } pub struct Module { /// Version of the specification. pub version: spirv::Word, /// All OpCapability instructions. pub capabilities: Vec<spirv::Capability>, /// All OpExtension instructions. pub extensions: Vec<String>, /// All OpExtInstImport instructions. pub ext_inst_imports: Vec<String>, /// The OpMemoryModel instruction. pub memory_model: instructions::MemoryModel, /// All entry point declarations. pub entry_points: Vec<EntryPoint>, /// All types pub types: Storage<Type>, /// All constants. pub constants: Storage<Constant>, /// All operations. pub ops: Storage<Op>, /// All functions. pub functions: Vec<Function>, }
// buat trait Summary dengan default implementasi dari method `summarize` trait Summary { fn summarize(&self) -> String { String::from("(Read more...)") } } struct News; // karena struk News tidak mendetilkan fungsi `summarize` maka akan // menggunakan default implementasi dari trait `Summary` impl Summary for News {} fn main() { let news = News {}; println!("Summary: {}", news.summarize()); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IMidiChannelPressureMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiChannelPressureMessage { type Vtable = IMidiChannelPressureMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbe1fa860_62b4_4d52_a37e_92e54d35b909); } #[repr(C)] #[doc(hidden)] pub struct IMidiChannelPressureMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiChannelPressureMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiChannelPressureMessageFactory { type Vtable = IMidiChannelPressureMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6218ed2f_2284_412a_94cf_10fb04842c6c); } #[repr(C)] #[doc(hidden)] pub struct IMidiChannelPressureMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, pressure: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiControlChangeMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiControlChangeMessage { type Vtable = IMidiControlChangeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7e15f83_780d_405f_b781_3e1598c97f40); } #[repr(C)] #[doc(hidden)] pub struct IMidiControlChangeMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiControlChangeMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiControlChangeMessageFactory { type Vtable = IMidiControlChangeMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2ab14321_956c_46ad_9752_f87f55052fe3); } #[repr(C)] #[doc(hidden)] pub struct IMidiControlChangeMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, controller: u8, controlvalue: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiInPort(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiInPort { type Vtable = IMidiInPort_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5c1d9db_971a_4eaf_a23d_ea19fe607ff9); } #[repr(C)] #[doc(hidden)] pub struct IMidiInPort_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiInPortStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiInPortStatics { type Vtable = IMidiInPortStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x44c439dc_67ff_4a6e_8bac_fdb6610cf296); } #[repr(C)] #[doc(hidden)] pub struct IMidiInPortStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMidiMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl IMidiMessage { #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for IMidiMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{79767945-1094-4283-9be0-289fc0ee8334}"); } impl ::core::convert::From<IMidiMessage> for ::windows::core::IUnknown { fn from(value: IMidiMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&IMidiMessage> for ::windows::core::IUnknown { fn from(value: &IMidiMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMidiMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMidiMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IMidiMessage> for ::windows::core::IInspectable { fn from(value: IMidiMessage) -> Self { value.0 } } impl ::core::convert::From<&IMidiMessage> for ::windows::core::IInspectable { fn from(value: &IMidiMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMidiMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IMidiMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMidiMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MidiMessageType) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiMessageReceivedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiMessageReceivedEventArgs { type Vtable = IMidiMessageReceivedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x76566e56_f328_4b51_907d_b3a8ce96bf80); } #[repr(C)] #[doc(hidden)] pub struct IMidiMessageReceivedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiNoteOffMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiNoteOffMessage { type Vtable = IMidiNoteOffMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x16fd8af4_198e_4d8f_a654_d305a293548f); } #[repr(C)] #[doc(hidden)] pub struct IMidiNoteOffMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiNoteOffMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiNoteOffMessageFactory { type Vtable = IMidiNoteOffMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa6b240e0_a749_425f_8af4_a4d979cc15b5); } #[repr(C)] #[doc(hidden)] pub struct IMidiNoteOffMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, note: u8, velocity: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiNoteOnMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiNoteOnMessage { type Vtable = IMidiNoteOnMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0224af5_6181_46dd_afa2_410004c057aa); } #[repr(C)] #[doc(hidden)] pub struct IMidiNoteOnMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiNoteOnMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiNoteOnMessageFactory { type Vtable = IMidiNoteOnMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b4280a0_59c1_420e_b517_15a10aa9606b); } #[repr(C)] #[doc(hidden)] pub struct IMidiNoteOnMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, note: u8, velocity: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMidiOutPort(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiOutPort { type Vtable = IMidiOutPort_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x931d6d9f_57a2_4a3a_adb8_4640886f6693); } impl IMidiOutPort { pub fn SendMessage<'a, Param0: ::windows::core::IntoParam<'a, IMidiMessage>>(&self, midimessage: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), midimessage.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn SendBuffer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(&self, mididata: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), mididata.into_param().abi()).ok() } } pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for IMidiOutPort { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{931d6d9f-57a2-4a3a-adb8-4640886f6693}"); } impl ::core::convert::From<IMidiOutPort> for ::windows::core::IUnknown { fn from(value: IMidiOutPort) -> Self { value.0 .0 } } impl ::core::convert::From<&IMidiOutPort> for ::windows::core::IUnknown { fn from(value: &IMidiOutPort) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IMidiOutPort> for ::windows::core::IInspectable { fn from(value: IMidiOutPort) -> Self { value.0 } } impl ::core::convert::From<&IMidiOutPort> for ::windows::core::IInspectable { fn from(value: &IMidiOutPort) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IMidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<IMidiOutPort> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: IMidiOutPort) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&IMidiOutPort> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &IMidiOutPort) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for IMidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &IMidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IMidiOutPort_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, midimessage: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mididata: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiOutPortStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiOutPortStatics { type Vtable = IMidiOutPortStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x065cc3e9_0f88_448b_9b64_a95826c65b8f); } #[repr(C)] #[doc(hidden)] pub struct IMidiOutPortStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiPitchBendChangeMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiPitchBendChangeMessage { type Vtable = IMidiPitchBendChangeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x29df4cb1_2e9f_4faf_8c2b_9cb82a9079ca); } #[repr(C)] #[doc(hidden)] pub struct IMidiPitchBendChangeMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiPitchBendChangeMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiPitchBendChangeMessageFactory { type Vtable = IMidiPitchBendChangeMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5eedf55_cfc8_4926_b30e_a3622393306c); } #[repr(C)] #[doc(hidden)] pub struct IMidiPitchBendChangeMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, bend: u16, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiPolyphonicKeyPressureMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiPolyphonicKeyPressureMessage { type Vtable = IMidiPolyphonicKeyPressureMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f7337fe_ace8_48a0_868e_7cdbf20f04d6); } #[repr(C)] #[doc(hidden)] pub struct IMidiPolyphonicKeyPressureMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiPolyphonicKeyPressureMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiPolyphonicKeyPressureMessageFactory { type Vtable = IMidiPolyphonicKeyPressureMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe98f483e_c4b3_4dd2_917c_e349815a1b3b); } #[repr(C)] #[doc(hidden)] pub struct IMidiPolyphonicKeyPressureMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, note: u8, pressure: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiProgramChangeMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiProgramChangeMessage { type Vtable = IMidiProgramChangeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9cbb3c78_7a3e_4327_aa98_20b8e4485af8); } #[repr(C)] #[doc(hidden)] pub struct IMidiProgramChangeMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiProgramChangeMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiProgramChangeMessageFactory { type Vtable = IMidiProgramChangeMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd6b04387_524b_4104_9c99_6572bfd2e261); } #[repr(C)] #[doc(hidden)] pub struct IMidiProgramChangeMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: u8, program: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSongPositionPointerMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSongPositionPointerMessage { type Vtable = IMidiSongPositionPointerMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4ca50c56_ec5e_4ae4_a115_88dc57cc2b79); } #[repr(C)] #[doc(hidden)] pub struct IMidiSongPositionPointerMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSongPositionPointerMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSongPositionPointerMessageFactory { type Vtable = IMidiSongPositionPointerMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9c00e996_f10b_4fea_b395_f5d6cf80f64e); } #[repr(C)] #[doc(hidden)] pub struct IMidiSongPositionPointerMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, beats: u16, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSongSelectMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSongSelectMessage { type Vtable = IMidiSongSelectMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49f0f27f_6d83_4741_a5bf_4629f6be974f); } #[repr(C)] #[doc(hidden)] pub struct IMidiSongSelectMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSongSelectMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSongSelectMessageFactory { type Vtable = IMidiSongSelectMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x848878e4_8748_4129_a66c_a05493f75daa); } #[repr(C)] #[doc(hidden)] pub struct IMidiSongSelectMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, song: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSynthesizer(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSynthesizer { type Vtable = IMidiSynthesizer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf0da155e_db90_405f_b8ae_21d2e17f2e45); } #[repr(C)] #[doc(hidden)] pub struct IMidiSynthesizer_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Enumeration")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Enumeration"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSynthesizerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSynthesizerStatics { type Vtable = IMidiSynthesizerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4224eaa8_6629_4d6b_aa8f_d4521a5a31ce); } #[repr(C)] #[doc(hidden)] pub struct IMidiSynthesizerStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Devices_Enumeration", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, audiodevice: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Enumeration", feature = "Foundation")))] usize, #[cfg(feature = "Devices_Enumeration")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mididevice: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Enumeration"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiSystemExclusiveMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiSystemExclusiveMessageFactory { type Vtable = IMidiSystemExclusiveMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x083de222_3b74_4320_9b42_0ca8545f8a24); } #[repr(C)] #[doc(hidden)] pub struct IMidiSystemExclusiveMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rawdata: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiTimeCodeMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiTimeCodeMessage { type Vtable = IMidiTimeCodeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0bf7087d_fa63_4a1c_8deb_c0e87796a6d7); } #[repr(C)] #[doc(hidden)] pub struct IMidiTimeCodeMessage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMidiTimeCodeMessageFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMidiTimeCodeMessageFactory { type Vtable = IMidiTimeCodeMessageFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeb3099c5_771c_40de_b961_175a7489a85e); } #[repr(C)] #[doc(hidden)] pub struct IMidiTimeCodeMessageFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, frametype: u8, values: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiActiveSensingMessage(pub ::windows::core::IInspectable); impl MidiActiveSensingMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiActiveSensingMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiActiveSensingMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiActiveSensingMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiActiveSensingMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiActiveSensingMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiActiveSensingMessage"; } impl ::core::convert::From<MidiActiveSensingMessage> for ::windows::core::IUnknown { fn from(value: MidiActiveSensingMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiActiveSensingMessage> for ::windows::core::IUnknown { fn from(value: &MidiActiveSensingMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiActiveSensingMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiActiveSensingMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiActiveSensingMessage> for ::windows::core::IInspectable { fn from(value: MidiActiveSensingMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiActiveSensingMessage> for ::windows::core::IInspectable { fn from(value: &MidiActiveSensingMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiActiveSensingMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiActiveSensingMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiActiveSensingMessage> for IMidiMessage { fn from(value: MidiActiveSensingMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiActiveSensingMessage> for IMidiMessage { fn from(value: &MidiActiveSensingMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiActiveSensingMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiActiveSensingMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiActiveSensingMessage {} unsafe impl ::core::marker::Sync for MidiActiveSensingMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiChannelPressureMessage(pub ::windows::core::IInspectable); impl MidiChannelPressureMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Pressure(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiChannelPressureMessage(channel: u8, pressure: u8) -> ::windows::core::Result<MidiChannelPressureMessage> { Self::IMidiChannelPressureMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, pressure, &mut result__).from_abi::<MidiChannelPressureMessage>(result__) }) } pub fn IMidiChannelPressureMessageFactory<R, F: FnOnce(&IMidiChannelPressureMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiChannelPressureMessage, IMidiChannelPressureMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiChannelPressureMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiChannelPressureMessage;{be1fa860-62b4-4d52-a37e-92e54d35b909})"); } unsafe impl ::windows::core::Interface for MidiChannelPressureMessage { type Vtable = IMidiChannelPressureMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbe1fa860_62b4_4d52_a37e_92e54d35b909); } impl ::windows::core::RuntimeName for MidiChannelPressureMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiChannelPressureMessage"; } impl ::core::convert::From<MidiChannelPressureMessage> for ::windows::core::IUnknown { fn from(value: MidiChannelPressureMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiChannelPressureMessage> for ::windows::core::IUnknown { fn from(value: &MidiChannelPressureMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiChannelPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiChannelPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiChannelPressureMessage> for ::windows::core::IInspectable { fn from(value: MidiChannelPressureMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiChannelPressureMessage> for ::windows::core::IInspectable { fn from(value: &MidiChannelPressureMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiChannelPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiChannelPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiChannelPressureMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiChannelPressureMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiChannelPressureMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiChannelPressureMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiChannelPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiChannelPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiChannelPressureMessage {} unsafe impl ::core::marker::Sync for MidiChannelPressureMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiContinueMessage(pub ::windows::core::IInspectable); impl MidiContinueMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiContinueMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiContinueMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiContinueMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiContinueMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiContinueMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiContinueMessage"; } impl ::core::convert::From<MidiContinueMessage> for ::windows::core::IUnknown { fn from(value: MidiContinueMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiContinueMessage> for ::windows::core::IUnknown { fn from(value: &MidiContinueMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiContinueMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiContinueMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiContinueMessage> for ::windows::core::IInspectable { fn from(value: MidiContinueMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiContinueMessage> for ::windows::core::IInspectable { fn from(value: &MidiContinueMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiContinueMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiContinueMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiContinueMessage> for IMidiMessage { fn from(value: MidiContinueMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiContinueMessage> for IMidiMessage { fn from(value: &MidiContinueMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiContinueMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiContinueMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiContinueMessage {} unsafe impl ::core::marker::Sync for MidiContinueMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiControlChangeMessage(pub ::windows::core::IInspectable); impl MidiControlChangeMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Controller(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn ControlValue(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiControlChangeMessage(channel: u8, controller: u8, controlvalue: u8) -> ::windows::core::Result<MidiControlChangeMessage> { Self::IMidiControlChangeMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, controller, controlvalue, &mut result__).from_abi::<MidiControlChangeMessage>(result__) }) } pub fn IMidiControlChangeMessageFactory<R, F: FnOnce(&IMidiControlChangeMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiControlChangeMessage, IMidiControlChangeMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiControlChangeMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiControlChangeMessage;{b7e15f83-780d-405f-b781-3e1598c97f40})"); } unsafe impl ::windows::core::Interface for MidiControlChangeMessage { type Vtable = IMidiControlChangeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7e15f83_780d_405f_b781_3e1598c97f40); } impl ::windows::core::RuntimeName for MidiControlChangeMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiControlChangeMessage"; } impl ::core::convert::From<MidiControlChangeMessage> for ::windows::core::IUnknown { fn from(value: MidiControlChangeMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiControlChangeMessage> for ::windows::core::IUnknown { fn from(value: &MidiControlChangeMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiControlChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiControlChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiControlChangeMessage> for ::windows::core::IInspectable { fn from(value: MidiControlChangeMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiControlChangeMessage> for ::windows::core::IInspectable { fn from(value: &MidiControlChangeMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiControlChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiControlChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiControlChangeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiControlChangeMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiControlChangeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiControlChangeMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiControlChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiControlChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiControlChangeMessage {} unsafe impl ::core::marker::Sync for MidiControlChangeMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiInPort(pub ::windows::core::IInspectable); impl MidiInPort { #[cfg(feature = "Foundation")] pub fn MessageReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<MidiInPort, MidiMessageReceivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveMessageReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MidiInPort>> { Self::IMidiInPortStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MidiInPort>>(result__) }) } pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IMidiInPortStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IMidiInPortStatics<R, F: FnOnce(&IMidiInPortStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiInPort, IMidiInPortStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiInPort { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiInPort;{d5c1d9db-971a-4eaf-a23d-ea19fe607ff9})"); } unsafe impl ::windows::core::Interface for MidiInPort { type Vtable = IMidiInPort_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5c1d9db_971a_4eaf_a23d_ea19fe607ff9); } impl ::windows::core::RuntimeName for MidiInPort { const NAME: &'static str = "Windows.Devices.Midi.MidiInPort"; } impl ::core::convert::From<MidiInPort> for ::windows::core::IUnknown { fn from(value: MidiInPort) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiInPort> for ::windows::core::IUnknown { fn from(value: &MidiInPort) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiInPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiInPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiInPort> for ::windows::core::IInspectable { fn from(value: MidiInPort) -> Self { value.0 } } impl ::core::convert::From<&MidiInPort> for ::windows::core::IInspectable { fn from(value: &MidiInPort) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiInPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiInPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<MidiInPort> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: MidiInPort) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&MidiInPort> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &MidiInPort) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for MidiInPort { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &MidiInPort { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiInPort {} unsafe impl ::core::marker::Sync for MidiInPort {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiMessageReceivedEventArgs(pub ::windows::core::IInspectable); impl MidiMessageReceivedEventArgs { pub fn Message(&self) -> ::windows::core::Result<IMidiMessage> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IMidiMessage>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiMessageReceivedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiMessageReceivedEventArgs;{76566e56-f328-4b51-907d-b3a8ce96bf80})"); } unsafe impl ::windows::core::Interface for MidiMessageReceivedEventArgs { type Vtable = IMidiMessageReceivedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x76566e56_f328_4b51_907d_b3a8ce96bf80); } impl ::windows::core::RuntimeName for MidiMessageReceivedEventArgs { const NAME: &'static str = "Windows.Devices.Midi.MidiMessageReceivedEventArgs"; } impl ::core::convert::From<MidiMessageReceivedEventArgs> for ::windows::core::IUnknown { fn from(value: MidiMessageReceivedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiMessageReceivedEventArgs> for ::windows::core::IUnknown { fn from(value: &MidiMessageReceivedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiMessageReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiMessageReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiMessageReceivedEventArgs> for ::windows::core::IInspectable { fn from(value: MidiMessageReceivedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&MidiMessageReceivedEventArgs> for ::windows::core::IInspectable { fn from(value: &MidiMessageReceivedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiMessageReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiMessageReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MidiMessageReceivedEventArgs {} unsafe impl ::core::marker::Sync for MidiMessageReceivedEventArgs {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MidiMessageType(pub i32); impl MidiMessageType { pub const None: MidiMessageType = MidiMessageType(0i32); pub const NoteOff: MidiMessageType = MidiMessageType(128i32); pub const NoteOn: MidiMessageType = MidiMessageType(144i32); pub const PolyphonicKeyPressure: MidiMessageType = MidiMessageType(160i32); pub const ControlChange: MidiMessageType = MidiMessageType(176i32); pub const ProgramChange: MidiMessageType = MidiMessageType(192i32); pub const ChannelPressure: MidiMessageType = MidiMessageType(208i32); pub const PitchBendChange: MidiMessageType = MidiMessageType(224i32); pub const SystemExclusive: MidiMessageType = MidiMessageType(240i32); pub const MidiTimeCode: MidiMessageType = MidiMessageType(241i32); pub const SongPositionPointer: MidiMessageType = MidiMessageType(242i32); pub const SongSelect: MidiMessageType = MidiMessageType(243i32); pub const TuneRequest: MidiMessageType = MidiMessageType(246i32); pub const EndSystemExclusive: MidiMessageType = MidiMessageType(247i32); pub const TimingClock: MidiMessageType = MidiMessageType(248i32); pub const Start: MidiMessageType = MidiMessageType(250i32); pub const Continue: MidiMessageType = MidiMessageType(251i32); pub const Stop: MidiMessageType = MidiMessageType(252i32); pub const ActiveSensing: MidiMessageType = MidiMessageType(254i32); pub const SystemReset: MidiMessageType = MidiMessageType(255i32); } impl ::core::convert::From<i32> for MidiMessageType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MidiMessageType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MidiMessageType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Midi.MidiMessageType;i4)"); } impl ::windows::core::DefaultType for MidiMessageType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiNoteOffMessage(pub ::windows::core::IInspectable); impl MidiNoteOffMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Note(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Velocity(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiNoteOffMessage(channel: u8, note: u8, velocity: u8) -> ::windows::core::Result<MidiNoteOffMessage> { Self::IMidiNoteOffMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, note, velocity, &mut result__).from_abi::<MidiNoteOffMessage>(result__) }) } pub fn IMidiNoteOffMessageFactory<R, F: FnOnce(&IMidiNoteOffMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiNoteOffMessage, IMidiNoteOffMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiNoteOffMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiNoteOffMessage;{16fd8af4-198e-4d8f-a654-d305a293548f})"); } unsafe impl ::windows::core::Interface for MidiNoteOffMessage { type Vtable = IMidiNoteOffMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x16fd8af4_198e_4d8f_a654_d305a293548f); } impl ::windows::core::RuntimeName for MidiNoteOffMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiNoteOffMessage"; } impl ::core::convert::From<MidiNoteOffMessage> for ::windows::core::IUnknown { fn from(value: MidiNoteOffMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiNoteOffMessage> for ::windows::core::IUnknown { fn from(value: &MidiNoteOffMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiNoteOffMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiNoteOffMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiNoteOffMessage> for ::windows::core::IInspectable { fn from(value: MidiNoteOffMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiNoteOffMessage> for ::windows::core::IInspectable { fn from(value: &MidiNoteOffMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiNoteOffMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiNoteOffMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiNoteOffMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiNoteOffMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiNoteOffMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiNoteOffMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiNoteOffMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiNoteOffMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiNoteOffMessage {} unsafe impl ::core::marker::Sync for MidiNoteOffMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiNoteOnMessage(pub ::windows::core::IInspectable); impl MidiNoteOnMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Note(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Velocity(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiNoteOnMessage(channel: u8, note: u8, velocity: u8) -> ::windows::core::Result<MidiNoteOnMessage> { Self::IMidiNoteOnMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, note, velocity, &mut result__).from_abi::<MidiNoteOnMessage>(result__) }) } pub fn IMidiNoteOnMessageFactory<R, F: FnOnce(&IMidiNoteOnMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiNoteOnMessage, IMidiNoteOnMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiNoteOnMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiNoteOnMessage;{e0224af5-6181-46dd-afa2-410004c057aa})"); } unsafe impl ::windows::core::Interface for MidiNoteOnMessage { type Vtable = IMidiNoteOnMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0224af5_6181_46dd_afa2_410004c057aa); } impl ::windows::core::RuntimeName for MidiNoteOnMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiNoteOnMessage"; } impl ::core::convert::From<MidiNoteOnMessage> for ::windows::core::IUnknown { fn from(value: MidiNoteOnMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiNoteOnMessage> for ::windows::core::IUnknown { fn from(value: &MidiNoteOnMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiNoteOnMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiNoteOnMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiNoteOnMessage> for ::windows::core::IInspectable { fn from(value: MidiNoteOnMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiNoteOnMessage> for ::windows::core::IInspectable { fn from(value: &MidiNoteOnMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiNoteOnMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiNoteOnMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiNoteOnMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiNoteOnMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiNoteOnMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiNoteOnMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiNoteOnMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiNoteOnMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiNoteOnMessage {} unsafe impl ::core::marker::Sync for MidiNoteOnMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiOutPort(pub ::windows::core::IInspectable); impl MidiOutPort { pub fn SendMessage<'a, Param0: ::windows::core::IntoParam<'a, IMidiMessage>>(&self, midimessage: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), midimessage.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn SendBuffer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(&self, mididata: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), mididata.into_param().abi()).ok() } } pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<IMidiOutPort>> { Self::IMidiOutPortStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<IMidiOutPort>>(result__) }) } pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IMidiOutPortStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IMidiOutPortStatics<R, F: FnOnce(&IMidiOutPortStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiOutPort, IMidiOutPortStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiOutPort { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiOutPort;{931d6d9f-57a2-4a3a-adb8-4640886f6693})"); } unsafe impl ::windows::core::Interface for MidiOutPort { type Vtable = IMidiOutPort_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x931d6d9f_57a2_4a3a_adb8_4640886f6693); } impl ::windows::core::RuntimeName for MidiOutPort { const NAME: &'static str = "Windows.Devices.Midi.MidiOutPort"; } impl ::core::convert::From<MidiOutPort> for ::windows::core::IUnknown { fn from(value: MidiOutPort) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiOutPort> for ::windows::core::IUnknown { fn from(value: &MidiOutPort) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiOutPort> for ::windows::core::IInspectable { fn from(value: MidiOutPort) -> Self { value.0 } } impl ::core::convert::From<&MidiOutPort> for ::windows::core::IInspectable { fn from(value: &MidiOutPort) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiOutPort> for IMidiOutPort { fn from(value: MidiOutPort) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiOutPort> for IMidiOutPort { fn from(value: &MidiOutPort) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiOutPort> for MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, IMidiOutPort> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiOutPort> for &MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, IMidiOutPort> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<MidiOutPort> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: MidiOutPort) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&MidiOutPort> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &MidiOutPort) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &MidiOutPort { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiOutPort {} unsafe impl ::core::marker::Sync for MidiOutPort {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiPitchBendChangeMessage(pub ::windows::core::IInspectable); impl MidiPitchBendChangeMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Bend(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiPitchBendChangeMessage(channel: u8, bend: u16) -> ::windows::core::Result<MidiPitchBendChangeMessage> { Self::IMidiPitchBendChangeMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, bend, &mut result__).from_abi::<MidiPitchBendChangeMessage>(result__) }) } pub fn IMidiPitchBendChangeMessageFactory<R, F: FnOnce(&IMidiPitchBendChangeMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiPitchBendChangeMessage, IMidiPitchBendChangeMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiPitchBendChangeMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiPitchBendChangeMessage;{29df4cb1-2e9f-4faf-8c2b-9cb82a9079ca})"); } unsafe impl ::windows::core::Interface for MidiPitchBendChangeMessage { type Vtable = IMidiPitchBendChangeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x29df4cb1_2e9f_4faf_8c2b_9cb82a9079ca); } impl ::windows::core::RuntimeName for MidiPitchBendChangeMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiPitchBendChangeMessage"; } impl ::core::convert::From<MidiPitchBendChangeMessage> for ::windows::core::IUnknown { fn from(value: MidiPitchBendChangeMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiPitchBendChangeMessage> for ::windows::core::IUnknown { fn from(value: &MidiPitchBendChangeMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiPitchBendChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiPitchBendChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiPitchBendChangeMessage> for ::windows::core::IInspectable { fn from(value: MidiPitchBendChangeMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiPitchBendChangeMessage> for ::windows::core::IInspectable { fn from(value: &MidiPitchBendChangeMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiPitchBendChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiPitchBendChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiPitchBendChangeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiPitchBendChangeMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiPitchBendChangeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiPitchBendChangeMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiPitchBendChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiPitchBendChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiPitchBendChangeMessage {} unsafe impl ::core::marker::Sync for MidiPitchBendChangeMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiPolyphonicKeyPressureMessage(pub ::windows::core::IInspectable); impl MidiPolyphonicKeyPressureMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Note(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Pressure(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiPolyphonicKeyPressureMessage(channel: u8, note: u8, pressure: u8) -> ::windows::core::Result<MidiPolyphonicKeyPressureMessage> { Self::IMidiPolyphonicKeyPressureMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, note, pressure, &mut result__).from_abi::<MidiPolyphonicKeyPressureMessage>(result__) }) } pub fn IMidiPolyphonicKeyPressureMessageFactory<R, F: FnOnce(&IMidiPolyphonicKeyPressureMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiPolyphonicKeyPressureMessage, IMidiPolyphonicKeyPressureMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiPolyphonicKeyPressureMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiPolyphonicKeyPressureMessage;{1f7337fe-ace8-48a0-868e-7cdbf20f04d6})"); } unsafe impl ::windows::core::Interface for MidiPolyphonicKeyPressureMessage { type Vtable = IMidiPolyphonicKeyPressureMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f7337fe_ace8_48a0_868e_7cdbf20f04d6); } impl ::windows::core::RuntimeName for MidiPolyphonicKeyPressureMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiPolyphonicKeyPressureMessage"; } impl ::core::convert::From<MidiPolyphonicKeyPressureMessage> for ::windows::core::IUnknown { fn from(value: MidiPolyphonicKeyPressureMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiPolyphonicKeyPressureMessage> for ::windows::core::IUnknown { fn from(value: &MidiPolyphonicKeyPressureMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiPolyphonicKeyPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiPolyphonicKeyPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiPolyphonicKeyPressureMessage> for ::windows::core::IInspectable { fn from(value: MidiPolyphonicKeyPressureMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiPolyphonicKeyPressureMessage> for ::windows::core::IInspectable { fn from(value: &MidiPolyphonicKeyPressureMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiPolyphonicKeyPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiPolyphonicKeyPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiPolyphonicKeyPressureMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiPolyphonicKeyPressureMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiPolyphonicKeyPressureMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiPolyphonicKeyPressureMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiPolyphonicKeyPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiPolyphonicKeyPressureMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiPolyphonicKeyPressureMessage {} unsafe impl ::core::marker::Sync for MidiPolyphonicKeyPressureMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiProgramChangeMessage(pub ::windows::core::IInspectable); impl MidiProgramChangeMessage { pub fn Channel(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Program(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiProgramChangeMessage(channel: u8, program: u8) -> ::windows::core::Result<MidiProgramChangeMessage> { Self::IMidiProgramChangeMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), channel, program, &mut result__).from_abi::<MidiProgramChangeMessage>(result__) }) } pub fn IMidiProgramChangeMessageFactory<R, F: FnOnce(&IMidiProgramChangeMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiProgramChangeMessage, IMidiProgramChangeMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiProgramChangeMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiProgramChangeMessage;{9cbb3c78-7a3e-4327-aa98-20b8e4485af8})"); } unsafe impl ::windows::core::Interface for MidiProgramChangeMessage { type Vtable = IMidiProgramChangeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9cbb3c78_7a3e_4327_aa98_20b8e4485af8); } impl ::windows::core::RuntimeName for MidiProgramChangeMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiProgramChangeMessage"; } impl ::core::convert::From<MidiProgramChangeMessage> for ::windows::core::IUnknown { fn from(value: MidiProgramChangeMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiProgramChangeMessage> for ::windows::core::IUnknown { fn from(value: &MidiProgramChangeMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiProgramChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiProgramChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiProgramChangeMessage> for ::windows::core::IInspectable { fn from(value: MidiProgramChangeMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiProgramChangeMessage> for ::windows::core::IInspectable { fn from(value: &MidiProgramChangeMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiProgramChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiProgramChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiProgramChangeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiProgramChangeMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiProgramChangeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiProgramChangeMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiProgramChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiProgramChangeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiProgramChangeMessage {} unsafe impl ::core::marker::Sync for MidiProgramChangeMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiSongPositionPointerMessage(pub ::windows::core::IInspectable); impl MidiSongPositionPointerMessage { pub fn Beats(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiSongPositionPointerMessage(beats: u16) -> ::windows::core::Result<MidiSongPositionPointerMessage> { Self::IMidiSongPositionPointerMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), beats, &mut result__).from_abi::<MidiSongPositionPointerMessage>(result__) }) } pub fn IMidiSongPositionPointerMessageFactory<R, F: FnOnce(&IMidiSongPositionPointerMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiSongPositionPointerMessage, IMidiSongPositionPointerMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiSongPositionPointerMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiSongPositionPointerMessage;{4ca50c56-ec5e-4ae4-a115-88dc57cc2b79})"); } unsafe impl ::windows::core::Interface for MidiSongPositionPointerMessage { type Vtable = IMidiSongPositionPointerMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4ca50c56_ec5e_4ae4_a115_88dc57cc2b79); } impl ::windows::core::RuntimeName for MidiSongPositionPointerMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiSongPositionPointerMessage"; } impl ::core::convert::From<MidiSongPositionPointerMessage> for ::windows::core::IUnknown { fn from(value: MidiSongPositionPointerMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiSongPositionPointerMessage> for ::windows::core::IUnknown { fn from(value: &MidiSongPositionPointerMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiSongPositionPointerMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiSongPositionPointerMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiSongPositionPointerMessage> for ::windows::core::IInspectable { fn from(value: MidiSongPositionPointerMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiSongPositionPointerMessage> for ::windows::core::IInspectable { fn from(value: &MidiSongPositionPointerMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiSongPositionPointerMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiSongPositionPointerMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiSongPositionPointerMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiSongPositionPointerMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiSongPositionPointerMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiSongPositionPointerMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiSongPositionPointerMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiSongPositionPointerMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiSongPositionPointerMessage {} unsafe impl ::core::marker::Sync for MidiSongPositionPointerMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiSongSelectMessage(pub ::windows::core::IInspectable); impl MidiSongSelectMessage { pub fn Song(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiSongSelectMessage(song: u8) -> ::windows::core::Result<MidiSongSelectMessage> { Self::IMidiSongSelectMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), song, &mut result__).from_abi::<MidiSongSelectMessage>(result__) }) } pub fn IMidiSongSelectMessageFactory<R, F: FnOnce(&IMidiSongSelectMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiSongSelectMessage, IMidiSongSelectMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiSongSelectMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiSongSelectMessage;{49f0f27f-6d83-4741-a5bf-4629f6be974f})"); } unsafe impl ::windows::core::Interface for MidiSongSelectMessage { type Vtable = IMidiSongSelectMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49f0f27f_6d83_4741_a5bf_4629f6be974f); } impl ::windows::core::RuntimeName for MidiSongSelectMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiSongSelectMessage"; } impl ::core::convert::From<MidiSongSelectMessage> for ::windows::core::IUnknown { fn from(value: MidiSongSelectMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiSongSelectMessage> for ::windows::core::IUnknown { fn from(value: &MidiSongSelectMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiSongSelectMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiSongSelectMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiSongSelectMessage> for ::windows::core::IInspectable { fn from(value: MidiSongSelectMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiSongSelectMessage> for ::windows::core::IInspectable { fn from(value: &MidiSongSelectMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiSongSelectMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiSongSelectMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiSongSelectMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiSongSelectMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiSongSelectMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiSongSelectMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiSongSelectMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiSongSelectMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiSongSelectMessage {} unsafe impl ::core::marker::Sync for MidiSongSelectMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiStartMessage(pub ::windows::core::IInspectable); impl MidiStartMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiStartMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiStartMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiStartMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiStartMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiStartMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiStartMessage"; } impl ::core::convert::From<MidiStartMessage> for ::windows::core::IUnknown { fn from(value: MidiStartMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiStartMessage> for ::windows::core::IUnknown { fn from(value: &MidiStartMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiStartMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiStartMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiStartMessage> for ::windows::core::IInspectable { fn from(value: MidiStartMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiStartMessage> for ::windows::core::IInspectable { fn from(value: &MidiStartMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiStartMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiStartMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiStartMessage> for IMidiMessage { fn from(value: MidiStartMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiStartMessage> for IMidiMessage { fn from(value: &MidiStartMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiStartMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiStartMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiStartMessage {} unsafe impl ::core::marker::Sync for MidiStartMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiStopMessage(pub ::windows::core::IInspectable); impl MidiStopMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiStopMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiStopMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiStopMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiStopMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiStopMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiStopMessage"; } impl ::core::convert::From<MidiStopMessage> for ::windows::core::IUnknown { fn from(value: MidiStopMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiStopMessage> for ::windows::core::IUnknown { fn from(value: &MidiStopMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiStopMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiStopMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiStopMessage> for ::windows::core::IInspectable { fn from(value: MidiStopMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiStopMessage> for ::windows::core::IInspectable { fn from(value: &MidiStopMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiStopMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiStopMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiStopMessage> for IMidiMessage { fn from(value: MidiStopMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiStopMessage> for IMidiMessage { fn from(value: &MidiStopMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiStopMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiStopMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiStopMessage {} unsafe impl ::core::marker::Sync for MidiStopMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiSynthesizer(pub ::windows::core::IInspectable); impl MidiSynthesizer { #[cfg(feature = "Devices_Enumeration")] pub fn AudioDevice(&self) -> ::windows::core::Result<super::Enumeration::DeviceInformation> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Enumeration::DeviceInformation>(result__) } } pub fn Volume(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn SetVolume(&self, value: f64) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn SendMessage<'a, Param0: ::windows::core::IntoParam<'a, IMidiMessage>>(&self, midimessage: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IMidiOutPort>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), midimessage.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn SendBuffer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(&self, mididata: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IMidiOutPort>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), mididata.into_param().abi()).ok() } } pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IMidiOutPort>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn CreateAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MidiSynthesizer>> { Self::IMidiSynthesizerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MidiSynthesizer>>(result__) }) } #[cfg(all(feature = "Devices_Enumeration", feature = "Foundation"))] pub fn CreateFromAudioDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, super::Enumeration::DeviceInformation>>(audiodevice: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MidiSynthesizer>> { Self::IMidiSynthesizerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), audiodevice.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MidiSynthesizer>>(result__) }) } #[cfg(feature = "Devices_Enumeration")] pub fn IsSynthesizer<'a, Param0: ::windows::core::IntoParam<'a, super::Enumeration::DeviceInformation>>(mididevice: Param0) -> ::windows::core::Result<bool> { Self::IMidiSynthesizerStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), mididevice.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn IMidiSynthesizerStatics<R, F: FnOnce(&IMidiSynthesizerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiSynthesizer, IMidiSynthesizerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiSynthesizer { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiSynthesizer;{f0da155e-db90-405f-b8ae-21d2e17f2e45})"); } unsafe impl ::windows::core::Interface for MidiSynthesizer { type Vtable = IMidiSynthesizer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf0da155e_db90_405f_b8ae_21d2e17f2e45); } impl ::windows::core::RuntimeName for MidiSynthesizer { const NAME: &'static str = "Windows.Devices.Midi.MidiSynthesizer"; } impl ::core::convert::From<MidiSynthesizer> for ::windows::core::IUnknown { fn from(value: MidiSynthesizer) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiSynthesizer> for ::windows::core::IUnknown { fn from(value: &MidiSynthesizer) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiSynthesizer> for ::windows::core::IInspectable { fn from(value: MidiSynthesizer) -> Self { value.0 } } impl ::core::convert::From<&MidiSynthesizer> for ::windows::core::IInspectable { fn from(value: &MidiSynthesizer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiSynthesizer> for IMidiOutPort { type Error = ::windows::core::Error; fn try_from(value: MidiSynthesizer) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiSynthesizer> for IMidiOutPort { type Error = ::windows::core::Error; fn try_from(value: &MidiSynthesizer) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiOutPort> for MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, IMidiOutPort> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiOutPort> for &MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, IMidiOutPort> { ::core::convert::TryInto::<IMidiOutPort>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<MidiSynthesizer> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: MidiSynthesizer) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&MidiSynthesizer> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &MidiSynthesizer) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &MidiSynthesizer { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiSynthesizer {} unsafe impl ::core::marker::Sync for MidiSynthesizer {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiSystemExclusiveMessage(pub ::windows::core::IInspectable); impl MidiSystemExclusiveMessage { #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn CreateMidiSystemExclusiveMessage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(rawdata: Param0) -> ::windows::core::Result<MidiSystemExclusiveMessage> { Self::IMidiSystemExclusiveMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), rawdata.into_param().abi(), &mut result__).from_abi::<MidiSystemExclusiveMessage>(result__) }) } pub fn IMidiSystemExclusiveMessageFactory<R, F: FnOnce(&IMidiSystemExclusiveMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiSystemExclusiveMessage, IMidiSystemExclusiveMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiSystemExclusiveMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiSystemExclusiveMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiSystemExclusiveMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiSystemExclusiveMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiSystemExclusiveMessage"; } impl ::core::convert::From<MidiSystemExclusiveMessage> for ::windows::core::IUnknown { fn from(value: MidiSystemExclusiveMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiSystemExclusiveMessage> for ::windows::core::IUnknown { fn from(value: &MidiSystemExclusiveMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiSystemExclusiveMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiSystemExclusiveMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiSystemExclusiveMessage> for ::windows::core::IInspectable { fn from(value: MidiSystemExclusiveMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiSystemExclusiveMessage> for ::windows::core::IInspectable { fn from(value: &MidiSystemExclusiveMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiSystemExclusiveMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiSystemExclusiveMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiSystemExclusiveMessage> for IMidiMessage { fn from(value: MidiSystemExclusiveMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiSystemExclusiveMessage> for IMidiMessage { fn from(value: &MidiSystemExclusiveMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiSystemExclusiveMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiSystemExclusiveMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiSystemExclusiveMessage {} unsafe impl ::core::marker::Sync for MidiSystemExclusiveMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiSystemResetMessage(pub ::windows::core::IInspectable); impl MidiSystemResetMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiSystemResetMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiSystemResetMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiSystemResetMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiSystemResetMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiSystemResetMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiSystemResetMessage"; } impl ::core::convert::From<MidiSystemResetMessage> for ::windows::core::IUnknown { fn from(value: MidiSystemResetMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiSystemResetMessage> for ::windows::core::IUnknown { fn from(value: &MidiSystemResetMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiSystemResetMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiSystemResetMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiSystemResetMessage> for ::windows::core::IInspectable { fn from(value: MidiSystemResetMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiSystemResetMessage> for ::windows::core::IInspectable { fn from(value: &MidiSystemResetMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiSystemResetMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiSystemResetMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiSystemResetMessage> for IMidiMessage { fn from(value: MidiSystemResetMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiSystemResetMessage> for IMidiMessage { fn from(value: &MidiSystemResetMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiSystemResetMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiSystemResetMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiSystemResetMessage {} unsafe impl ::core::marker::Sync for MidiSystemResetMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiTimeCodeMessage(pub ::windows::core::IInspectable); impl MidiTimeCodeMessage { pub fn FrameType(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn Values(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = &::windows::core::Interface::cast::<IMidiMessage>(self)?; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } pub fn CreateMidiTimeCodeMessage(frametype: u8, values: u8) -> ::windows::core::Result<MidiTimeCodeMessage> { Self::IMidiTimeCodeMessageFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), frametype, values, &mut result__).from_abi::<MidiTimeCodeMessage>(result__) }) } pub fn IMidiTimeCodeMessageFactory<R, F: FnOnce(&IMidiTimeCodeMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiTimeCodeMessage, IMidiTimeCodeMessageFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MidiTimeCodeMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiTimeCodeMessage;{0bf7087d-fa63-4a1c-8deb-c0e87796a6d7})"); } unsafe impl ::windows::core::Interface for MidiTimeCodeMessage { type Vtable = IMidiTimeCodeMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0bf7087d_fa63_4a1c_8deb_c0e87796a6d7); } impl ::windows::core::RuntimeName for MidiTimeCodeMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiTimeCodeMessage"; } impl ::core::convert::From<MidiTimeCodeMessage> for ::windows::core::IUnknown { fn from(value: MidiTimeCodeMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiTimeCodeMessage> for ::windows::core::IUnknown { fn from(value: &MidiTimeCodeMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiTimeCodeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiTimeCodeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiTimeCodeMessage> for ::windows::core::IInspectable { fn from(value: MidiTimeCodeMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiTimeCodeMessage> for ::windows::core::IInspectable { fn from(value: &MidiTimeCodeMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiTimeCodeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiTimeCodeMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<MidiTimeCodeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: MidiTimeCodeMessage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&MidiTimeCodeMessage> for IMidiMessage { type Error = ::windows::core::Error; fn try_from(value: &MidiTimeCodeMessage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiTimeCodeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiTimeCodeMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::core::convert::TryInto::<IMidiMessage>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for MidiTimeCodeMessage {} unsafe impl ::core::marker::Sync for MidiTimeCodeMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiTimingClockMessage(pub ::windows::core::IInspectable); impl MidiTimingClockMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiTimingClockMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiTimingClockMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiTimingClockMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiTimingClockMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiTimingClockMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiTimingClockMessage"; } impl ::core::convert::From<MidiTimingClockMessage> for ::windows::core::IUnknown { fn from(value: MidiTimingClockMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiTimingClockMessage> for ::windows::core::IUnknown { fn from(value: &MidiTimingClockMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiTimingClockMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiTimingClockMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiTimingClockMessage> for ::windows::core::IInspectable { fn from(value: MidiTimingClockMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiTimingClockMessage> for ::windows::core::IInspectable { fn from(value: &MidiTimingClockMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiTimingClockMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiTimingClockMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiTimingClockMessage> for IMidiMessage { fn from(value: MidiTimingClockMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiTimingClockMessage> for IMidiMessage { fn from(value: &MidiTimingClockMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiTimingClockMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiTimingClockMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiTimingClockMessage {} unsafe impl ::core::marker::Sync for MidiTimingClockMessage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MidiTuneRequestMessage(pub ::windows::core::IInspectable); impl MidiTuneRequestMessage { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MidiTuneRequestMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn RawData(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__) } } pub fn Type(&self) -> ::windows::core::Result<MidiMessageType> { let this = self; unsafe { let mut result__: MidiMessageType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MidiMessageType>(result__) } } } unsafe impl ::windows::core::RuntimeType for MidiTuneRequestMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Midi.MidiTuneRequestMessage;{79767945-1094-4283-9be0-289fc0ee8334})"); } unsafe impl ::windows::core::Interface for MidiTuneRequestMessage { type Vtable = IMidiMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79767945_1094_4283_9be0_289fc0ee8334); } impl ::windows::core::RuntimeName for MidiTuneRequestMessage { const NAME: &'static str = "Windows.Devices.Midi.MidiTuneRequestMessage"; } impl ::core::convert::From<MidiTuneRequestMessage> for ::windows::core::IUnknown { fn from(value: MidiTuneRequestMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&MidiTuneRequestMessage> for ::windows::core::IUnknown { fn from(value: &MidiTuneRequestMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MidiTuneRequestMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MidiTuneRequestMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MidiTuneRequestMessage> for ::windows::core::IInspectable { fn from(value: MidiTuneRequestMessage) -> Self { value.0 } } impl ::core::convert::From<&MidiTuneRequestMessage> for ::windows::core::IInspectable { fn from(value: &MidiTuneRequestMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MidiTuneRequestMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MidiTuneRequestMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<MidiTuneRequestMessage> for IMidiMessage { fn from(value: MidiTuneRequestMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&MidiTuneRequestMessage> for IMidiMessage { fn from(value: &MidiTuneRequestMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for MidiTuneRequestMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMidiMessage> for &MidiTuneRequestMessage { fn into_param(self) -> ::windows::core::Param<'a, IMidiMessage> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for MidiTuneRequestMessage {} unsafe impl ::core::marker::Sync for MidiTuneRequestMessage {}
use binary_search::BinarySearch; use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let (n, m) = scan!((usize, usize)); let h = scan!(u64; n); let w = scan!(u64; m); let mut h = h; h.sort(); let mut left = vec![0; n + 1]; for i in (2..=n).step_by(2) { left[i] = left[i - 2] + (h[i - 1] - h[i - 2]); } let mut right = vec![0; n + 1]; for i in (1..(n - 1)).rev() { right[i] = right[i + 2] + (h[i + 1] - h[i]); } let mut ans = std::u64::MAX; for w in w { let i = h.lower_bound(&w); if i == 0 { ans = ans.min((h[0] - w) + right[1]); } else if i == n { ans = ans.min((w - h[n - 1]) + left[n - 1]); } else if i % 2 == 1 { ans = ans.min(absolute(w, h[i - 1]) + left[i - 1] + right[i]); } else { ans = ans.min(absolute(w, h[i]) + left[i] + right[i + 1]); } } println!("{}", ans); } fn absolute(a: u64, b: u64) -> u64 { a.max(b) - a.min(b) }
struct Foo<'a> { x: &'a i32 } impl<'a> Foo<'a> { fn x(&self) -> &'a i32 { self.x } } fn main() { let a = 5; let _y = double(a); println!("{}", a); let b = true; // _y = change_truth(b) will fail // _y = double(10) will fail either // but let _y = change_truth(b) will success let _y = change_truth(b); println!("{}", b); let v1 = vec![1,2,3]; let v2 = vec![1,2,3]; let (v1, v2, answer) = foo(v1, v2); let answer = foo_ref(&v1, &v2); let y = &5; let f = Foo {x: y}; println!("{}", f.x); } fn double(x: i32) -> i32 { x * 2 } fn change_truth(x: bool) -> bool { !x } fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>,Vec<i32>,i32) { (v1, v2, 42) } fn foo_ref(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 { 42 }
use crate::cairo::ext_py; use crate::gas_price; use crate::SyncState; use pathfinder_common::ChainId; use pathfinder_storage::Storage; use starknet_gateway_types::pending::PendingData; use std::sync::Arc; type SequencerClient = starknet_gateway_client::Client; #[derive(Copy, Clone, Default)] pub enum RpcVersion { #[default] Undefined, V01, V02, V03, V04, } impl RpcVersion { fn parse(s: &str) -> Self { match s { "v0.1" => Self::V01, "v0.2" => Self::V02, "v0.3" => Self::V03, "v0.4" => Self::V04, _ => Self::default(), } } } #[derive(Clone)] pub struct RpcContext { pub storage: Storage, pub pending_data: Option<PendingData>, pub sync_status: Arc<SyncState>, pub chain_id: ChainId, pub call_handle: Option<ext_py::Handle>, pub eth_gas_price: Option<gas_price::Cached>, pub sequencer: SequencerClient, pub version: RpcVersion, } impl RpcContext { pub fn new( storage: Storage, sync_status: Arc<SyncState>, chain_id: ChainId, sequencer: SequencerClient, ) -> Self { Self { storage, sync_status, chain_id, pending_data: None, call_handle: None, eth_gas_price: None, sequencer, version: RpcVersion::default(), } } pub(crate) fn with_version(self, version: &str) -> Self { Self { version: RpcVersion::parse(version), ..self } } pub fn for_tests() -> Self { Self::for_tests_on(pathfinder_common::Chain::Testnet) } pub fn for_tests_on(chain: pathfinder_common::Chain) -> Self { assert_ne!(chain, Chain::Mainnet, "Testing on MainNet?"); use pathfinder_common::Chain; let (chain_id, sequencer) = match chain { Chain::Mainnet => (ChainId::MAINNET, SequencerClient::mainnet()), Chain::Testnet => (ChainId::TESTNET, SequencerClient::testnet()), Chain::Integration => (ChainId::INTEGRATION, SequencerClient::integration()), Chain::Testnet2 => (ChainId::TESTNET2, SequencerClient::testnet2()), Chain::Custom => unreachable!("Should not be testing with custom chain"), }; let storage = super::test_utils::setup_storage(); let sync_state = Arc::new(SyncState::default()); Self::new( storage, sync_state, chain_id, sequencer.disable_retry_for_tests(), ) } pub fn with_storage(self, storage: Storage) -> Self { Self { storage, ..self } } pub fn with_pending_data(self, pending_data: PendingData) -> Self { Self { pending_data: Some(pending_data), ..self } } pub async fn for_tests_with_pending() -> Self { // This is a bit silly with the arc in and out, but since its for tests the ergonomics of // having Arc also constructed is nice. let context = Self::for_tests(); let pending_data = super::test_utils::create_pending_data(context.storage.clone()).await; context.with_pending_data(pending_data) } pub fn with_call_handling(self, call_handle: ext_py::Handle) -> Self { Self { call_handle: Some(call_handle), ..self } } pub fn with_eth_gas_price(self, gas_price: gas_price::Cached) -> Self { Self { eth_gas_price: Some(gas_price), ..self } } }