text
stringlengths
8
4.13M
use simple_pdf::{graphics, Page, PDF}; use std::fs::File; fn main() -> std::io::Result<()> { let mut pdf = PDF::from_file(File::create("simple")?); let mut page = Page::new(); // Page builder page.add( graphics::Path::from((10f64, 10f64)) .line_to((200f64, 200f64)) .rect((10f64, 10f64, 190f64, 190f64)) .stroke(graphics::Color::red()), ); pdf.add_page(page); pdf.write() }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_meta_types::protobuf::raft_service_client::RaftServiceClient; use common_meta_types::Endpoint; use common_meta_types::NodeId; use common_metrics::counter; use tonic::transport::channel::Channel; use tracing::debug; use crate::metrics::raft_metrics; /// A metrics reporter of active raft peers. pub struct PeerCounter { target: NodeId, endpoint: Endpoint, endpoint_str: String, } impl counter::Count for PeerCounter { fn incr_count(&mut self, n: i64) { raft_metrics::network::incr_active_peers(&self.target, &self.endpoint_str, n) } } /// RaftClient is a grpc client bound with a metrics reporter.. pub type RaftClient = counter::WithCount<PeerCounter, RaftServiceClient<Channel>>; /// Defines the API of the client to a raft node. pub trait RaftClientApi { fn new(target: NodeId, endpoint: Endpoint, channel: Channel) -> Self; fn endpoint(&self) -> &Endpoint; } impl RaftClientApi for RaftClient { fn new(target: NodeId, endpoint: Endpoint, channel: Channel) -> Self { let endpoint_str = endpoint.to_string(); debug!( "RaftClient::new: target: {} endpoint: {}", target, endpoint_str ); counter::WithCount::new(RaftServiceClient::new(channel), PeerCounter { target, endpoint, endpoint_str, }) } fn endpoint(&self) -> &Endpoint { &self.counter().endpoint } }
use super::socket::UdpSocket; use std::io; use std::net::SocketAddr; use futures::{Async, Future, Poll}; /// A future used to receive a datagram from a UDP socket. /// /// This is created by the `UdpSocket::recv_dgram` method. #[must_use = "futures do nothing unless polled"] #[derive(Debug)] pub struct RecvDgram<T> { /// None means future was completed state: Option<RecvDgramInner<T>> } /// A struct is used to represent the full info of RecvDgram. #[derive(Debug)] struct RecvDgramInner<T> { /// Rx socket socket: UdpSocket, /// The received data will be put in the buffer buffer: T } /// Components of a `RecvDgram` future, returned from `into_parts`. #[derive(Debug)] pub struct Parts<T> { /// The socket pub socket: UdpSocket, /// The buffer pub buffer: T, _priv: () } impl<T> RecvDgram<T> { /// Create a new future to receive UDP Datagram pub(crate) fn new(socket: UdpSocket, buffer: T) -> RecvDgram<T> { let inner = RecvDgramInner { socket: socket, buffer: buffer }; RecvDgram { state: Some(inner) } } /// Consume the `RecvDgram`, returning the socket and buffer. /// /// ``` /// # extern crate tokio_udp; /// /// use tokio_udp::UdpSocket; /// /// # pub fn main() { /// /// let socket = UdpSocket::bind(&([127, 0, 0, 1], 0).into()).unwrap(); /// let mut buffer = vec![0; 4096]; /// /// let future = socket.recv_dgram(buffer); /// /// // ... polling `future` ... giving up (e.g. after timeout) /// /// let parts = future.into_parts(); /// /// let socket = parts.socket; // extract the socket /// let buffer = parts.buffer; // extract the buffer /// /// # } /// ``` /// # Panics /// /// If called after the future has completed. pub fn into_parts(mut self) -> Parts<T> { let state = self.state .take() .expect("into_parts called after completion"); Parts { socket: state.socket, buffer: state.buffer, _priv: () } } } impl<T> Future for RecvDgram<T> where T: AsMut<[u8]>, { type Item = (UdpSocket, T, usize, SocketAddr); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { let (n, addr) = { let ref mut inner = self.state.as_mut().expect("RecvDgram polled after completion"); try_ready!(inner.socket.poll_recv_from(inner.buffer.as_mut())) }; let inner = self.state.take().unwrap(); Ok(Async::Ready((inner.socket, inner.buffer, n, addr))) } }
// Copyright 2020-2021 the Deno authors. All rights reserved. MIT license. use super::{Context, LintRule, ProgramRef, DUMMY_NODE}; use derive_more::Display; use once_cell::sync::Lazy; use regex::{Matches, Regex}; use swc_common::{hygiene::SyntaxContext, BytePos, Span}; use swc_ecmascript::ast::Str; use swc_ecmascript::visit::Node; use swc_ecmascript::visit::Visit; pub struct NoIrregularWhitespace; const CODE: &str = "no-irregular-whitespace"; const HINT: &str = "Change to a normal space or tab"; #[derive(Display)] enum NoIrregularWhitespaceMessage { #[display(fmt = "Irregular whitespace not allowed.")] NotAllowed, } static IRREGULAR_WHITESPACE: Lazy<Regex> = Lazy::new(|| { Regex::new(r"[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+").unwrap() }); static IRREGULAR_LINE_TERMINATORS: Lazy<Regex> = Lazy::new(|| Regex::new(r"[\u2028\u2029]").unwrap()); fn test_for_whitespace(value: &str) -> Option<Vec<Matches>> { let mut matches_vector: Vec<Matches> = vec![]; if IRREGULAR_WHITESPACE.is_match(value) { let matches = IRREGULAR_WHITESPACE.find_iter(value); matches_vector.push(matches); } if IRREGULAR_LINE_TERMINATORS.is_match(value) { let matches = IRREGULAR_LINE_TERMINATORS.find_iter(value); matches_vector.push(matches); } if !matches_vector.is_empty() { Some(matches_vector) } else { None } } impl LintRule for NoIrregularWhitespace { fn new() -> Box<Self> { Box::new(NoIrregularWhitespace) } fn tags(&self) -> &'static [&'static str] { &["recommended"] } fn code(&self) -> &'static str { CODE } fn lint_program<'view>( &self, context: &mut Context<'view>, program: ProgramRef<'view>, ) { let mut visitor = NoIrregularWhitespaceVisitor::default(); match program { ProgramRef::Module(m) => visitor.visit_module(m, &DUMMY_NODE), ProgramRef::Script(s) => visitor.visit_script(s, &DUMMY_NODE), } let excluded_ranges = visitor.ranges.iter(); let span = match program { ProgramRef::Module(m) => m.span, ProgramRef::Script(s) => s.span, }; let file_and_lines = context.source_map().span_to_lines(span).unwrap(); let file = file_and_lines.file; for line_index in 0..file.count_lines() { let line = file.get_line(line_index).unwrap(); let (byte_pos, _hi) = file.line_bounds(line_index); if let Some(whitespace_results) = test_for_whitespace(&line) { for whitespace_matches in whitespace_results.into_iter() { for whitespace_match in whitespace_matches { let range = whitespace_match.range(); let span = Span::new( byte_pos + BytePos(range.start as u32), byte_pos + BytePos(range.end as u32), SyntaxContext::empty(), ); let is_excluded = excluded_ranges.clone().any(|range| range.contains(span)); if !is_excluded { context.add_diagnostic_with_hint( span, CODE, NoIrregularWhitespaceMessage::NotAllowed, HINT, ); } } } } } } #[cfg(feature = "docs")] fn docs(&self) -> &'static str { include_str!("../../docs/rules/no_irregular_whitespace.md") } } struct NoIrregularWhitespaceVisitor { ranges: Vec<Span>, } impl NoIrregularWhitespaceVisitor { fn default() -> Self { Self { ranges: vec![] } } } impl Visit for NoIrregularWhitespaceVisitor { fn visit_str(&mut self, string_literal: &Str, _parent: &dyn Node) { self.ranges.push(string_literal.span); } } #[cfg(test)] mod tests { use super::*; #[test] fn no_irregular_whitespace_valid() { assert_lint_ok! { NoIrregularWhitespace, "'\\u{000B}';", "'\\u{000C}';", "'\\u{0085}';", "'\\u{00A0}';", "'\\u{180E}';", "'\\u{feff}';", "'\\u{2000}';", "'\\u{2001}';", "'\\u{2002}';", "'\\u{2003}';", "'\\u{2004}';", "'\\u{2005}';", "'\\u{2006}';", "'\\u{2007}';", "'\\u{2008}';", "'\\u{2009}';", "'\\u{200A}';", "'\\u{200B}';", "'\\u{2028}';", "'\\u{2029}';", "'\\u{202F}';", "'\\u{205f}';", "'\\u{3000}';", "'\u{000B}';", "'\u{000C}';", "'\u{0085}';", "'\u{00A0}';", "'\u{180E}';", "'\u{feff}';", "'\u{2000}';", "'\u{2001}';", "'\u{2002}';", "'\u{2003}';", "'\u{2004}';", "'\u{2005}';", "'\u{2006}';", "'\u{2007}';", "'\u{2008}';", "'\u{2009}';", "'\u{200A}';", "'\u{200B}';", "'\\\u{2028}';", "'\\\u{2029}';", "'\u{202F}';", "'\u{205f}';", "'\u{3000}';", }; } #[test] fn no_irregular_whitespace_invalid() { assert_lint_err! { NoIrregularWhitespace, "var any \u{000B} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{000C} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{00A0} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{feff} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2000} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2001} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2002} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2003} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2004} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2005} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2006} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2007} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2008} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2009} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{200A} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2028} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{2029} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{202F} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{205f} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{3000} = 'thing';": [ { col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var a = 'b',\u{2028}c = 'd',\ne = 'f'\u{2028}": [ { line: 1, col: 12, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, }, { line: 2, col: 7, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ], "var any \u{3000} = 'thing', other \u{3000} = 'thing';\nvar third \u{3000} = 'thing';": [ { line: 1, col: 8, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, }, { line: 1, col: 27, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, }, { line: 2, col: 10, message: NoIrregularWhitespaceMessage::NotAllowed, hint: HINT, } ] }; } }
//! Contains starknet transaction related code and __not__ database transaction. use anyhow::Context; use pathfinder_common::{BlockHash, BlockNumber, TransactionHash}; use starknet_gateway_types::reply::transaction as gateway; use crate::{prelude::*, BlockId}; pub enum TransactionStatus { L1Accepted, L2Accepted, } pub(super) fn insert_transactions( tx: &Transaction<'_>, block_hash: BlockHash, block_number: BlockNumber, transaction_data: &[(gateway::Transaction, gateway::Receipt)], ) -> anyhow::Result<()> { if transaction_data.is_empty() { return Ok(()); } let mut compressor = zstd::bulk::Compressor::new(10).context("Create zstd compressor")?; for (i, (transaction, receipt)) in transaction_data.iter().enumerate() { // Serialize and compress transaction data. let tx_data = serde_json::to_vec(&transaction).context("Serializing transaction")?; let tx_data = compressor .compress(&tx_data) .context("Compressing transaction")?; let serialized_receipt = serde_json::to_vec(&receipt).context("Serializing receipt")?; let serialized_receipt = compressor .compress(&serialized_receipt) .context("Compressing receipt")?; let execution_status = match receipt.execution_status { gateway::ExecutionStatus::Succeeded => 0, gateway::ExecutionStatus::Reverted => 1, }; tx.inner().execute(r"INSERT OR REPLACE INTO starknet_transactions (hash, idx, block_hash, tx, receipt, execution_status) VALUES (:hash, :idx, :block_hash, :tx, :receipt, :execution_status)", named_params![ ":hash": &transaction.hash(), ":idx": &i.try_into_sql_int()?, ":block_hash": &block_hash, ":tx": &tx_data, ":receipt": &serialized_receipt, ":execution_status": &execution_status, ]).context("Inserting transaction data")?; // insert events from receipt super::event::insert_events(tx, block_number, receipt.transaction_hash, &receipt.events) .context("Inserting events")?; } Ok(()) } pub(super) fn transaction( tx: &Transaction<'_>, transaction: TransactionHash, ) -> anyhow::Result<Option<gateway::Transaction>> { let mut stmt = tx .inner() .prepare("SELECT tx FROM starknet_transactions WHERE hash = ?") .context("Preparing statement")?; let mut rows = stmt .query(params![&transaction]) .context("Executing query")?; let row = match rows.next()? { Some(row) => row, None => return Ok(None), }; let transaction = row.get_ref_unwrap(0).as_blob()?; let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?; let transaction = serde_json::from_slice(&transaction).context("Deserializing transaction")?; Ok(Some(transaction)) } pub(super) fn transaction_with_receipt( tx: &Transaction<'_>, txn_hash: TransactionHash, ) -> anyhow::Result<Option<(gateway::Transaction, gateway::Receipt, BlockHash)>> { let mut stmt = tx .inner() .prepare("SELECT tx, receipt, block_hash FROM starknet_transactions WHERE hash = ?1") .context("Preparing statement")?; let mut rows = stmt.query(params![&txn_hash]).context("Executing query")?; let row = match rows.next()? { Some(row) => row, None => return Ok(None), }; let transaction = row.get_ref_unwrap("tx").as_blob()?; let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?; let transaction = serde_json::from_slice(&transaction).context("Deserializing transaction")?; let receipt = match row.get_ref_unwrap("receipt").as_blob_or_null()? { Some(data) => data, None => return Ok(None), }; let receipt = zstd::decode_all(receipt).context("Decompressing receipt")?; let receipt = serde_json::from_slice(&receipt).context("Deserializing receipt")?; let block_hash = row.get_block_hash("block_hash")?; Ok(Some((transaction, receipt, block_hash))) } pub(super) fn transaction_at_block( tx: &Transaction<'_>, block: BlockId, index: usize, ) -> anyhow::Result<Option<gateway::Transaction>> { // Identify block hash let Some((_, block_hash)) = tx.block_id(block)? else { return Ok(None); }; let mut stmt = tx .inner() .prepare("SELECT tx FROM starknet_transactions WHERE block_hash = ? AND idx = ?") .context("Preparing statement")?; let mut rows = stmt .query(params![&block_hash, &index.try_into_sql_int()?]) .context("Executing query")?; let row = match rows.next()? { Some(row) => row, None => return Ok(None), }; let transaction = match row.get_ref_unwrap(0).as_blob_or_null()? { Some(data) => data, None => return Ok(None), }; let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?; let transaction = serde_json::from_slice(&transaction).context("Deserializing transaction")?; Ok(Some(transaction)) } pub(super) fn transaction_count(tx: &Transaction<'_>, block: BlockId) -> anyhow::Result<usize> { match block { BlockId::Number(number) => tx .inner() .query_row( "SELECT COUNT(*) FROM starknet_transactions JOIN block_headers ON starknet_transactions.block_hash = block_headers.hash WHERE number = ?1", params![&number], |row| row.get(0), ) .context("Counting transactions"), BlockId::Hash(hash) => tx .inner() .query_row( "SELECT COUNT(*) FROM starknet_transactions WHERE block_hash = ?1", params![&hash], |row| row.get(0), ) .context("Counting transactions"), BlockId::Latest => { // First get the latest block let block = match tx.block_id(BlockId::Latest)? { Some((number, _)) => number, None => return Ok(0), }; transaction_count(tx, block.into()) } } } pub(super) fn transaction_data_for_block( tx: &Transaction<'_>, block: BlockId, ) -> anyhow::Result<Option<Vec<(gateway::Transaction, gateway::Receipt)>>> { let Some((_, block_hash)) = tx.block_id(block)? else { return Ok(None); }; let mut stmt = tx .inner() .prepare( "SELECT tx, receipt FROM starknet_transactions WHERE block_hash = ? ORDER BY idx ASC", ) .context("Preparing statement")?; let mut rows = stmt .query(params![&block_hash]) .context("Executing query")?; let mut data = Vec::new(); while let Some(row) = rows.next()? { let receipt = row .get_ref_unwrap("receipt") .as_blob_or_null()? .context("Receipt data missing")?; let receipt = zstd::decode_all(receipt).context("Decompressing transaction receipt")?; let receipt = serde_json::from_slice(&receipt).context("Deserializing transaction receipt")?; let transaction = row .get_ref_unwrap("tx") .as_blob_or_null()? .context("Transaction data missing")?; let transaction = zstd::decode_all(transaction).context("Decompressing transaction")?; let transaction = serde_json::from_slice(&transaction).context("Deserializing transaction")?; data.push((transaction, receipt)); } Ok(Some(data)) } pub(super) fn transaction_block_hash( tx: &Transaction<'_>, hash: TransactionHash, ) -> anyhow::Result<Option<BlockHash>> { tx.inner() .query_row( "SELECT block_hash FROM starknet_transactions WHERE hash = ?", params![&hash], |row| row.get_block_hash(0), ) .optional() .map_err(|e| e.into()) } #[cfg(test)] mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{BlockHeader, TransactionIndex, TransactionVersion}; use starknet_gateway_types::reply::transaction::{ DeclareTransactionV0V1, DeclareTransactionV2, DeployAccountTransaction, DeployTransaction, InvokeTransactionV0, InvokeTransactionV1, }; use super::*; fn setup() -> ( crate::Connection, BlockHeader, Vec<(gateway::Transaction, gateway::Receipt)>, ) { let header = BlockHeader::builder().finalize_with_hash(block_hash_bytes!(b"block hash")); // Create one of each transaction type. let transactions = vec![ gateway::Transaction::Declare(gateway::DeclareTransaction::V0( DeclareTransactionV0V1 { class_hash: class_hash_bytes!(b"declare v0 class hash"), max_fee: fee_bytes!(b"declare v0 max fee"), nonce: transaction_nonce_bytes!(b"declare v0 tx nonce"), sender_address: contract_address_bytes!(b"declare v0 contract address"), signature: vec![ transaction_signature_elem_bytes!(b"declare v0 tx sig 0"), transaction_signature_elem_bytes!(b"declare v0 tx sig 1"), ], transaction_hash: transaction_hash_bytes!(b"declare v0 tx hash"), }, )), gateway::Transaction::Declare(gateway::DeclareTransaction::V1( DeclareTransactionV0V1 { class_hash: class_hash_bytes!(b"declare v1 class hash"), max_fee: fee_bytes!(b"declare v1 max fee"), nonce: transaction_nonce_bytes!(b"declare v1 tx nonce"), sender_address: contract_address_bytes!(b"declare v1 contract address"), signature: vec![ transaction_signature_elem_bytes!(b"declare v1 tx sig 0"), transaction_signature_elem_bytes!(b"declare v1 tx sig 1"), ], transaction_hash: transaction_hash_bytes!(b"declare v1 tx hash"), }, )), gateway::Transaction::Declare(gateway::DeclareTransaction::V2(DeclareTransactionV2 { class_hash: class_hash_bytes!(b"declare v2 class hash"), max_fee: fee_bytes!(b"declare v2 max fee"), nonce: transaction_nonce_bytes!(b"declare v2 tx nonce"), sender_address: contract_address_bytes!(b"declare v2 contract address"), signature: vec![ transaction_signature_elem_bytes!(b"declare v2 tx sig 0"), transaction_signature_elem_bytes!(b"declare v2 tx sig 1"), ], transaction_hash: transaction_hash_bytes!(b"declare v2 tx hash"), compiled_class_hash: casm_hash_bytes!(b"declare v2 casm hash"), })), gateway::Transaction::Deploy(DeployTransaction { contract_address: contract_address_bytes!(b"deploy contract address"), contract_address_salt: contract_address_salt_bytes!( b"deploy contract address salt" ), class_hash: class_hash_bytes!(b"deploy class hash"), constructor_calldata: vec![ constructor_param_bytes!(b"deploy call data 0"), constructor_param_bytes!(b"deploy call data 1"), ], transaction_hash: transaction_hash_bytes!(b"deploy tx hash"), version: TransactionVersion::ZERO, }), gateway::Transaction::DeployAccount(DeployAccountTransaction { contract_address: contract_address_bytes!(b"deploy account contract address"), transaction_hash: transaction_hash_bytes!(b"deploy account tx hash"), max_fee: fee_bytes!(b"deploy account max fee"), version: TransactionVersion::ZERO, signature: vec![ transaction_signature_elem_bytes!(b"deploy account tx sig 0"), transaction_signature_elem_bytes!(b"deploy account tx sig 1"), ], nonce: transaction_nonce_bytes!(b"deploy account tx nonce"), contract_address_salt: contract_address_salt_bytes!(b"deploy account address salt"), constructor_calldata: vec![ call_param_bytes!(b"deploy account call data 0"), call_param_bytes!(b"deploy account call data 1"), ], class_hash: class_hash_bytes!(b"deploy account class hash"), }), gateway::Transaction::Invoke(gateway::InvokeTransaction::V0(InvokeTransactionV0 { calldata: vec![ call_param_bytes!(b"invoke v0 call data 0"), call_param_bytes!(b"invoke v0 call data 1"), ], sender_address: contract_address_bytes!(b"invoke v0 contract address"), entry_point_selector: entry_point_bytes!(b"invoke v0 entry point"), entry_point_type: None, max_fee: fee_bytes!(b"invoke v0 max fee"), signature: vec![ transaction_signature_elem_bytes!(b"invoke v0 tx sig 0"), transaction_signature_elem_bytes!(b"invoke v0 tx sig 1"), ], transaction_hash: transaction_hash_bytes!(b"invoke v0 tx hash"), })), gateway::Transaction::Invoke(gateway::InvokeTransaction::V1(InvokeTransactionV1 { calldata: vec![ call_param_bytes!(b"invoke v1 call data 0"), call_param_bytes!(b"invoke v1 call data 1"), ], sender_address: contract_address_bytes!(b"invoke v1 contract address"), max_fee: fee_bytes!(b"invoke v1 max fee"), signature: vec![ transaction_signature_elem_bytes!(b"invoke v1 tx sig 0"), transaction_signature_elem_bytes!(b"invoke v1 tx sig 1"), ], nonce: transaction_nonce_bytes!(b"invoke v1 tx nonce"), transaction_hash: transaction_hash_bytes!(b"invoke v1 tx hash"), })), gateway::Transaction::L1Handler(gateway::L1HandlerTransaction { contract_address: contract_address_bytes!(b"L1 handler contract address"), entry_point_selector: entry_point_bytes!(b"L1 handler entry point"), nonce: transaction_nonce_bytes!(b"L1 handler tx nonce"), calldata: vec![ call_param_bytes!(b"L1 handler call data 0"), call_param_bytes!(b"L1 handler call data 1"), ], transaction_hash: transaction_hash_bytes!(b"L1 handler tx hash"), version: TransactionVersion::ZERO, }), ]; // Generate a random receipt for each transaction. Note that these won't make physical sense // but its enough for the tests. let receipts: Vec<gateway::Receipt> = transactions .iter() .enumerate() .map(|(i, t)| gateway::Receipt { actual_fee: None, events: vec![], execution_resources: None, l1_to_l2_consumed_message: None, l2_to_l1_messages: vec![], transaction_hash: t.hash(), transaction_index: TransactionIndex::new_or_panic(i as u64), execution_status: Default::default(), revert_error: Default::default(), }) .collect(); assert_eq!(transactions.len(), receipts.len()); let body = transactions .into_iter() .zip(receipts.into_iter()) .map(|(t, r)| (t, r)) .collect::<Vec<_>>(); let mut db = crate::Storage::in_memory().unwrap().connection().unwrap(); let db_tx = db.transaction().unwrap(); db_tx.insert_block_header(&header).unwrap(); db_tx .insert_transaction_data(header.hash, header.number, &body) .unwrap(); db_tx.commit().unwrap(); (db, header, body) } #[test] fn transaction() { let (mut db, _, body) = setup(); let tx = db.transaction().unwrap(); let (expected, _) = body.first().unwrap().clone(); let result = super::transaction(&tx, expected.hash()).unwrap().unwrap(); assert_eq!(result, expected); let invalid = super::transaction(&tx, transaction_hash_bytes!(b"invalid")).unwrap(); assert_eq!(invalid, None); } #[test] fn transaction_wtih_receipt() { let (mut db, header, body) = setup(); let tx = db.transaction().unwrap(); let (transaction, receipt) = body.first().unwrap().clone(); let result = super::transaction_with_receipt(&tx, transaction.hash()) .unwrap() .unwrap(); assert_eq!(result.0, transaction); assert_eq!(result.1, receipt); assert_eq!(result.2, header.hash); let invalid = super::transaction_with_receipt(&tx, transaction_hash_bytes!(b"invalid")).unwrap(); assert_eq!(invalid, None); } #[test] fn transaction_at_block() { let (mut db, header, body) = setup(); let tx = db.transaction().unwrap(); let idx = 5; let expected = Some(body[idx].0.clone()); let by_number = super::transaction_at_block(&tx, header.number.into(), idx).unwrap(); assert_eq!(by_number, expected); let by_hash = super::transaction_at_block(&tx, header.hash.into(), idx).unwrap(); assert_eq!(by_hash, expected); let by_latest = super::transaction_at_block(&tx, BlockId::Latest, idx).unwrap(); assert_eq!(by_latest, expected); let invalid_index = super::transaction_at_block(&tx, header.number.into(), body.len() + 1).unwrap(); assert_eq!(invalid_index, None); let invalid_index = super::transaction_at_block(&tx, BlockNumber::MAX.into(), idx).unwrap(); assert_eq!(invalid_index, None); } #[test] fn transaction_count() { let (mut db, header, body) = setup(); let tx = db.transaction().unwrap(); let by_latest = super::transaction_count(&tx, BlockId::Latest).unwrap(); assert_eq!(by_latest, body.len()); let by_number = super::transaction_count(&tx, header.number.into()).unwrap(); assert_eq!(by_number, body.len()); let by_hash = super::transaction_count(&tx, header.hash.into()).unwrap(); assert_eq!(by_hash, body.len()); } #[test] fn transaction_data_for_block() { let (mut db, header, body) = setup(); let tx = db.transaction().unwrap(); let expected = Some(body); let by_number = super::transaction_data_for_block(&tx, header.number.into()).unwrap(); assert_eq!(by_number, expected); let by_hash = super::transaction_data_for_block(&tx, header.hash.into()).unwrap(); assert_eq!(by_hash, expected); let by_latest = super::transaction_data_for_block(&tx, BlockId::Latest).unwrap(); assert_eq!(by_latest, expected); let invalid_block = super::transaction_data_for_block(&tx, BlockNumber::MAX.into()).unwrap(); assert_eq!(invalid_block, None); } #[test] fn transaction_block_hash() { let (mut db, header, body) = setup(); let tx = db.transaction().unwrap(); let target = body.first().unwrap().0.hash(); let valid = super::transaction_block_hash(&tx, target).unwrap().unwrap(); assert_eq!(valid, header.hash); let invalid = super::transaction_block_hash(&tx, transaction_hash_bytes!(b"invalid hash")).unwrap(); assert_eq!(invalid, None); } }
use crate::ast; use crate::{Parse, Spanned, ToTokens}; /// A literal expression. #[derive(Debug, Clone, PartialEq, Eq, Parse, ToTokens, Spanned)] #[rune(parse = "meta_only")] pub struct ExprLit { /// Attributes associated with the literal expression. #[rune(iter, meta)] pub attributes: Vec<ast::Attribute>, /// The literal in the expression. pub lit: ast::Lit, } expr_parse!(Lit, ExprLit, "literal expression");
use crate::{ Result, backend::Backend, lifecycle::{Event, State, Window}, }; #[cfg(not(target_arch = "wasm32"))] use std::{thread, time::{SystemTime, UNIX_EPOCH, Duration}}; #[cfg(target_arch = "wasm32")] use stdweb::web::Date; pub struct Application<T: State> { pub state: T, pub window: Window, pub event_buffer: Vec<Event>, accumulator: f64, last_draw: f64, last_update: f64, } impl<T: State> Application<T> { pub fn new<F: FnOnce()->Result<T>>(window: Window, f: F) -> Result<Application<T>> { let time = current_time(); Ok(Application { state: f()?, window, event_buffer: Vec::new(), accumulator: 0.0, last_draw: time, last_update: time, }) } pub fn update(&mut self) -> Result<()> { self.window.update_gamepads(&mut self.event_buffer); for i in 0..self.event_buffer.len() { self.window.process_event(&self.event_buffer[i]); self.state.event(&self.event_buffer[i], &mut self.window)?; } self.event_buffer.clear(); let current = current_time(); self.accumulator += current - self.last_update; self.last_update = current; let mut ticks = 0; let update_rate = self.window.update_rate(); while self.accumulator > 0.0 && (self.window.max_updates() == 0 || ticks < self.window.max_updates()) { self.state.update(&mut self.window)?; self.window.clear_temporary_states(); self.accumulator -= update_rate; ticks += 1; } Ok(()) } #[cfg(not(target_arch = "wasm32"))] pub fn draw(&mut self) -> Result<()> { let current = current_time(); let delta_draw = current - self.last_draw; if delta_draw >= self.window.draw_rate() { self.state.draw(&mut self.window)?; self.window.flush()?; self.window.backend().present()?; self.window.log_framerate(delta_draw); self.last_draw = current; } else { // Only sleep up to 1/10th of minimum of draw and update rate to make sure that we're definitely not sleeping longer than needed let max_sleep = self.window.draw_rate().min(self.window.update_rate()) * 0.1; let remaining_time = self.window.draw_rate() - delta_draw; if remaining_time >= max_sleep { thread::sleep(Duration::from_millis(max_sleep as u64)); } } Ok(()) } #[cfg(target_arch = "wasm32")] pub fn draw(&mut self) -> Result<()> { let current = current_time(); let delta_draw = current - self.last_draw; if delta_draw >= self.window.draw_rate() { self.state.draw(&mut self.window)?; self.window.flush()?; self.window.backend().present()?; self.window.log_framerate(delta_draw); self.last_draw = current; } Ok(()) } } #[cfg(not(target_arch = "wasm32"))] fn current_time() -> f64 { let start = SystemTime::now(); let since_the_epoch = start.duration_since(UNIX_EPOCH) .expect("Time went backwards"); since_the_epoch.as_secs() as f64 * 1000.0 + since_the_epoch.subsec_nanos() as f64 / 1e6 } #[cfg(target_arch = "wasm32")] fn current_time() -> f64 { Date::now() }
use super::*; pub use std::collections::BTreeMap; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub enum TypeInclude { Full, Minimal, None, } impl Default for TypeInclude { fn default() -> Self { Self::None } } #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)] pub struct TypeEntry { pub def: Vec<ElementType>, pub include: TypeInclude, } // The TypeTree needs to use a BTreeMap rather than the fast HashMap because it affects code gen and we need // the code gen to be stable. pub struct TypeTree { pub namespace: &'static str, pub types: BTreeMap<&'static str, TypeEntry>, pub namespaces: BTreeMap<&'static str, TypeTree>, pub include: bool, } impl TypeTree { pub fn from_namespace(namespace: &'static str) -> Self { Self { namespace, types: BTreeMap::new(), namespaces: BTreeMap::new(), include: false } } pub fn features(&self, features: &mut BTreeSet<&'static str>, keys: &mut std::collections::HashSet<Row>) { self.types.values().map(|entry| entry.def.iter()).flatten().for_each(|def| def.features(features, keys)); } pub fn insert_namespace(&mut self, namespace: &'static str, pos: usize) -> &mut Self { if let Some(next) = namespace[pos..].find('.') { let next = pos + next; self.namespaces.entry(&namespace[pos..next]).or_insert_with(|| Self::from_namespace(&namespace[..next])).insert_namespace(namespace, next + 1) } else { self.namespaces.entry(&namespace[pos..]).or_insert_with(|| Self::from_namespace(namespace)) } } pub fn insert_type(&mut self, name: &'static str, def: ElementType) { self.types.entry(name).or_default().def.push(def); } // TODO: slow method - remove or make this an iterator somehow? pub fn namespaces(&self) -> Vec<&'static str> { let mut namespaces = Vec::new(); for tree in self.namespaces.values() { if !tree.types.is_empty() { namespaces.push(tree.namespace) } namespaces.append(&mut tree.namespaces()); } namespaces } pub fn get_type(&self, name: &str) -> Option<&TypeEntry> { self.types.get(name) } pub fn get_type_mut(&mut self, name: &str) -> Option<&mut TypeEntry> { self.types.get_mut(name) } pub fn get_namespace(&self, namespace: &str) -> Option<&Self> { if let Some(next) = namespace.find('.') { self.namespaces.get(&namespace[..next]).and_then(|child| child.get_namespace(&namespace[next + 1..])) } else { self.namespaces.get(namespace) } } pub fn get_namespace_mut(&mut self, namespace: &str) -> Option<&mut Self> { self.include = true; if let Some(next) = namespace.find('.') { self.namespaces.get_mut(&namespace[..next]).and_then(|child| child.get_namespace_mut(&namespace[next + 1..])) } else { self.namespaces.get_mut(namespace).map(|ns| { ns.include = true; ns }) } } pub fn exclude_namespace(&mut self, namespace: &str) { if let Some(tree) = self.get_namespace_mut(namespace) { tree.include = false; } } }
use std::io::prelude::*; use std::str::FromStr; fn ans(i:Vec<f64>) -> (f64,f64,f64) { let x1 = i[0]; let y1 = i[1]; let x2 = i[2]; let y2 = i[3]; let x3 = i[4]; let y3 = i[5]; let a2 = x1.powf(2.0) - x2.powf(2.0); let b2 = 2.0 * (x1-x2); let c2 = y1.powf(2.0) - y2.powf(2.0); let d2 = 2.0 * (y1-y2); let a3 = x1.powf(2.0) - x3.powf(2.0); let b3 = 2.0 * (x1-x3); let c3 = y1.powf(2.0) - y3.powf(2.0); let d3 = 2.0 * (y1-y3); let xp = (a2*d3 + c2*d3 - a3*d2 - c3*d2) / (b2*d3 - b3*d2); let yp = if d2 != 0.0 { (a2+c2 - b2*xp) / d2 } else { (a3+c3-b3*xp) / d3 }; let r = ( (x1-xp).powf(2.0) + (y1-yp).powf(2.0) ).sqrt(); (xp, yp, r) } fn main() { let stdin = std::io::stdin(); let l = stdin.lock().lines().next().unwrap().unwrap(); let n = i32::from_str(&l).unwrap(); for _ in 0..n { let s = stdin.lock().lines().next().unwrap().unwrap(); let d : Vec<f64> = s.split_whitespace().map(|x| f64::from_str(x).unwrap()).collect(); let (x,y,r) = ans(d); println!("{:.3} {:.3} {:.3}",x,y,r); } }
// 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::time::Instant; use mysql_async::prelude::Queryable; use mysql_async::Conn; use mysql_async::Pool; use mysql_async::Row; use sqllogictest::DBOutput; use sqllogictest::DefaultColumnType; use crate::error::Result; #[derive(Debug)] pub struct MySQLClient { pub conn: Conn, pub debug: bool, pub tpch: bool, } impl MySQLClient { pub async fn create() -> Result<Self> { let url = "mysql://root:@127.0.0.1:3307/default"; let pool = Pool::new(url); let conn = pool.get_conn().await?; Ok(Self { conn, debug: false, tpch: false, }) } pub fn enable_tpch(&mut self) { self.tpch = true; } pub async fn query(&mut self, sql: &str) -> Result<DBOutput<DefaultColumnType>> { let start = Instant::now(); let rows: Vec<Row> = self.conn.query(sql).await?; let elapsed = start.elapsed(); if self.tpch && !(sql.trim_start().starts_with("set") || sql.trim_start().starts_with("analyze")) { println!("{elapsed:?}"); } if self.debug { println!("Running sql with mysql client: [{sql}] ({elapsed:?})"); }; let types = vec![DefaultColumnType::Any; rows.len()]; let mut parsed_rows = Vec::with_capacity(rows.len()); for row in rows.into_iter() { let mut parsed_row = Vec::new(); for i in 0..row.len() { let value: Option<Option<String>> = row.get(i); if let Some(v) = value { match v { None => parsed_row.push("NULL".to_string()), Some(s) if s.is_empty() => parsed_row.push("(empty)".to_string()), Some(s) => parsed_row.push(s), } } } parsed_rows.push(parsed_row); } // Todo: add types to compare Ok(DBOutput::Rows { types, rows: parsed_rows, }) } }
//! This module contains a timer object, bevy-systems for updating (using) //! the timer, and run-criterias that uses this timer. //! pub mod scenario_intervals; pub mod scenario_timer;
// This file is part of file-descriptors. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/file-descriptors/master/COPYRIGHT. No part of file-descriptors, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2018-2019 The developers of file-descriptors. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/file-descriptors/master/COPYRIGHT. /// An error that can occur during registration with epoll. #[derive(Debug)] pub enum EventPollRegistrationError { /// Error on creation of a file descriptor. Creation(CreationError), /// Could not allocate (out of memory in some way) from an `Arena`. Allocation(ArenaAllocationError), /// Could not internally add a file descriptor to an epoll instance. Add(EPollAddError), /// Could not create a file descriptor to register with an epoll instance. NewSocketServerListener(NewSocketServerListenerError), /// Initial input-output activity failed before registration. InitialInputOrOutputFailed(Box<dyn error::Error + 'static>), } impl Display for EventPollRegistrationError { #[inline(always)] fn fmt(&self, f: &mut Formatter) -> fmt::Result { <EventPollRegistrationError as Debug>::fmt(self, f) } } impl error::Error for EventPollRegistrationError { #[inline(always)] fn source(&self) -> Option<&(error::Error + 'static)> { use self::EventPollRegistrationError::*; match self { &Creation(ref error) => Some(error), &Allocation(ref error) => Some(error), &Add(ref error) => Some(error), &NewSocketServerListener(ref error) => Some(error), &InitialInputOrOutputFailed(ref error) => Some(error.deref()), } } } impl From<CreationError> for EventPollRegistrationError { #[inline(always)] fn from(error: CreationError) -> Self { EventPollRegistrationError::Creation(error) } } impl From<ArenaAllocationError> for EventPollRegistrationError { #[inline(always)] fn from(error: ArenaAllocationError) -> Self { EventPollRegistrationError::Allocation(error) } } impl From<EPollAddError> for EventPollRegistrationError { #[inline(always)] fn from(error: EPollAddError) -> Self { EventPollRegistrationError::Add(error) } } impl From<NewSocketServerListenerError> for EventPollRegistrationError { #[inline(always)] fn from(error: NewSocketServerListenerError) -> Self { EventPollRegistrationError::NewSocketServerListener(error) } }
use smart_pointer::ref_cell_demo::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; pub fn hello_ref_cell() { ref_cell_demo(); } pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a, T: 'a + Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger, { pub fn new(messenger: &T, max: usize) -> LimitTracker<T> { LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percent_of_max = self.value as f64 / self.max as f64; if percent_of_max >= 0.75 && percent_of_max < 0.9 { self.messenger .send("warning: You've used up over 75% of your quota!"); } else if percent_of_max >= 0.9 && percent_of_max < 1.0 { self.messenger .send("urgent warning: You've used up over 90% of your quota!"); } else if percent_of_max >= 1.0 { self.messenger.send("error: You are over your quota!"); } } } #[derive(Debug)] enum List { Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } fn ref_cell_demo() { let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); println!("a before = {:?}", a); println!("b before = {:?}", b); println!("c before = {:?}", c); *value.borrow_mut() += 10; println!("a after = {:?}", a); println!("b after = {:?}", b); println!("c after = {:?}", c); }
//! Parse the Linux vDSO. //! //! The following code is transliterated from //! tools/testing/selftests/vDSO/parse_vdso.c in Linux 5.11, which is licensed //! with Creative Commons Zero License, version 1.0, //! available at <https://creativecommons.org/publicdomain/zero/1.0/legalcode> //! //! # Safety //! //! Parsing the vDSO involves a lot of raw pointer manipulation. This //! implementation follows Linux's reference implementation, and adds several //! additional safety checks. #![allow(unsafe_code)] use super::c; use super::elf::*; use crate::ffi::CStr; use crate::utils::check_raw_pointer; use core::ffi::c_void; use core::mem::size_of; use core::ptr::{null, null_mut}; pub(super) struct Vdso { // Load information load_addr: *const Elf_Ehdr, load_end: *const c_void, // the end of the `PT_LOAD` segment pv_offset: usize, // recorded paddr - recorded vaddr // Symbol table symtab: *const Elf_Sym, symstrings: *const u8, bucket: *const u32, chain: *const u32, nbucket: u32, //nchain: u32, // Version table versym: *const u16, verdef: *const Elf_Verdef, } // Straight from the ELF specification. fn elf_hash(name: &CStr) -> u32 { let mut h: u32 = 0; for b in name.to_bytes() { h = (h << 4).wrapping_add(u32::from(*b)); let g = h & 0xf000_0000; if g != 0 { h ^= g >> 24; } h &= !g; } h } /// Create a `Vdso` value by parsing the vDSO at the `sysinfo_ehdr` address. fn init_from_sysinfo_ehdr() -> Option<Vdso> { // SAFETY: the auxv initialization code does extensive checks to ensure // that the value we get really is an `AT_SYSINFO_EHDR` value from the // kernel. unsafe { let hdr = super::param::auxv::sysinfo_ehdr(); // If the platform doesn't provide a `AT_SYSINFO_EHDR`, we can't locate // the vDSO. if hdr.is_null() { return None; } let mut vdso = Vdso { load_addr: hdr, load_end: hdr.cast(), pv_offset: 0, symtab: null(), symstrings: null(), bucket: null(), chain: null(), nbucket: 0, //nchain: 0, versym: null(), verdef: null(), }; let hdr = &*hdr; let pt = check_raw_pointer::<Elf_Phdr>(vdso.base_plus(hdr.e_phoff)? as *mut _)?.as_ptr(); let mut dyn_: *const Elf_Dyn = null(); let mut num_dyn = 0; // We need two things from the segment table: the load offset // and the dynamic table. let mut found_vaddr = false; for i in 0..hdr.e_phnum { let phdr = &*pt.add(i as usize); if phdr.p_flags & PF_W != 0 { // Don't trust any vDSO that claims to be loading writable // segments into memory. return None; } if phdr.p_type == PT_LOAD && !found_vaddr { // The segment should be readable and executable, because it // contains the symbol table and the function bodies. if phdr.p_flags & (PF_R | PF_X) != (PF_R | PF_X) { return None; } found_vaddr = true; vdso.load_end = vdso.base_plus(phdr.p_offset.checked_add(phdr.p_memsz)?)?; vdso.pv_offset = phdr.p_offset.wrapping_sub(phdr.p_vaddr); } else if phdr.p_type == PT_DYNAMIC { // If `p_offset` is zero, it's more likely that we're looking at memory // that has been zeroed than that the kernel has somehow aliased the // `Ehdr` and the `Elf_Dyn` array. if phdr.p_offset < size_of::<Elf_Ehdr>() { return None; } dyn_ = check_raw_pointer::<Elf_Dyn>(vdso.base_plus(phdr.p_offset)? as *mut _)? .as_ptr(); num_dyn = phdr.p_memsz / size_of::<Elf_Dyn>(); } else if phdr.p_type == PT_INTERP || phdr.p_type == PT_GNU_RELRO { // Don't trust any ELF image that has an “interpreter” or that uses // RELRO, which is likely to be a user ELF image rather and not the // kernel vDSO. return None; } } if !found_vaddr || dyn_.is_null() { return None; // Failed } // Fish out the useful bits of the dynamic table. let mut hash: *const u32 = null(); vdso.symstrings = null(); vdso.symtab = null(); vdso.versym = null(); vdso.verdef = null(); let mut i = 0; loop { if i == num_dyn { return None; } let d = &*dyn_.add(i); match d.d_tag { DT_STRTAB => { vdso.symstrings = check_raw_pointer::<u8>(vdso.addr_from_elf(d.d_val)? as *mut _)?.as_ptr(); } DT_SYMTAB => { vdso.symtab = check_raw_pointer::<Elf_Sym>(vdso.addr_from_elf(d.d_val)? as *mut _)? .as_ptr(); } DT_HASH => { hash = check_raw_pointer::<u32>(vdso.addr_from_elf(d.d_val)? as *mut _)?.as_ptr(); } DT_VERSYM => { vdso.versym = check_raw_pointer::<u16>(vdso.addr_from_elf(d.d_val)? as *mut _)?.as_ptr(); } DT_VERDEF => { vdso.verdef = check_raw_pointer::<Elf_Verdef>(vdso.addr_from_elf(d.d_val)? as *mut _)? .as_ptr(); } DT_SYMENT => { if d.d_val != size_of::<Elf_Sym>() { return None; // Failed } } DT_NULL => break, _ => {} } i = i.checked_add(1)?; } // The upstream code checks `symstrings`, `symtab`, and `hash` for null; // here, `check_raw_pointer` has already done that. if vdso.verdef.is_null() { vdso.versym = null(); } // Parse the hash table header. vdso.nbucket = *hash.add(0); //vdso.nchain = *hash.add(1); vdso.bucket = hash.add(2); vdso.chain = hash.add(vdso.nbucket as usize + 2); // That's all we need. Some(vdso) } } impl Vdso { /// Parse the vDSO. /// /// Returns `None` if the vDSO can't be located or if it doesn't conform /// to our expectations. #[inline] pub(super) fn new() -> Option<Self> { init_from_sysinfo_ehdr() } /// Check the version for a symbol. /// /// # Safety /// /// The raw pointers inside `self` must be valid. unsafe fn match_version(&self, mut ver: u16, name: &CStr, hash: u32) -> bool { // This is a helper function to check if the version indexed by // ver matches name (which hashes to hash). // // The version definition table is a mess, and I don't know how // to do this in better than linear time without allocating memory // to build an index. I also don't know why the table has // variable size entries in the first place. // // For added fun, I can't find a comprehensible specification of how // to parse all the weird flags in the table. // // So I just parse the whole table every time. // First step: find the version definition ver &= 0x7fff; // Apparently bit 15 means "hidden" let mut def = self.verdef; loop { if (*def).vd_version != VER_DEF_CURRENT { return false; // Failed } if ((*def).vd_flags & VER_FLG_BASE) == 0 && ((*def).vd_ndx & 0x7fff) == ver { break; } if (*def).vd_next == 0 { return false; // No definition. } def = def .cast::<u8>() .add((*def).vd_next as usize) .cast::<Elf_Verdef>(); } // Now figure out whether it matches. let aux = &*(def.cast::<u8>()) .add((*def).vd_aux as usize) .cast::<Elf_Verdaux>(); (*def).vd_hash == hash && (name == CStr::from_ptr(self.symstrings.add(aux.vda_name as usize).cast())) } /// Look up a symbol in the vDSO. pub(super) fn sym(&self, version: &CStr, name: &CStr) -> *mut c::c_void { let ver_hash = elf_hash(version); let name_hash = elf_hash(name); // SAFETY: The pointers in `self` must be valid. unsafe { let mut chain = *self.bucket.add((name_hash % self.nbucket) as usize); while chain != STN_UNDEF { let sym = &*self.symtab.add(chain as usize); // Check for a defined global or weak function w/ right name. // // The reference parser in Linux's parse_vdso.c requires // symbols to have type `STT_FUNC`, but on powerpc64, the vDSO // uses `STT_NOTYPE`, so allow that too. if (ELF_ST_TYPE(sym.st_info) != STT_FUNC && ELF_ST_TYPE(sym.st_info) != STT_NOTYPE) || (ELF_ST_BIND(sym.st_info) != STB_GLOBAL && ELF_ST_BIND(sym.st_info) != STB_WEAK) || sym.st_shndx == SHN_UNDEF || sym.st_shndx == SHN_ABS || ELF_ST_VISIBILITY(sym.st_other) != STV_DEFAULT || (name != CStr::from_ptr(self.symstrings.add(sym.st_name as usize).cast())) // Check symbol version. || (!self.versym.is_null() && !self.match_version(*self.versym.add(chain as usize), version, ver_hash)) { chain = *self.chain.add(chain as usize); continue; } let sum = self.addr_from_elf(sym.st_value).unwrap(); assert!( sum as usize >= self.load_addr as usize && sum as usize <= self.load_end as usize ); return sum as *mut c::c_void; } } null_mut() } /// Add the given address to the vDSO base address. unsafe fn base_plus(&self, offset: usize) -> Option<*const c_void> { // Check for overflow. let _ = (self.load_addr as usize).checked_add(offset)?; // Add the offset to the base. Some(self.load_addr.cast::<u8>().add(offset).cast()) } /// Translate an ELF-address-space address into a usable virtual address. unsafe fn addr_from_elf(&self, elf_addr: usize) -> Option<*const c_void> { self.base_plus(elf_addr.wrapping_add(self.pv_offset)) } }
use crate::row::{ColumnIndex, Row}; use crate::sqlite::statement::Statement; use crate::sqlite::value::SqliteValue; use crate::sqlite::{Sqlite, SqliteConnection}; use serde::de::DeserializeOwned; #[derive(Debug)] pub struct SqliteRow<'c> { pub(super) values: usize, pub(super) statement: Option<usize>, pub(super) connection: &'c SqliteConnection, } impl crate::row::private_row::Sealed for SqliteRow<'_> {} // Accessing values from the statement object is // safe across threads as long as we don't call [sqlite3_step] // That should not be possible as long as an immutable borrow is held on the connection unsafe impl Send for SqliteRow<'_> {} unsafe impl Sync for SqliteRow<'_> {} impl<'c> SqliteRow<'c> { #[inline] fn statement(&self) -> &'c Statement { self.connection.statement(self.statement) } } impl <'c>SqliteRow<'c>{ pub fn json_decode_impl<T, I>(&self, index: I) -> crate::Result<T> where I: ColumnIndex<'c, Self>, T: DeserializeOwned { self.json_decode(index) } } impl<'c> Row<'c> for SqliteRow<'c> { type Database = Sqlite; #[inline] fn len(&self) -> usize { self.values } #[doc(hidden)] fn try_get_raw<I>(&self, index: I) -> crate::Result<SqliteValue<'c>> where I: ColumnIndex<'c, Self>, { Ok(SqliteValue { statement: self.statement(), index: index.index(self)? as i32, }) } } impl<'c> ColumnIndex<'c, SqliteRow<'c>> for usize { fn index(&self, row: &SqliteRow<'c>) -> crate::Result<usize> { let len = Row::len(row); if *self >= len { return Err(crate::Error::ColumnIndexOutOfBounds { len, index: *self }); } Ok(*self) } } impl<'c> ColumnIndex<'c, SqliteRow<'c>> for str { fn index(&self, row: &SqliteRow<'c>) -> crate::Result<usize> { row.statement() .columns .get(self) .ok_or_else(|| crate::Error::ColumnNotFound((*self).into())) .map(|&index| index as usize) } }
extern crate multipart; extern crate iron; extern crate env_logger; use std::io::{self, Write}; use multipart::mock::StdoutTee; use multipart::server::{Multipart, Entries, SaveResult}; use iron::prelude::*; use iron::status; fn main() { env_logger::init(); Iron::new(process_request).http("localhost:80").expect("Could not bind localhost:80"); } /// Processes a request and returns response or an occured error. fn process_request(request: &mut Request) -> IronResult<Response> { // Getting a multipart reader wrapper match Multipart::from_request(request) { Ok(mut multipart) => { // Fetching all data and processing it. // save().temp() reads the request fully, parsing all fields and saving all files // in a new temporary directory under the OS temporary directory. match multipart.save().temp() { SaveResult::Full(entries) => process_entries(entries), SaveResult::Partial(entries, reason) => { process_entries(entries.keep_partial())?; Ok(Response::with(( status::BadRequest, format!("error reading request: {}", reason.unwrap_err()) ))) } SaveResult::Error(error) => Ok(Response::with(( status::BadRequest, format!("error reading request: {}", error) ))), } } Err(_) => { Ok(Response::with((status::BadRequest, "The request is not multipart"))) } } } /// Processes saved entries from multipart request. /// Returns an OK response or an error. fn process_entries(entries: Entries) -> IronResult<Response> { let mut data = Vec::new(); { let stdout = io::stdout(); let tee = StdoutTee::new(&mut data, &stdout); entries.write_debug(tee).map_err(|e| { IronError::new( e, (status::InternalServerError, "Error printing request fields") ) })?; } let _ = writeln!(data, "Entries processed"); Ok(Response::with((status::Ok, data))) }
mod result; mod plugin; use log::{debug}; use result::Result; use plugin::Plugin; use std::ffi::OsStr; use std::path::Path; /// The Quantum Core #[derive(Debug)] pub struct Quantum { plugin_dir: String, plugins: Vec<Plugin>, } impl Quantum { /// Creates a new Quantum instance pub fn new() -> Quantum { Quantum { plugin_dir: ".".to_owned(), plugins: Vec::new(), } } /// Loads a plugin from a shared library pub fn load_plugin<S: AsRef<OsStr> + ?Sized>(&mut self, path: &S) -> Result<String> { let mut path = Path::new(path).to_path_buf(); if path.is_relative() { path = Path::new(&self.plugin_dir).join(path); } let plugin = Plugin::load(path)?; let name = plugin.name().to_owned(); self.plugins.push(plugin); Ok(name) } }
use super::Grip; use super::Menu; use super::Side; use super::System; use super::Touchpad; use super::Trigger; use super::Vive; use button::Button; use openvr_sys::TrackedDevicePose_t; use openvr_sys::VRControllerState_t; use std::f32; use std::u32; const INVALID_INDEX: u32 = u32::MAX; const INVALID_POSITION: (f32, f32, f32) = (f32::NAN, f32::NAN, f32::NAN); const INVALID_ROTATION: (f32, f32, f32) = (f32::NAN, f32::NAN, f32::NAN); pub struct Hand { side: Side, index: u32, controller_state: VRControllerState_t, controller_pose: TrackedDevicePose_t, pub position: (f32, f32, f32), pub rotation: (f32, f32, f32), pub grip: Grip, pub menu: Menu, pub system: System, pub touchpad: Touchpad, pub trigger: Trigger, } impl Hand { pub fn new(side: Side) -> Self { Hand { side: side, index: INVALID_INDEX, controller_state: VRControllerState_t::default(), controller_pose: TrackedDevicePose_t::default(), position: INVALID_POSITION, rotation: INVALID_ROTATION, grip: Grip::default(), menu: Menu::default(), system: System::default(), touchpad: Touchpad::default(), trigger: Trigger::default(), } } pub fn available(&self) -> bool { self.index != INVALID_INDEX } pub fn update(&mut self) { { // update controller index self.index = { use openvr_sys::ETrackedControllerRole; let role = match self.side { Side::Left => ETrackedControllerRole::ETrackedControllerRole_TrackedControllerRole_LeftHand, Side::Right => ETrackedControllerRole::ETrackedControllerRole_TrackedControllerRole_RightHand, }; Vive::api().system.get_tracked_device_index_for_controller_role(role) }; } { // update controller state and pose use openvr_sys::ETrackingUniverseOrigin; let tracking_origin = ETrackingUniverseOrigin::ETrackingUniverseOrigin_TrackingUniverseStanding; Vive::api().system.get_controller_state_with_pose(tracking_origin, self.index, &mut self.controller_state, &mut self.controller_pose); } { // update buttons let controller_mask = self.controller_state.ulButtonPressed; self.trigger.update(controller_mask); self.touchpad.update(controller_mask); self.grip.update(controller_mask); self.menu.update(controller_mask); self.system.update(controller_mask); } { // update position and rotation let a = self.controller_pose.mDeviceToAbsoluteTracking.m; //let x0_y0 = a[0][0]; //let x1_y0 = a[0][1]; //let x2_y0 = -a[0][2]; let x3_y0 = a[0][3]; //let x0_y1 = a[1][0]; //let x1_y1 = a[1][1]; //let x2_y1 = -a[1][2]; let x3_y1 = a[1][3]; //let x0_y2 = -a[2][0]; //let x1_y2 = -a[2][1]; //let x2_y2 = a[2][2]; let x3_y2 = -a[2][3]; //let x0_y3 = 0.0; //let x1_y3 = 0.0; //let x2_y3 = 0.0; //let x3_y3 = 1.0; // TODO hand position self.position = { let x = x3_y0; let y = x3_y1; let z = x3_y2; (x, y, z) }; // TODO hand rotation self.rotation = (0.0, 0.0, 0.0) } } pub fn rumble(&self, duration: u16) { assert!(duration > 0 && duration < 4000); Vive::api().system.trigger_haptic_pulse(self.index, 0, duration); } }
use fake::Dummy; use stark_hash::Felt; use crate::{ToProtobuf, TryFromProtobuf}; use super::common::{BlockBody, BlockHeader}; use super::proto; #[derive(Debug, Clone, PartialEq, Eq, Dummy)] pub enum Request { GetBlockHeaders(GetBlockHeaders), GetBlockBodies(GetBlockBodies), GetStateDiffs(GetStateDiffs), GetClasses(GetClasses), Status(Status), } const MAX_UNCOMPRESSED_MESSAGE_SIZE: usize = 1024 * 1024; impl Request { pub fn from_protobuf_encoding(bytes: &[u8]) -> std::io::Result<Self> { use prost::Message; let bytes = zstd::bulk::decompress(bytes, MAX_UNCOMPRESSED_MESSAGE_SIZE)?; let request = proto::sync::Request::decode(bytes.as_ref())?; TryFromProtobuf::try_from_protobuf(request, "message") } pub fn into_protobuf_encoding(self) -> std::io::Result<Vec<u8>> { use prost::Message; let request: proto::sync::Request = self.to_protobuf(); let encoded_len = request.encoded_len(); if encoded_len > MAX_UNCOMPRESSED_MESSAGE_SIZE { return Err(std::io::Error::new( std::io::ErrorKind::OutOfMemory, "Protobuf encoded message would exceed maximum message size", )); } let mut buf = Vec::with_capacity(request.encoded_len()); request .encode(&mut buf) .expect("Buffer provides enough capacity"); let buf = zstd::bulk::compress(buf.as_ref(), 1)?; Ok(buf) } } impl TryFromProtobuf<proto::sync::Request> for Request { fn try_from_protobuf( value: proto::sync::Request, field_name: &'static str, ) -> Result<Self, std::io::Error> { match value.request { Some(r) => match r { proto::sync::request::Request::GetBlockHeaders(r) => Ok(Request::GetBlockHeaders( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), proto::sync::request::Request::GetBlockBodies(r) => Ok(Request::GetBlockBodies( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), proto::sync::request::Request::GetStateDiffs(r) => Ok(Request::GetStateDiffs( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), proto::sync::request::Request::GetClasses(r) => Ok(Request::GetClasses( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), proto::sync::request::Request::Status(r) => Ok(Request::Status( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), }, None => Err(std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Missing field {field_name}"), )), } } } impl ToProtobuf<proto::sync::Request> for Request { fn to_protobuf(self) -> proto::sync::Request { proto::sync::Request { request: Some(match self { Request::GetBlockHeaders(r) => { proto::sync::request::Request::GetBlockHeaders(r.to_protobuf()) } Request::GetBlockBodies(r) => { proto::sync::request::Request::GetBlockBodies(r.to_protobuf()) } Request::GetStateDiffs(r) => { proto::sync::request::Request::GetStateDiffs(r.to_protobuf()) } Request::GetClasses(r) => { proto::sync::request::Request::GetClasses(r.to_protobuf()) } Request::Status(r) => proto::sync::request::Request::Status(r.to_protobuf()), }), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Dummy)] pub enum Direction { Forward, Backward, } impl TryFromProtobuf<i32> for Direction { fn try_from_protobuf(input: i32, field_name: &'static str) -> Result<Self, std::io::Error> { let input = proto::sync::Direction::from_i32(input).ok_or_else(|| { std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Failed to parse {field_name}"), ) })?; Ok(match input { proto::sync::Direction::Backward => Direction::Backward, proto::sync::Direction::Forward => Direction::Forward, }) } } impl ToProtobuf<i32> for Direction { fn to_protobuf(self) -> i32 { match self { Direction::Forward => proto::sync::Direction::Forward as i32, Direction::Backward => proto::sync::Direction::Backward as i32, } } } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::GetBlockHeaders")] pub struct GetBlockHeaders { pub start_block: u64, pub count: u64, pub size_limit: u64, pub direction: Direction, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::GetBlockBodies")] pub struct GetBlockBodies { pub start_block: Felt, pub count: u64, pub size_limit: u64, pub direction: Direction, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::GetStateDiffs")] pub struct GetStateDiffs { pub start_block: Felt, pub count: u64, pub size_limit: u64, pub direction: Direction, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::GetClasses")] pub struct GetClasses { pub class_hashes: Vec<Felt>, pub size_limit: u64, } #[derive(Debug, Clone, PartialEq, Eq, Dummy)] pub enum Response { BlockHeaders(BlockHeaders), BlockBodies(BlockBodies), StateDiffs(StateDiffs), Classes(Classes), Status(Status), } impl Response { pub fn from_protobuf_encoding(bytes: &[u8]) -> std::io::Result<Self> { use prost::Message; let bytes = zstd::bulk::decompress(bytes, MAX_UNCOMPRESSED_MESSAGE_SIZE)?; let response = proto::sync::Response::decode(bytes.as_ref())?; TryFromProtobuf::try_from_protobuf(response, "message") } pub fn into_protobuf_encoding(self) -> std::io::Result<Vec<u8>> { use prost::Message; let response: proto::sync::Response = self.to_protobuf(); let encoded_len = response.encoded_len(); if encoded_len > MAX_UNCOMPRESSED_MESSAGE_SIZE { return Err(std::io::Error::new( std::io::ErrorKind::OutOfMemory, "Protobuf encoded message would exceed maximum message size", )); } let mut buf = Vec::with_capacity(response.encoded_len()); response .encode(&mut buf) .expect("Buffer provides enough capacity"); let buf = zstd::bulk::compress(buf.as_ref(), 1)?; Ok(buf) } } impl TryFromProtobuf<proto::sync::Response> for Response { fn try_from_protobuf( value: proto::sync::Response, field_name: &'static str, ) -> Result<Self, std::io::Error> { match value.response { Some(r) => match r { proto::sync::response::Response::BlockHeaders(h) => Ok(Response::BlockHeaders( TryFromProtobuf::try_from_protobuf(h, field_name)?, )), proto::sync::response::Response::BlockBodies(r) => Ok(Response::BlockBodies( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), proto::sync::response::Response::StateDiffs(r) => Ok(Response::StateDiffs( TryFromProtobuf::try_from_protobuf(r, field_name)?, )), proto::sync::response::Response::Classes(s) => Ok(Response::Classes( TryFromProtobuf::try_from_protobuf(s, field_name)?, )), proto::sync::response::Response::Status(s) => Ok(Response::Status( TryFromProtobuf::try_from_protobuf(s, field_name)?, )), }, None => Err(std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Missing field {field_name}"), )), } } } impl ToProtobuf<proto::sync::Response> for Response { fn to_protobuf(self) -> proto::sync::Response { proto::sync::Response { response: Some(match self { Response::BlockHeaders(r) => { proto::sync::response::Response::BlockHeaders(r.to_protobuf()) } Response::BlockBodies(r) => { proto::sync::response::Response::BlockBodies(r.to_protobuf()) } Response::StateDiffs(r) => { proto::sync::response::Response::StateDiffs(r.to_protobuf()) } Response::Classes(r) => proto::sync::response::Response::Classes(r.to_protobuf()), Response::Status(r) => proto::sync::response::Response::Status(r.to_protobuf()), }), } } } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::BlockHeaders")] pub struct BlockHeaders { pub headers: Vec<BlockHeader>, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::BlockBodies")] pub struct BlockBodies { pub block_bodies: Vec<BlockBody>, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::StateDiffs")] pub struct StateDiffs { pub block_state_updates: Vec<BlockStateUpdateWithHash>, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::state_diffs::BlockStateUpdateWithHash")] pub struct BlockStateUpdateWithHash { pub block_hash: Felt, pub state_update: super::propagation::BlockStateUpdate, pub state_commitment: Felt, pub parent_state_commitment: Felt, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::Status")] pub struct Status { pub height: u64, pub hash: Felt, pub chain_id: Felt, } #[derive(Debug, Clone, PartialEq, Eq, ToProtobuf, TryFromProtobuf, Dummy)] #[protobuf(name = "crate::proto::sync::Classes")] pub struct Classes { pub classes: Vec<super::common::RawClass>, }
fn read_line() -> String { let mut buf = String::new(); std::io::stdin().read_line(&mut buf).expect("failed to readline"); buf } fn create_num_vec() -> Vec<i64> { let buf = read_line(); let iter = buf.split_whitespace().map(|x| x.parse().expect("unable to parse")); let num_vec : Vec<i64> = iter.collect(); num_vec } fn main() { let n : String = read_line(); let num_vec : Vec<i64> = create_num_vec(); let sum : i64 = num_vec.iter().sum(); println!("{}", sum); }
use std::{io, i32}; use std::sync::atomic::{AtomicI32, Ordering}; use sys::{futex_wait, futex_wake}; pub struct RwFutex { readers: AtomicI32, writers_queued: AtomicI32, writers_wakeup: AtomicI32, } //rconst WRITER_LOCKED: i32 = i32::MIN; const WRITER_LOCKED_READERS_QUEUED: i32 = i32::MIN + 1; impl RwFutex { pub fn new() -> RwFutex { RwFutex { readers: AtomicI32::new(0), writers_queued: AtomicI32::new(0), writers_wakeup: AtomicI32::new(0), } } pub fn acquire_read(&self) { loop { // only try to acquire if no one is waiting to write let mut val; if self.writers_queued.load(Ordering::Relaxed) == 0 { val = self.readers.fetch_add(1, Ordering::Acquire); if val >= 0 { // got it break; } // try to undo the damage (if any) val = val + 1; while val > WRITER_LOCKED_READERS_QUEUED && val < 0 { val = self.readers.compare_and_swap(val, WRITER_LOCKED_READERS_QUEUED, Ordering::Relaxed); } if val >= 0 { // unlock happened, try again to acquire continue; } } else { val = self.readers.load(Ordering::Relaxed); } // writer is active if let Err(e) = futex_wait(&self.readers, val) { match e.kind() { io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => (), // ok _ => panic!("{}", e), } } } } pub fn acquire_write(&self) { self.writers_queued.fetch_add(1, Ordering::Acquire); loop { let val = self.readers.compare_and_swap(0, i32::MIN, Ordering::Acquire); if val == 0 { // got it! break; } else { // load if let Err(e) = futex_wait(&self.writers_wakeup, 0) { match e.kind() { io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => (), // ok _ => panic!("{}", e), } } } } self.writers_queued.fetch_sub(1, Ordering::Release); } pub fn release_read(&self) { let val = self.readers.fetch_sub(1, Ordering::Release); if val == 1 { // now 0 => no more readers => wake up a writer if self.writers_queued.load(Ordering::Relaxed) > 0 { futex_wake(&self.writers_wakeup, 1).unwrap(); } } } pub fn release_write(&self) { self.readers.swap(0, Ordering::Release); if self.writers_queued.load(Ordering::Relaxed) > 0 { // store if futex_wake(&self.writers_wakeup, 1).unwrap() == 1 { // woke up a writer - don't wake up the readers return; } } futex_wake(&self.readers, i32::MAX).unwrap(); } }
use std::collections::VecDeque; 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 = scan!(usize); let mut g = vec![vec![]; n]; for i in 0..(n - 1) { let (a, b) = scan!((usize, usize)); g[a - 1].push((b - 1, i)); g[b - 1].push((a - 1, i)); } let mut ans = vec![0; n - 1]; let mut que = VecDeque::new(); que.push_back((0, 0, 0)); while let Some((cur, prev, ng_color)) = que.pop_front() { let mut color = 1; for &(nxt, i) in &g[cur] { if nxt == prev { continue; } if color == ng_color { color += 1; } ans[i] = color; que.push_back((nxt, cur, color)); color += 1; } } let mut k = 0; for &ans in &ans { k = k.max(ans); assert_ne!(ans, 0); } println!("{}", k); for ans in ans { println!("{}", ans); } }
use crate::ast::{Tm, TmRef, Ty, TyRef}; use crate::tcm::{TCM, TCS}; pub fn infer(tcs: &mut TCS, tm: TmRef) -> TCM<TyRef> { let ty_exh_size = tcs.ty_exh.size(); let rules = [var_rule, abs_rule, app_rule, gen_rule, inst_rule]; for rule in rules.iter() { if let Ok(ty) = rule(tcs, tm) { return Ok(ty); } tcs.ty_exh.shrink(ty_exh_size); } Err("no match type") } fn var_rule(tcs: &mut TCS, tm: TmRef) -> TCM<TyRef> { match tcs.tm_exh.deref(tm) { Tm::Var(dbi) => { let depth = tcs.gamma.len(); let ty_ref = (tcs.gamma)[depth - dbi - 1]; Ok(ty_ref) } _ => Err("expected variable"), } } fn abs_rule(tcs: &mut TCS, tm: TmRef) -> TCM<TyRef> { match tcs.tm_exh.deref(tm) { Tm::Abs(param_ty, body) => { tcs.gamma.push(param_ty); let ret_ty = infer(tcs, body)?; tcs.gamma.pop(); let arr = tcs.ty_exh.arr(param_ty, ret_ty); Ok(arr) } _ => Err("expected lambda expression"), } } fn app_rule(tcs: &mut TCS, tm: TmRef) -> TCM<TyRef> { match tcs.tm_exh.deref(tm) { Tm::App(opt, opr) => { let arr = infer(tcs, opt)?; let (param_ty, ret_ty) = match tcs.ty_exh.deref(arr) { Ty::Arr(param_ty, ret_ty) => (param_ty, ret_ty), _ => return Err("not a function"), }; let arg_ty = infer(tcs, opr)?; if !tcs.ty_exh.eq(arg_ty, param_ty) { return Err("could not match as the same type"); } Ok(ret_ty) } _ => Err("excepted application"), } } fn gen_rule(tcs: &mut TCS, tm: TmRef) -> TCM<TyRef> { match tcs.tm_exh.deref(tm) { Tm::Gen(body) => { let ty = infer(tcs, body)?; let gen = tcs.ty_exh.for_all(ty); Ok(gen) } _ => Err("excepted generalization"), } } fn inst_rule(tcs: &mut TCS, tm: TmRef) -> TCM<TyRef> { match tcs.tm_exh.deref(tm) { Tm::Inst(tm, spec) => { let tm_ty = infer(tcs, tm)?; let for_all = match tcs.ty_exh.deref(tm_ty) { Ty::ForAll(t) => t, _ => return Err("not a generic type"), }; let res_ty = tcs.ty_exh.subst(for_all, spec, 0); Ok(res_ty) } _ => Err("excepted specification"), } } #[cfg(test)] mod test { use crate::ast::{TmExpr, TyExpr}; use crate::exhibit::{TmExhibit, TyExhibit}; use crate::tcm::TCS; #[test] fn id() { let mut ty_exh = TyExhibit::new(); let mut tm_exh = TmExhibit::new(); let gen_id_expr = TmExpr::Gen(Box::new(TmExpr::Abs( TyExpr::Var(0), Box::new(TmExpr::Var(0)), ))); let gen_id = tm_exh.alloc(&gen_id_expr, &mut ty_exh); assert_eq!(tm_exh.quote(gen_id, &ty_exh), gen_id_expr); let expected_ty_expr = TyExpr::ForAll(Box::new(TyExpr::Arr( Box::new(TyExpr::Var(0)), Box::new(TyExpr::Var(0)), ))); let expected_ty = ty_exh.alloc(&expected_ty_expr); assert_eq!(ty_exh.quote(expected_ty), expected_ty_expr); let mut tcs = TCS::new(tm_exh, ty_exh); let inferred_ty = tcs.infer(gen_id).unwrap(); assert!(tcs.ty_exh.eq(expected_ty, inferred_ty)); } #[test] fn r#const() { let mut ty_exh = TyExhibit::new(); let mut tm_exh = TmExhibit::new(); let gen_const_expr = TmExpr::Gen(Box::new(TmExpr::Gen(Box::new(TmExpr::Abs( TyExpr::Var(1), Box::new(TmExpr::Abs(TyExpr::Var(0), Box::new(TmExpr::Var(1)))), ))))); let gen_const = tm_exh.alloc(&gen_const_expr, &mut ty_exh); assert_eq!(tm_exh.quote(gen_const, &ty_exh), gen_const_expr); let expected_ty_expr = TyExpr::ForAll(Box::new(TyExpr::ForAll(Box::new(TyExpr::Arr( Box::new(TyExpr::Var(1)), Box::new(TyExpr::Arr( Box::new(TyExpr::Var(0)), Box::new(TyExpr::Var(1)), )), ))))); let expected_ty = ty_exh.alloc(&expected_ty_expr); assert_eq!(ty_exh.quote(expected_ty), expected_ty_expr); let mut tcs = TCS::new(tm_exh, ty_exh); let inferred_ty = tcs.infer(gen_const).unwrap(); assert!(tcs.ty_exh.eq(expected_ty, inferred_ty)); } #[test] fn one() { let mut ty_exh = TyExhibit::new(); let mut tm_exh = TmExhibit::new(); let one_expr = TmExpr::Gen(Box::new(TmExpr::Abs( TyExpr::Var(0), Box::new(TmExpr::Abs( TyExpr::ForAll(Box::new(TyExpr::Arr( Box::new(TyExpr::Var(0)), Box::new(TyExpr::Var(1)), ))), Box::new(TmExpr::App( Box::new(TmExpr::Inst(Box::new(TmExpr::Var(0)), TyExpr::Var(0))), Box::new(TmExpr::Var(1)), )), )), ))); let one_const = tm_exh.alloc(&one_expr, &mut ty_exh); assert_eq!(tm_exh.quote(one_const, &ty_exh), one_expr); let expected_ty_expr = TyExpr::ForAll(Box::new(TyExpr::Arr( Box::new(TyExpr::Var(0)), Box::new(TyExpr::Arr( Box::new(TyExpr::ForAll(Box::new(TyExpr::Arr( Box::new(TyExpr::Var(0)), Box::new(TyExpr::Var(1)), )))), Box::new(TyExpr::Var(0)), )), ))); let expected_ty = ty_exh.alloc(&expected_ty_expr); assert_eq!(ty_exh.quote(expected_ty), expected_ty_expr); let mut tcs = TCS::new(tm_exh, ty_exh); let inferred_ty = tcs.infer(one_const).unwrap(); assert!(tcs.ty_exh.eq(expected_ty, inferred_ty)); } }
use crate::split_whitespace_and_convert_to_i64; fn number_increasing(last: impl Iterator<Item = i64>, cur: impl Iterator<Item = i64>) -> usize { cur.zip(last).fold(0, |increasing_count, (cur, last)| { if cur > last { increasing_count + 1 } else { increasing_count } }) } pub fn part1(input: String) { let last = split_whitespace_and_convert_to_i64(&input); let cur = { let mut cur = split_whitespace_and_convert_to_i64(&input); cur.next(); cur }; println!("Number increasing: {}", number_increasing(last, cur),); } fn window_sums(input: &str) -> impl Iterator<Item = i64> + '_ { let depths0 = split_whitespace_and_convert_to_i64(input); let mut depths1 = split_whitespace_and_convert_to_i64(input); depths1.next(); let depths1 = depths1; let mut depths2 = split_whitespace_and_convert_to_i64(input); depths2.next(); depths2.next(); let depths2 = depths2; depths0 .zip(depths1) .zip(depths2) .map(|((a, b), c)| a + b + c) } pub fn part2(input: String) { let last = window_sums(&input); let cur = { let mut cur = window_sums(&input); cur.next(); cur }; println!("Number increasing: {}", number_increasing(last, cur)); }
use std::env; use std::fmt::{self, Debug, Formatter}; /// S3 credentials #[derive(Clone, PartialEq, Eq)] pub struct Credentials { key: String, secret: String, } impl Credentials { /// Construct a new `Credentials` using the provided key and secret #[inline] pub fn new(key: String, secret: String) -> Self { Self { key, secret } } /// Construct a new `Credentials` using AWS's default environment variables /// /// Reads the key from the `AWS_ACCESS_KEY_ID` environment variable and the secret /// from the `AWS_SECRET_ACCESS_KEY` environment variable. /// Returns `None` if either environment variables aren't set or they aren't valid utf-8. pub fn from_env() -> Option<Self> { let key = env::var("AWS_ACCESS_KEY_ID").ok()?; let secret = env::var("AWS_SECRET_ACCESS_KEY").ok()?; Some(Self::new(key, secret)) } /// Get the key of this `Credentials` #[inline] pub fn key(&self) -> &str { &self.key } /// Get the secret of this `Credentials` #[inline] pub fn secret(&self) -> &str { &self.secret } } impl Debug for Credentials { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("Credentials") .field("key", &self.key) .finish() } } #[cfg(test)] mod tests { use pretty_assertions::assert_eq; use super::*; #[test] fn key_secret() { let credentials = Credentials::new("abcd".into(), "1234".into()); assert_eq!(credentials.key(), "abcd"); assert_eq!(credentials.secret(), "1234"); } #[test] fn debug() { let credentials = Credentials::new("abcd".into(), "1234".into()); let debug_output = format!("{:?}", credentials); assert_eq!(debug_output, "Credentials { key: \"abcd\" }"); } #[test] fn from_env() { env::set_var("AWS_ACCESS_KEY_ID", "key"); env::set_var("AWS_SECRET_ACCESS_KEY", "secret"); let credentials = Credentials::from_env().unwrap(); assert_eq!(credentials.key(), "key"); assert_eq!(credentials.secret(), "secret"); env::remove_var("AWS_ACCESS_KEY_ID"); env::remove_var("AWS_SECRET_ACCESS_KEY"); assert!(Credentials::from_env().is_none()); } }
native "rust" mod rustrt { fn task_sleep(time_in_us: uint); fn task_yield(); fn task_join(t: task) -> int; fn unsupervise(); fn pin_task(); fn unpin_task(); fn clone_chan(c: *rust_chan) -> *rust_chan; type rust_chan; fn set_min_stack(stack_size: uint); } /** * Hints the scheduler to yield this task for a specified ammount of time. * * arg: time_in_us maximum number of microseconds to yield control for */ fn sleep(time_in_us: uint) { ret rustrt::task_sleep(time_in_us); } fn yield() { ret rustrt::task_yield(); } tag task_result { tr_success; tr_failure; } fn join(t: task) -> task_result { alt rustrt::task_join(t) { 0 { tr_success } _ { tr_failure } } } fn unsupervise() { ret rustrt::unsupervise(); } fn pin() { rustrt::pin_task(); } fn unpin() { rustrt::unpin_task(); } fn clone_chan[T](c: chan[T]) -> chan[T] { let cloned = rustrt::clone_chan(unsafe::reinterpret_cast(c)); ret unsafe::reinterpret_cast(cloned); } fn send[T](c: chan[T], v: &T) { c <| v; } fn recv[T](p: port[T]) -> T { let v; p |> v; v } fn set_min_stack(stack_size : uint) { rustrt::set_min_stack(stack_size); } // Local Variables: // mode: rust; // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End:
use allegro::{Color}; use allegro_font::{Font, FontAlign, FontDrawing}; use std::u8; #[no_mangle] pub struct Loading { pub base_text: String, /// The number of dots to display. pub dot_count: i8, /// The number of dots after which they will be reset to 0. pub dot_max: i8, /// Number of frames before adding the next dot. pub dot_delay: i8, /// Incremented once each frame. pub dot_timer: i8, pub map: Option<::TiledMap>, } impl Loading { pub fn new(_: &::Platform) -> Loading{ Loading{ base_text: String::from("Loading"), dot_count: 0, dot_max: 3, dot_delay: 15, dot_timer: 0, map: None, } } pub fn render(&self, p: &::Platform) { let font = Font::new_builtin(&p.font_addon).unwrap(); let color = Color::from_rgb(u8::MAX, u8::MAX, u8::MAX); let pos = (10.0, 10.0); // (x, y) let align = FontAlign::Left; let dots = (0..self.dot_count).map(|_| '.').collect::<String>(); p.core.draw_text(&font, color, pos.0, pos.1, align, &(String::from("Loading") + &dots)[..]); } pub fn update(mut self, p: &::Platform) -> ::State { if self.map.is_none() { self.map = Some(::TiledMap::load(&p.core, "../assets/maps/city.tmx")); } // Handle the dot animation. if self.dot_timer >= self.dot_delay { self.dot_count = if self.dot_count < self.dot_max { self.dot_count + 1 } else { 0 }; self.dot_timer = 0; if self.dot_count == 0 && self.map.is_some() { // Done loading. return ::State::Game(::states::game::Game::new(self.map.unwrap())); } } else { self.dot_timer += 1; } ::State::Loading(self) } }
use procon_reader::ProconReader; use union_find::UnionFind; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let a: Vec<usize> = rd.get_vec(n); let mut uf = UnionFind::new(2_000_00 + 1); let mut ans = 0; for i in 0..(n / 2) { if !uf.same(a[i], a[n - i - 1]) { ans += 1; uf.unite(a[i], a[n - i - 1]); } } println!("{}", ans); }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qpainterpath.h // dst-file: /src/gui/qpainterpath.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 super::qmatrix::*; // 773 use super::qpolygon::*; // 773 use super::qtransform::*; // 773 // use super::qlist::*; // 775 use super::super::core::qrect::*; // 771 use super::super::core::qpoint::*; // 771 use super::qfont::*; // 773 use super::super::core::qstring::*; // 771 use super::qregion::*; // 773 use super::qpen::*; // 773 // use super::qvector::*; // 775 // use super::qpainterpath::QPainterPath; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QPainterPath_Class_Size() -> c_int; // proto: void QPainterPath::setElementPositionAt(int i, qreal x, qreal y); fn C_ZN12QPainterPath20setElementPositionAtEidd(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_double, arg2: c_double); // proto: QPolygonF QPainterPath::toFillPolygon(const QMatrix & matrix); fn C_ZNK12QPainterPath13toFillPolygonERK7QMatrix(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QPainterPath QPainterPath::translated(qreal dx, qreal dy); fn C_ZNK12QPainterPath10translatedEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double) -> *mut c_void; // proto: void QPainterPath::~QPainterPath(); fn C_ZN12QPainterPathD2Ev(qthis: u64 /* *mut c_void*/); // proto: QList<QPolygonF> QPainterPath::toSubpathPolygons(const QTransform & matrix); fn C_ZNK12QPainterPath17toSubpathPolygonsERK10QTransform(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QRectF QPainterPath::controlPointRect(); fn C_ZNK12QPainterPath16controlPointRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QList<QPolygonF> QPainterPath::toFillPolygons(const QMatrix & matrix); fn C_ZNK12QPainterPath14toFillPolygonsERK7QMatrix(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QPainterPath QPainterPath::translated(const QPointF & offset); fn C_ZNK12QPainterPath10translatedERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::quadTo(const QPointF & ctrlPt, const QPointF & endPt); fn C_ZN12QPainterPath6quadToERK7QPointFS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: QList<QPolygonF> QPainterPath::toFillPolygons(const QTransform & matrix); fn C_ZNK12QPainterPath14toFillPolygonsERK10QTransform(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::arcTo(qreal x, qreal y, qreal w, qreal h, qreal startAngle, qreal arcLength); fn C_ZN12QPainterPath5arcToEdddddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_double, arg5: c_double); // proto: void QPainterPath::addRect(const QRectF & rect); fn C_ZN12QPainterPath7addRectERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPainterPath::addRoundRect(const QRectF & rect, int xRnd, int yRnd); fn C_ZN12QPainterPath12addRoundRectERK6QRectFii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int); // proto: void QPainterPath::addText(qreal x, qreal y, const QFont & f, const QString & text); fn C_ZN12QPainterPath7addTextEddRK5QFontRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: *mut c_void, arg3: *mut c_void); // proto: bool QPainterPath::intersects(const QRectF & rect); fn C_ZNK12QPainterPath10intersectsERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: bool QPainterPath::contains(const QPointF & pt); fn C_ZNK12QPainterPath8containsERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QPainterPath::arcTo(const QRectF & rect, qreal startAngle, qreal arcLength); fn C_ZN12QPainterPath5arcToERK6QRectFdd(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_double, arg2: c_double); // proto: void QPainterPath::addRoundRect(const QRectF & rect, int roundness); fn C_ZN12QPainterPath12addRoundRectERK6QRectFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int); // proto: void QPainterPath::addEllipse(const QPointF & center, qreal rx, qreal ry); fn C_ZN12QPainterPath10addEllipseERK7QPointFdd(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_double, arg2: c_double); // proto: void QPainterPath::lineTo(qreal x, qreal y); fn C_ZN12QPainterPath6lineToEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double); // proto: void QPainterPath::cubicTo(const QPointF & ctrlPt1, const QPointF & ctrlPt2, const QPointF & endPt); fn C_ZN12QPainterPath7cubicToERK7QPointFS2_S2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: qreal QPainterPath::slopeAtPercent(qreal t); fn C_ZNK12QPainterPath14slopeAtPercentEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> c_double; // proto: void QPainterPath::addEllipse(qreal x, qreal y, qreal w, qreal h); fn C_ZN12QPainterPath10addEllipseEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double); // proto: bool QPainterPath::intersects(const QPainterPath & p); fn C_ZNK12QPainterPath10intersectsERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QPainterPath::addRoundRect(qreal x, qreal y, qreal w, qreal h, int roundness); fn C_ZN12QPainterPath12addRoundRectEddddi(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_int); // proto: void QPainterPath::QPainterPath(const QPointF & startPoint); fn C_ZN12QPainterPathC2ERK7QPointF(arg0: *mut c_void) -> u64; // proto: QPainterPath QPainterPath::intersected(const QPainterPath & r); fn C_ZNK12QPainterPath11intersectedERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::translate(qreal dx, qreal dy); fn C_ZN12QPainterPath9translateEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double); // proto: void QPainterPath::addPolygon(const QPolygonF & polygon); fn C_ZN12QPainterPath10addPolygonERK9QPolygonF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPainterPath::translate(const QPointF & offset); fn C_ZN12QPainterPath9translateERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QPolygonF QPainterPath::toFillPolygon(const QTransform & matrix); fn C_ZNK12QPainterPath13toFillPolygonERK10QTransform(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::addPath(const QPainterPath & path); fn C_ZN12QPainterPath7addPathERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPainterPath::quadTo(qreal ctrlPtx, qreal ctrlPty, qreal endPtx, qreal endPty); fn C_ZN12QPainterPath6quadToEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double); // proto: int QPainterPath::elementCount(); fn C_ZNK12QPainterPath12elementCountEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: QPainterPath QPainterPath::simplified(); fn C_ZNK12QPainterPath10simplifiedEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QPainterPath::contains(const QRectF & rect); fn C_ZNK12QPainterPath8containsERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: qreal QPainterPath::length(); fn C_ZNK12QPainterPath6lengthEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: void QPainterPath::connectPath(const QPainterPath & path); fn C_ZN12QPainterPath11connectPathERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPainterPath::addRegion(const QRegion & region); fn C_ZN12QPainterPath9addRegionERK7QRegion(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QPointF QPainterPath::currentPosition(); fn C_ZNK12QPainterPath15currentPositionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QPainterPath QPainterPath::toReversed(); fn C_ZNK12QPainterPath10toReversedEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPainterPath::addRoundRect(qreal x, qreal y, qreal w, qreal h, int xRnd, int yRnd); fn C_ZN12QPainterPath12addRoundRectEddddii(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_int, arg5: c_int); // proto: QRectF QPainterPath::boundingRect(); fn C_ZNK12QPainterPath12boundingRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPainterPath::swap(QPainterPath & other); fn C_ZN12QPainterPath4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: bool QPainterPath::contains(const QPainterPath & p); fn C_ZNK12QPainterPath8containsERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QPainterPath::moveTo(qreal x, qreal y); fn C_ZN12QPainterPath6moveToEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double); // proto: QPainterPath QPainterPath::subtracted(const QPainterPath & r); fn C_ZNK12QPainterPath10subtractedERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::QPainterPath(); fn C_ZN12QPainterPathC2Ev() -> u64; // proto: void QPainterPath::addText(const QPointF & point, const QFont & f, const QString & text); fn C_ZN12QPainterPath7addTextERK7QPointFRK5QFontRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QPainterPath::QPainterPath(const QPainterPath & other); fn C_ZN12QPainterPathC2ERKS_(arg0: *mut c_void) -> u64; // proto: QPointF QPainterPath::pointAtPercent(qreal t); fn C_ZNK12QPainterPath14pointAtPercentEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> *mut c_void; // proto: qreal QPainterPath::percentAtLength(qreal t); fn C_ZNK12QPainterPath15percentAtLengthEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> c_double; // proto: void QPainterPath::cubicTo(qreal ctrlPt1x, qreal ctrlPt1y, qreal ctrlPt2x, qreal ctrlPt2y, qreal endPtx, qreal endPty); fn C_ZN12QPainterPath7cubicToEdddddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_double, arg5: c_double); // proto: void QPainterPath::lineTo(const QPointF & p); fn C_ZN12QPainterPath6lineToERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QPainterPath QPainterPath::subtractedInverted(const QPainterPath & r); fn C_ZNK12QPainterPath18subtractedInvertedERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::arcMoveTo(qreal x, qreal y, qreal w, qreal h, qreal angle); fn C_ZN12QPainterPath9arcMoveToEddddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: c_double); // proto: bool QPainterPath::isEmpty(); fn C_ZNK12QPainterPath7isEmptyEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPainterPath::addRect(qreal x, qreal y, qreal w, qreal h); fn C_ZN12QPainterPath7addRectEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double); // proto: void QPainterPath::arcMoveTo(const QRectF & rect, qreal angle); fn C_ZN12QPainterPath9arcMoveToERK6QRectFd(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_double); // proto: QList<QPolygonF> QPainterPath::toSubpathPolygons(const QMatrix & matrix); fn C_ZNK12QPainterPath17toSubpathPolygonsERK7QMatrix(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QPainterPath QPainterPath::united(const QPainterPath & r); fn C_ZNK12QPainterPath6unitedERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPath::addEllipse(const QRectF & rect); fn C_ZN12QPainterPath10addEllipseERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPainterPath::moveTo(const QPointF & p); fn C_ZN12QPainterPath6moveToERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: qreal QPainterPath::angleAtPercent(qreal t); fn C_ZNK12QPainterPath14angleAtPercentEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> c_double; // proto: void QPainterPath::closeSubpath(); fn C_ZN12QPainterPath12closeSubpathEv(qthis: u64 /* *mut c_void*/); fn QPainterPathStroker_Class_Size() -> c_int; // proto: qreal QPainterPathStroker::curveThreshold(); fn C_ZNK19QPainterPathStroker14curveThresholdEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: void QPainterPathStroker::setWidth(qreal width); fn C_ZN19QPainterPathStroker8setWidthEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: void QPainterPathStroker::~QPainterPathStroker(); fn C_ZN19QPainterPathStrokerD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QPainterPathStroker::setMiterLimit(qreal length); fn C_ZN19QPainterPathStroker13setMiterLimitEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: void QPainterPathStroker::QPainterPathStroker(const QPen & pen); fn C_ZN19QPainterPathStrokerC2ERK4QPen(arg0: *mut c_void) -> u64; // proto: void QPainterPathStroker::setCurveThreshold(qreal threshold); fn C_ZN19QPainterPathStroker17setCurveThresholdEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: QVector<qreal> QPainterPathStroker::dashPattern(); fn C_ZNK19QPainterPathStroker11dashPatternEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: qreal QPainterPathStroker::dashOffset(); fn C_ZNK19QPainterPathStroker10dashOffsetEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: void QPainterPathStroker::QPainterPathStroker(); fn C_ZN19QPainterPathStrokerC2Ev() -> u64; // proto: QPainterPath QPainterPathStroker::createStroke(const QPainterPath & path); fn C_ZNK19QPainterPathStroker12createStrokeERK12QPainterPath(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPainterPathStroker::setDashOffset(qreal offset); fn C_ZN19QPainterPathStroker13setDashOffsetEd(qthis: u64 /* *mut c_void*/, arg0: c_double); // proto: qreal QPainterPathStroker::width(); fn C_ZNK19QPainterPathStroker5widthEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: qreal QPainterPathStroker::miterLimit(); fn C_ZNK19QPainterPathStroker10miterLimitEv(qthis: u64 /* *mut c_void*/) -> c_double; } // <= ext block end // body block begin => // class sizeof(QPainterPath)=1 #[derive(Default)] pub struct QPainterPath { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } // class sizeof(QPainterPathStroker)=1 #[derive(Default)] pub struct QPainterPathStroker { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QPainterPath { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QPainterPath { return QPainterPath{qclsinst: qthis, ..Default::default()}; } } // proto: void QPainterPath::setElementPositionAt(int i, qreal x, qreal y); impl /*struct*/ QPainterPath { pub fn setElementPositionAt<RetType, T: QPainterPath_setElementPositionAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setElementPositionAt(self); // return 1; } } pub trait QPainterPath_setElementPositionAt<RetType> { fn setElementPositionAt(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::setElementPositionAt(int i, qreal x, qreal y); impl<'a> /*trait*/ QPainterPath_setElementPositionAt<()> for (i32, f64, f64) { fn setElementPositionAt(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath20setElementPositionAtEidd()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; unsafe {C_ZN12QPainterPath20setElementPositionAtEidd(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: QPolygonF QPainterPath::toFillPolygon(const QMatrix & matrix); impl /*struct*/ QPainterPath { pub fn toFillPolygon<RetType, T: QPainterPath_toFillPolygon<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toFillPolygon(self); // return 1; } } pub trait QPainterPath_toFillPolygon<RetType> { fn toFillPolygon(self , rsthis: & QPainterPath) -> RetType; } // proto: QPolygonF QPainterPath::toFillPolygon(const QMatrix & matrix); impl<'a> /*trait*/ QPainterPath_toFillPolygon<QPolygonF> for (Option<&'a QMatrix>) { fn toFillPolygon(self , rsthis: & QPainterPath) -> QPolygonF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath13toFillPolygonERK7QMatrix()}; let arg0 = (if self.is_none() {QMatrix::new(()).qclsinst} else {self.unwrap().qclsinst}) as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath13toFillPolygonERK7QMatrix(rsthis.qclsinst, arg0)}; let mut ret1 = QPolygonF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPainterPath QPainterPath::translated(qreal dx, qreal dy); impl /*struct*/ QPainterPath { pub fn translated<RetType, T: QPainterPath_translated<RetType>>(& self, overload_args: T) -> RetType { return overload_args.translated(self); // return 1; } } pub trait QPainterPath_translated<RetType> { fn translated(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::translated(qreal dx, qreal dy); impl<'a> /*trait*/ QPainterPath_translated<QPainterPath> for (f64, f64) { fn translated(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10translatedEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let mut ret = unsafe {C_ZNK12QPainterPath10translatedEdd(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::~QPainterPath(); impl /*struct*/ QPainterPath { pub fn free<RetType, T: QPainterPath_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QPainterPath_free<RetType> { fn free(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::~QPainterPath(); impl<'a> /*trait*/ QPainterPath_free<()> for () { fn free(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPathD2Ev()}; unsafe {C_ZN12QPainterPathD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QList<QPolygonF> QPainterPath::toSubpathPolygons(const QTransform & matrix); impl /*struct*/ QPainterPath { pub fn toSubpathPolygons<RetType, T: QPainterPath_toSubpathPolygons<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toSubpathPolygons(self); // return 1; } } pub trait QPainterPath_toSubpathPolygons<RetType> { fn toSubpathPolygons(self , rsthis: & QPainterPath) -> RetType; } // proto: QList<QPolygonF> QPainterPath::toSubpathPolygons(const QTransform & matrix); impl<'a> /*trait*/ QPainterPath_toSubpathPolygons<u64> for (&'a QTransform) { fn toSubpathPolygons(self , rsthis: & QPainterPath) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath17toSubpathPolygonsERK10QTransform()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath17toSubpathPolygonsERK10QTransform(rsthis.qclsinst, arg0)}; return ret as u64; // 5 // return 1; } } // proto: QRectF QPainterPath::controlPointRect(); impl /*struct*/ QPainterPath { pub fn controlPointRect<RetType, T: QPainterPath_controlPointRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.controlPointRect(self); // return 1; } } pub trait QPainterPath_controlPointRect<RetType> { fn controlPointRect(self , rsthis: & QPainterPath) -> RetType; } // proto: QRectF QPainterPath::controlPointRect(); impl<'a> /*trait*/ QPainterPath_controlPointRect<QRectF> for () { fn controlPointRect(self , rsthis: & QPainterPath) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath16controlPointRectEv()}; let mut ret = unsafe {C_ZNK12QPainterPath16controlPointRectEv(rsthis.qclsinst)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QList<QPolygonF> QPainterPath::toFillPolygons(const QMatrix & matrix); impl /*struct*/ QPainterPath { pub fn toFillPolygons<RetType, T: QPainterPath_toFillPolygons<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toFillPolygons(self); // return 1; } } pub trait QPainterPath_toFillPolygons<RetType> { fn toFillPolygons(self , rsthis: & QPainterPath) -> RetType; } // proto: QList<QPolygonF> QPainterPath::toFillPolygons(const QMatrix & matrix); impl<'a> /*trait*/ QPainterPath_toFillPolygons<u64> for (Option<&'a QMatrix>) { fn toFillPolygons(self , rsthis: & QPainterPath) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath14toFillPolygonsERK7QMatrix()}; let arg0 = (if self.is_none() {QMatrix::new(()).qclsinst} else {self.unwrap().qclsinst}) as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath14toFillPolygonsERK7QMatrix(rsthis.qclsinst, arg0)}; return ret as u64; // 5 // return 1; } } // proto: QPainterPath QPainterPath::translated(const QPointF & offset); impl<'a> /*trait*/ QPainterPath_translated<QPainterPath> for (&'a QPointF) { fn translated(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10translatedERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath10translatedERK7QPointF(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::quadTo(const QPointF & ctrlPt, const QPointF & endPt); impl /*struct*/ QPainterPath { pub fn quadTo<RetType, T: QPainterPath_quadTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.quadTo(self); // return 1; } } pub trait QPainterPath_quadTo<RetType> { fn quadTo(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::quadTo(const QPointF & ctrlPt, const QPointF & endPt); impl<'a> /*trait*/ QPainterPath_quadTo<()> for (&'a QPointF, &'a QPointF) { fn quadTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath6quadToERK7QPointFS2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath6quadToERK7QPointFS2_(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QList<QPolygonF> QPainterPath::toFillPolygons(const QTransform & matrix); impl<'a> /*trait*/ QPainterPath_toFillPolygons<u64> for (&'a QTransform) { fn toFillPolygons(self , rsthis: & QPainterPath) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath14toFillPolygonsERK10QTransform()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath14toFillPolygonsERK10QTransform(rsthis.qclsinst, arg0)}; return ret as u64; // 5 // return 1; } } // proto: void QPainterPath::arcTo(qreal x, qreal y, qreal w, qreal h, qreal startAngle, qreal arcLength); impl /*struct*/ QPainterPath { pub fn arcTo<RetType, T: QPainterPath_arcTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.arcTo(self); // return 1; } } pub trait QPainterPath_arcTo<RetType> { fn arcTo(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::arcTo(qreal x, qreal y, qreal w, qreal h, qreal startAngle, qreal arcLength); impl<'a> /*trait*/ QPainterPath_arcTo<()> for (f64, f64, f64, f64, f64, f64) { fn arcTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath5arcToEdddddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_double; let arg5 = self.5 as c_double; unsafe {C_ZN12QPainterPath5arcToEdddddd(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: void QPainterPath::addRect(const QRectF & rect); impl /*struct*/ QPainterPath { pub fn addRect<RetType, T: QPainterPath_addRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addRect(self); // return 1; } } pub trait QPainterPath_addRect<RetType> { fn addRect(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addRect(const QRectF & rect); impl<'a> /*trait*/ QPainterPath_addRect<()> for (&'a QRectF) { fn addRect(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7addRectERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath7addRectERK6QRectF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPath::addRoundRect(const QRectF & rect, int xRnd, int yRnd); impl /*struct*/ QPainterPath { pub fn addRoundRect<RetType, T: QPainterPath_addRoundRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addRoundRect(self); // return 1; } } pub trait QPainterPath_addRoundRect<RetType> { fn addRoundRect(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addRoundRect(const QRectF & rect, int xRnd, int yRnd); impl<'a> /*trait*/ QPainterPath_addRoundRect<()> for (&'a QRectF, i32, i32) { fn addRoundRect(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath12addRoundRectERK6QRectFii()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_int; let arg2 = self.2 as c_int; unsafe {C_ZN12QPainterPath12addRoundRectERK6QRectFii(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QPainterPath::addText(qreal x, qreal y, const QFont & f, const QString & text); impl /*struct*/ QPainterPath { pub fn addText<RetType, T: QPainterPath_addText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addText(self); // return 1; } } pub trait QPainterPath_addText<RetType> { fn addText(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addText(qreal x, qreal y, const QFont & f, const QString & text); impl<'a> /*trait*/ QPainterPath_addText<()> for (f64, f64, &'a QFont, &'a QString) { fn addText(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7addTextEddRK5QFontRK7QString()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2.qclsinst as *mut c_void; let arg3 = self.3.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath7addTextEddRK5QFontRK7QString(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: bool QPainterPath::intersects(const QRectF & rect); impl /*struct*/ QPainterPath { pub fn intersects<RetType, T: QPainterPath_intersects<RetType>>(& self, overload_args: T) -> RetType { return overload_args.intersects(self); // return 1; } } pub trait QPainterPath_intersects<RetType> { fn intersects(self , rsthis: & QPainterPath) -> RetType; } // proto: bool QPainterPath::intersects(const QRectF & rect); impl<'a> /*trait*/ QPainterPath_intersects<i8> for (&'a QRectF) { fn intersects(self , rsthis: & QPainterPath) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10intersectsERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath10intersectsERK6QRectF(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: bool QPainterPath::contains(const QPointF & pt); impl /*struct*/ QPainterPath { pub fn contains<RetType, T: QPainterPath_contains<RetType>>(& self, overload_args: T) -> RetType { return overload_args.contains(self); // return 1; } } pub trait QPainterPath_contains<RetType> { fn contains(self , rsthis: & QPainterPath) -> RetType; } // proto: bool QPainterPath::contains(const QPointF & pt); impl<'a> /*trait*/ QPainterPath_contains<i8> for (&'a QPointF) { fn contains(self , rsthis: & QPainterPath) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath8containsERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath8containsERK7QPointF(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QPainterPath::arcTo(const QRectF & rect, qreal startAngle, qreal arcLength); impl<'a> /*trait*/ QPainterPath_arcTo<()> for (&'a QRectF, f64, f64) { fn arcTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath5arcToERK6QRectFdd()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; unsafe {C_ZN12QPainterPath5arcToERK6QRectFdd(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QPainterPath::addRoundRect(const QRectF & rect, int roundness); impl<'a> /*trait*/ QPainterPath_addRoundRect<()> for (&'a QRectF, i32) { fn addRoundRect(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath12addRoundRectERK6QRectFi()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_int; unsafe {C_ZN12QPainterPath12addRoundRectERK6QRectFi(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QPainterPath::addEllipse(const QPointF & center, qreal rx, qreal ry); impl /*struct*/ QPainterPath { pub fn addEllipse<RetType, T: QPainterPath_addEllipse<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addEllipse(self); // return 1; } } pub trait QPainterPath_addEllipse<RetType> { fn addEllipse(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addEllipse(const QPointF & center, qreal rx, qreal ry); impl<'a> /*trait*/ QPainterPath_addEllipse<()> for (&'a QPointF, f64, f64) { fn addEllipse(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath10addEllipseERK7QPointFdd()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; unsafe {C_ZN12QPainterPath10addEllipseERK7QPointFdd(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QPainterPath::lineTo(qreal x, qreal y); impl /*struct*/ QPainterPath { pub fn lineTo<RetType, T: QPainterPath_lineTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.lineTo(self); // return 1; } } pub trait QPainterPath_lineTo<RetType> { fn lineTo(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::lineTo(qreal x, qreal y); impl<'a> /*trait*/ QPainterPath_lineTo<()> for (f64, f64) { fn lineTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath6lineToEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; unsafe {C_ZN12QPainterPath6lineToEdd(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QPainterPath::cubicTo(const QPointF & ctrlPt1, const QPointF & ctrlPt2, const QPointF & endPt); impl /*struct*/ QPainterPath { pub fn cubicTo<RetType, T: QPainterPath_cubicTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cubicTo(self); // return 1; } } pub trait QPainterPath_cubicTo<RetType> { fn cubicTo(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::cubicTo(const QPointF & ctrlPt1, const QPointF & ctrlPt2, const QPointF & endPt); impl<'a> /*trait*/ QPainterPath_cubicTo<()> for (&'a QPointF, &'a QPointF, &'a QPointF) { fn cubicTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7cubicToERK7QPointFS2_S2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath7cubicToERK7QPointFS2_S2_(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: qreal QPainterPath::slopeAtPercent(qreal t); impl /*struct*/ QPainterPath { pub fn slopeAtPercent<RetType, T: QPainterPath_slopeAtPercent<RetType>>(& self, overload_args: T) -> RetType { return overload_args.slopeAtPercent(self); // return 1; } } pub trait QPainterPath_slopeAtPercent<RetType> { fn slopeAtPercent(self , rsthis: & QPainterPath) -> RetType; } // proto: qreal QPainterPath::slopeAtPercent(qreal t); impl<'a> /*trait*/ QPainterPath_slopeAtPercent<f64> for (f64) { fn slopeAtPercent(self , rsthis: & QPainterPath) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath14slopeAtPercentEd()}; let arg0 = self as c_double; let mut ret = unsafe {C_ZNK12QPainterPath14slopeAtPercentEd(rsthis.qclsinst, arg0)}; return ret as f64; // 1 // return 1; } } // proto: void QPainterPath::addEllipse(qreal x, qreal y, qreal w, qreal h); impl<'a> /*trait*/ QPainterPath_addEllipse<()> for (f64, f64, f64, f64) { fn addEllipse(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath10addEllipseEdddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; unsafe {C_ZN12QPainterPath10addEllipseEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: bool QPainterPath::intersects(const QPainterPath & p); impl<'a> /*trait*/ QPainterPath_intersects<i8> for (&'a QPainterPath) { fn intersects(self , rsthis: & QPainterPath) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10intersectsERKS_()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath10intersectsERKS_(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QPainterPath::addRoundRect(qreal x, qreal y, qreal w, qreal h, int roundness); impl<'a> /*trait*/ QPainterPath_addRoundRect<()> for (f64, f64, f64, f64, i32) { fn addRoundRect(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath12addRoundRectEddddi()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_int; unsafe {C_ZN12QPainterPath12addRoundRectEddddi(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)}; // return 1; } } // proto: void QPainterPath::QPainterPath(const QPointF & startPoint); impl /*struct*/ QPainterPath { pub fn new<T: QPainterPath_new>(value: T) -> QPainterPath { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QPainterPath_new { fn new(self) -> QPainterPath; } // proto: void QPainterPath::QPainterPath(const QPointF & startPoint); impl<'a> /*trait*/ QPainterPath_new for (&'a QPointF) { fn new(self) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPathC2ERK7QPointF()}; let ctysz: c_int = unsafe{QPainterPath_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN12QPainterPathC2ERK7QPointF(arg0)}; let rsthis = QPainterPath{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QPainterPath QPainterPath::intersected(const QPainterPath & r); impl /*struct*/ QPainterPath { pub fn intersected<RetType, T: QPainterPath_intersected<RetType>>(& self, overload_args: T) -> RetType { return overload_args.intersected(self); // return 1; } } pub trait QPainterPath_intersected<RetType> { fn intersected(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::intersected(const QPainterPath & r); impl<'a> /*trait*/ QPainterPath_intersected<QPainterPath> for (&'a QPainterPath) { fn intersected(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath11intersectedERKS_()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath11intersectedERKS_(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::translate(qreal dx, qreal dy); impl /*struct*/ QPainterPath { pub fn translate<RetType, T: QPainterPath_translate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.translate(self); // return 1; } } pub trait QPainterPath_translate<RetType> { fn translate(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::translate(qreal dx, qreal dy); impl<'a> /*trait*/ QPainterPath_translate<()> for (f64, f64) { fn translate(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath9translateEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; unsafe {C_ZN12QPainterPath9translateEdd(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QPainterPath::addPolygon(const QPolygonF & polygon); impl /*struct*/ QPainterPath { pub fn addPolygon<RetType, T: QPainterPath_addPolygon<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addPolygon(self); // return 1; } } pub trait QPainterPath_addPolygon<RetType> { fn addPolygon(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addPolygon(const QPolygonF & polygon); impl<'a> /*trait*/ QPainterPath_addPolygon<()> for (&'a QPolygonF) { fn addPolygon(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath10addPolygonERK9QPolygonF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath10addPolygonERK9QPolygonF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPath::translate(const QPointF & offset); impl<'a> /*trait*/ QPainterPath_translate<()> for (&'a QPointF) { fn translate(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath9translateERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath9translateERK7QPointF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QPolygonF QPainterPath::toFillPolygon(const QTransform & matrix); impl<'a> /*trait*/ QPainterPath_toFillPolygon<QPolygonF> for (&'a QTransform) { fn toFillPolygon(self , rsthis: & QPainterPath) -> QPolygonF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath13toFillPolygonERK10QTransform()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath13toFillPolygonERK10QTransform(rsthis.qclsinst, arg0)}; let mut ret1 = QPolygonF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::addPath(const QPainterPath & path); impl /*struct*/ QPainterPath { pub fn addPath<RetType, T: QPainterPath_addPath<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addPath(self); // return 1; } } pub trait QPainterPath_addPath<RetType> { fn addPath(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addPath(const QPainterPath & path); impl<'a> /*trait*/ QPainterPath_addPath<()> for (&'a QPainterPath) { fn addPath(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7addPathERKS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath7addPathERKS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPath::quadTo(qreal ctrlPtx, qreal ctrlPty, qreal endPtx, qreal endPty); impl<'a> /*trait*/ QPainterPath_quadTo<()> for (f64, f64, f64, f64) { fn quadTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath6quadToEdddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; unsafe {C_ZN12QPainterPath6quadToEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: int QPainterPath::elementCount(); impl /*struct*/ QPainterPath { pub fn elementCount<RetType, T: QPainterPath_elementCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.elementCount(self); // return 1; } } pub trait QPainterPath_elementCount<RetType> { fn elementCount(self , rsthis: & QPainterPath) -> RetType; } // proto: int QPainterPath::elementCount(); impl<'a> /*trait*/ QPainterPath_elementCount<i32> for () { fn elementCount(self , rsthis: & QPainterPath) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath12elementCountEv()}; let mut ret = unsafe {C_ZNK12QPainterPath12elementCountEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: QPainterPath QPainterPath::simplified(); impl /*struct*/ QPainterPath { pub fn simplified<RetType, T: QPainterPath_simplified<RetType>>(& self, overload_args: T) -> RetType { return overload_args.simplified(self); // return 1; } } pub trait QPainterPath_simplified<RetType> { fn simplified(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::simplified(); impl<'a> /*trait*/ QPainterPath_simplified<QPainterPath> for () { fn simplified(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10simplifiedEv()}; let mut ret = unsafe {C_ZNK12QPainterPath10simplifiedEv(rsthis.qclsinst)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QPainterPath::contains(const QRectF & rect); impl<'a> /*trait*/ QPainterPath_contains<i8> for (&'a QRectF) { fn contains(self , rsthis: & QPainterPath) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath8containsERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath8containsERK6QRectF(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: qreal QPainterPath::length(); impl /*struct*/ QPainterPath { pub fn length<RetType, T: QPainterPath_length<RetType>>(& self, overload_args: T) -> RetType { return overload_args.length(self); // return 1; } } pub trait QPainterPath_length<RetType> { fn length(self , rsthis: & QPainterPath) -> RetType; } // proto: qreal QPainterPath::length(); impl<'a> /*trait*/ QPainterPath_length<f64> for () { fn length(self , rsthis: & QPainterPath) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath6lengthEv()}; let mut ret = unsafe {C_ZNK12QPainterPath6lengthEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: void QPainterPath::connectPath(const QPainterPath & path); impl /*struct*/ QPainterPath { pub fn connectPath<RetType, T: QPainterPath_connectPath<RetType>>(& self, overload_args: T) -> RetType { return overload_args.connectPath(self); // return 1; } } pub trait QPainterPath_connectPath<RetType> { fn connectPath(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::connectPath(const QPainterPath & path); impl<'a> /*trait*/ QPainterPath_connectPath<()> for (&'a QPainterPath) { fn connectPath(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath11connectPathERKS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath11connectPathERKS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPath::addRegion(const QRegion & region); impl /*struct*/ QPainterPath { pub fn addRegion<RetType, T: QPainterPath_addRegion<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addRegion(self); // return 1; } } pub trait QPainterPath_addRegion<RetType> { fn addRegion(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::addRegion(const QRegion & region); impl<'a> /*trait*/ QPainterPath_addRegion<()> for (&'a QRegion) { fn addRegion(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath9addRegionERK7QRegion()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath9addRegionERK7QRegion(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QPointF QPainterPath::currentPosition(); impl /*struct*/ QPainterPath { pub fn currentPosition<RetType, T: QPainterPath_currentPosition<RetType>>(& self, overload_args: T) -> RetType { return overload_args.currentPosition(self); // return 1; } } pub trait QPainterPath_currentPosition<RetType> { fn currentPosition(self , rsthis: & QPainterPath) -> RetType; } // proto: QPointF QPainterPath::currentPosition(); impl<'a> /*trait*/ QPainterPath_currentPosition<QPointF> for () { fn currentPosition(self , rsthis: & QPainterPath) -> QPointF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath15currentPositionEv()}; let mut ret = unsafe {C_ZNK12QPainterPath15currentPositionEv(rsthis.qclsinst)}; let mut ret1 = QPointF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPainterPath QPainterPath::toReversed(); impl /*struct*/ QPainterPath { pub fn toReversed<RetType, T: QPainterPath_toReversed<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toReversed(self); // return 1; } } pub trait QPainterPath_toReversed<RetType> { fn toReversed(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::toReversed(); impl<'a> /*trait*/ QPainterPath_toReversed<QPainterPath> for () { fn toReversed(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10toReversedEv()}; let mut ret = unsafe {C_ZNK12QPainterPath10toReversedEv(rsthis.qclsinst)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::addRoundRect(qreal x, qreal y, qreal w, qreal h, int xRnd, int yRnd); impl<'a> /*trait*/ QPainterPath_addRoundRect<()> for (f64, f64, f64, f64, i32, i32) { fn addRoundRect(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath12addRoundRectEddddii()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_int; let arg5 = self.5 as c_int; unsafe {C_ZN12QPainterPath12addRoundRectEddddii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: QRectF QPainterPath::boundingRect(); impl /*struct*/ QPainterPath { pub fn boundingRect<RetType, T: QPainterPath_boundingRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.boundingRect(self); // return 1; } } pub trait QPainterPath_boundingRect<RetType> { fn boundingRect(self , rsthis: & QPainterPath) -> RetType; } // proto: QRectF QPainterPath::boundingRect(); impl<'a> /*trait*/ QPainterPath_boundingRect<QRectF> for () { fn boundingRect(self , rsthis: & QPainterPath) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath12boundingRectEv()}; let mut ret = unsafe {C_ZNK12QPainterPath12boundingRectEv(rsthis.qclsinst)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::swap(QPainterPath & other); impl /*struct*/ QPainterPath { pub fn swap<RetType, T: QPainterPath_swap<RetType>>(& self, overload_args: T) -> RetType { return overload_args.swap(self); // return 1; } } pub trait QPainterPath_swap<RetType> { fn swap(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::swap(QPainterPath & other); impl<'a> /*trait*/ QPainterPath_swap<()> for (&'a QPainterPath) { fn swap(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath4swapERS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath4swapERS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QPainterPath::contains(const QPainterPath & p); impl<'a> /*trait*/ QPainterPath_contains<i8> for (&'a QPainterPath) { fn contains(self , rsthis: & QPainterPath) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath8containsERKS_()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath8containsERKS_(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QPainterPath::moveTo(qreal x, qreal y); impl /*struct*/ QPainterPath { pub fn moveTo<RetType, T: QPainterPath_moveTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.moveTo(self); // return 1; } } pub trait QPainterPath_moveTo<RetType> { fn moveTo(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::moveTo(qreal x, qreal y); impl<'a> /*trait*/ QPainterPath_moveTo<()> for (f64, f64) { fn moveTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath6moveToEdd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; unsafe {C_ZN12QPainterPath6moveToEdd(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QPainterPath QPainterPath::subtracted(const QPainterPath & r); impl /*struct*/ QPainterPath { pub fn subtracted<RetType, T: QPainterPath_subtracted<RetType>>(& self, overload_args: T) -> RetType { return overload_args.subtracted(self); // return 1; } } pub trait QPainterPath_subtracted<RetType> { fn subtracted(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::subtracted(const QPainterPath & r); impl<'a> /*trait*/ QPainterPath_subtracted<QPainterPath> for (&'a QPainterPath) { fn subtracted(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath10subtractedERKS_()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath10subtractedERKS_(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::QPainterPath(); impl<'a> /*trait*/ QPainterPath_new for () { fn new(self) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPathC2Ev()}; let ctysz: c_int = unsafe{QPainterPath_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN12QPainterPathC2Ev()}; let rsthis = QPainterPath{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QPainterPath::addText(const QPointF & point, const QFont & f, const QString & text); impl<'a> /*trait*/ QPainterPath_addText<()> for (&'a QPointF, &'a QFont, &'a QString) { fn addText(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7addTextERK7QPointFRK5QFontRK7QString()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath7addTextERK7QPointFRK5QFontRK7QString(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QPainterPath::QPainterPath(const QPainterPath & other); impl<'a> /*trait*/ QPainterPath_new for (&'a QPainterPath) { fn new(self) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPathC2ERKS_()}; let ctysz: c_int = unsafe{QPainterPath_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN12QPainterPathC2ERKS_(arg0)}; let rsthis = QPainterPath{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QPointF QPainterPath::pointAtPercent(qreal t); impl /*struct*/ QPainterPath { pub fn pointAtPercent<RetType, T: QPainterPath_pointAtPercent<RetType>>(& self, overload_args: T) -> RetType { return overload_args.pointAtPercent(self); // return 1; } } pub trait QPainterPath_pointAtPercent<RetType> { fn pointAtPercent(self , rsthis: & QPainterPath) -> RetType; } // proto: QPointF QPainterPath::pointAtPercent(qreal t); impl<'a> /*trait*/ QPainterPath_pointAtPercent<QPointF> for (f64) { fn pointAtPercent(self , rsthis: & QPainterPath) -> QPointF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath14pointAtPercentEd()}; let arg0 = self as c_double; let mut ret = unsafe {C_ZNK12QPainterPath14pointAtPercentEd(rsthis.qclsinst, arg0)}; let mut ret1 = QPointF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: qreal QPainterPath::percentAtLength(qreal t); impl /*struct*/ QPainterPath { pub fn percentAtLength<RetType, T: QPainterPath_percentAtLength<RetType>>(& self, overload_args: T) -> RetType { return overload_args.percentAtLength(self); // return 1; } } pub trait QPainterPath_percentAtLength<RetType> { fn percentAtLength(self , rsthis: & QPainterPath) -> RetType; } // proto: qreal QPainterPath::percentAtLength(qreal t); impl<'a> /*trait*/ QPainterPath_percentAtLength<f64> for (f64) { fn percentAtLength(self , rsthis: & QPainterPath) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath15percentAtLengthEd()}; let arg0 = self as c_double; let mut ret = unsafe {C_ZNK12QPainterPath15percentAtLengthEd(rsthis.qclsinst, arg0)}; return ret as f64; // 1 // return 1; } } // proto: void QPainterPath::cubicTo(qreal ctrlPt1x, qreal ctrlPt1y, qreal ctrlPt2x, qreal ctrlPt2y, qreal endPtx, qreal endPty); impl<'a> /*trait*/ QPainterPath_cubicTo<()> for (f64, f64, f64, f64, f64, f64) { fn cubicTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7cubicToEdddddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_double; let arg5 = self.5 as c_double; unsafe {C_ZN12QPainterPath7cubicToEdddddd(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: void QPainterPath::lineTo(const QPointF & p); impl<'a> /*trait*/ QPainterPath_lineTo<()> for (&'a QPointF) { fn lineTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath6lineToERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath6lineToERK7QPointF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QPainterPath QPainterPath::subtractedInverted(const QPainterPath & r); impl /*struct*/ QPainterPath { pub fn subtractedInverted<RetType, T: QPainterPath_subtractedInverted<RetType>>(& self, overload_args: T) -> RetType { return overload_args.subtractedInverted(self); // return 1; } } pub trait QPainterPath_subtractedInverted<RetType> { fn subtractedInverted(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::subtractedInverted(const QPainterPath & r); impl<'a> /*trait*/ QPainterPath_subtractedInverted<QPainterPath> for (&'a QPainterPath) { fn subtractedInverted(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath18subtractedInvertedERKS_()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath18subtractedInvertedERKS_(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::arcMoveTo(qreal x, qreal y, qreal w, qreal h, qreal angle); impl /*struct*/ QPainterPath { pub fn arcMoveTo<RetType, T: QPainterPath_arcMoveTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.arcMoveTo(self); // return 1; } } pub trait QPainterPath_arcMoveTo<RetType> { fn arcMoveTo(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::arcMoveTo(qreal x, qreal y, qreal w, qreal h, qreal angle); impl<'a> /*trait*/ QPainterPath_arcMoveTo<()> for (f64, f64, f64, f64, f64) { fn arcMoveTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath9arcMoveToEddddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; let arg4 = self.4 as c_double; unsafe {C_ZN12QPainterPath9arcMoveToEddddd(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)}; // return 1; } } // proto: bool QPainterPath::isEmpty(); impl /*struct*/ QPainterPath { pub fn isEmpty<RetType, T: QPainterPath_isEmpty<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isEmpty(self); // return 1; } } pub trait QPainterPath_isEmpty<RetType> { fn isEmpty(self , rsthis: & QPainterPath) -> RetType; } // proto: bool QPainterPath::isEmpty(); impl<'a> /*trait*/ QPainterPath_isEmpty<i8> for () { fn isEmpty(self , rsthis: & QPainterPath) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath7isEmptyEv()}; let mut ret = unsafe {C_ZNK12QPainterPath7isEmptyEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPainterPath::addRect(qreal x, qreal y, qreal w, qreal h); impl<'a> /*trait*/ QPainterPath_addRect<()> for (f64, f64, f64, f64) { fn addRect(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath7addRectEdddd()}; let arg0 = self.0 as c_double; let arg1 = self.1 as c_double; let arg2 = self.2 as c_double; let arg3 = self.3 as c_double; unsafe {C_ZN12QPainterPath7addRectEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: void QPainterPath::arcMoveTo(const QRectF & rect, qreal angle); impl<'a> /*trait*/ QPainterPath_arcMoveTo<()> for (&'a QRectF, f64) { fn arcMoveTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath9arcMoveToERK6QRectFd()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_double; unsafe {C_ZN12QPainterPath9arcMoveToERK6QRectFd(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QList<QPolygonF> QPainterPath::toSubpathPolygons(const QMatrix & matrix); impl<'a> /*trait*/ QPainterPath_toSubpathPolygons<u64> for (Option<&'a QMatrix>) { fn toSubpathPolygons(self , rsthis: & QPainterPath) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath17toSubpathPolygonsERK7QMatrix()}; let arg0 = (if self.is_none() {QMatrix::new(()).qclsinst} else {self.unwrap().qclsinst}) as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath17toSubpathPolygonsERK7QMatrix(rsthis.qclsinst, arg0)}; return ret as u64; // 5 // return 1; } } // proto: QPainterPath QPainterPath::united(const QPainterPath & r); impl /*struct*/ QPainterPath { pub fn united<RetType, T: QPainterPath_united<RetType>>(& self, overload_args: T) -> RetType { return overload_args.united(self); // return 1; } } pub trait QPainterPath_united<RetType> { fn united(self , rsthis: & QPainterPath) -> RetType; } // proto: QPainterPath QPainterPath::united(const QPainterPath & r); impl<'a> /*trait*/ QPainterPath_united<QPainterPath> for (&'a QPainterPath) { fn united(self , rsthis: & QPainterPath) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath6unitedERKS_()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK12QPainterPath6unitedERKS_(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPath::addEllipse(const QRectF & rect); impl<'a> /*trait*/ QPainterPath_addEllipse<()> for (&'a QRectF) { fn addEllipse(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath10addEllipseERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath10addEllipseERK6QRectF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPath::moveTo(const QPointF & p); impl<'a> /*trait*/ QPainterPath_moveTo<()> for (&'a QPointF) { fn moveTo(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath6moveToERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QPainterPath6moveToERK7QPointF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: qreal QPainterPath::angleAtPercent(qreal t); impl /*struct*/ QPainterPath { pub fn angleAtPercent<RetType, T: QPainterPath_angleAtPercent<RetType>>(& self, overload_args: T) -> RetType { return overload_args.angleAtPercent(self); // return 1; } } pub trait QPainterPath_angleAtPercent<RetType> { fn angleAtPercent(self , rsthis: & QPainterPath) -> RetType; } // proto: qreal QPainterPath::angleAtPercent(qreal t); impl<'a> /*trait*/ QPainterPath_angleAtPercent<f64> for (f64) { fn angleAtPercent(self , rsthis: & QPainterPath) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QPainterPath14angleAtPercentEd()}; let arg0 = self as c_double; let mut ret = unsafe {C_ZNK12QPainterPath14angleAtPercentEd(rsthis.qclsinst, arg0)}; return ret as f64; // 1 // return 1; } } // proto: void QPainterPath::closeSubpath(); impl /*struct*/ QPainterPath { pub fn closeSubpath<RetType, T: QPainterPath_closeSubpath<RetType>>(& self, overload_args: T) -> RetType { return overload_args.closeSubpath(self); // return 1; } } pub trait QPainterPath_closeSubpath<RetType> { fn closeSubpath(self , rsthis: & QPainterPath) -> RetType; } // proto: void QPainterPath::closeSubpath(); impl<'a> /*trait*/ QPainterPath_closeSubpath<()> for () { fn closeSubpath(self , rsthis: & QPainterPath) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QPainterPath12closeSubpathEv()}; unsafe {C_ZN12QPainterPath12closeSubpathEv(rsthis.qclsinst)}; // return 1; } } impl /*struct*/ QPainterPathStroker { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QPainterPathStroker { return QPainterPathStroker{qclsinst: qthis, ..Default::default()}; } } // proto: qreal QPainterPathStroker::curveThreshold(); impl /*struct*/ QPainterPathStroker { pub fn curveThreshold<RetType, T: QPainterPathStroker_curveThreshold<RetType>>(& self, overload_args: T) -> RetType { return overload_args.curveThreshold(self); // return 1; } } pub trait QPainterPathStroker_curveThreshold<RetType> { fn curveThreshold(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: qreal QPainterPathStroker::curveThreshold(); impl<'a> /*trait*/ QPainterPathStroker_curveThreshold<f64> for () { fn curveThreshold(self , rsthis: & QPainterPathStroker) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QPainterPathStroker14curveThresholdEv()}; let mut ret = unsafe {C_ZNK19QPainterPathStroker14curveThresholdEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: void QPainterPathStroker::setWidth(qreal width); impl /*struct*/ QPainterPathStroker { pub fn setWidth<RetType, T: QPainterPathStroker_setWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setWidth(self); // return 1; } } pub trait QPainterPathStroker_setWidth<RetType> { fn setWidth(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: void QPainterPathStroker::setWidth(qreal width); impl<'a> /*trait*/ QPainterPathStroker_setWidth<()> for (f64) { fn setWidth(self , rsthis: & QPainterPathStroker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStroker8setWidthEd()}; let arg0 = self as c_double; unsafe {C_ZN19QPainterPathStroker8setWidthEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPathStroker::~QPainterPathStroker(); impl /*struct*/ QPainterPathStroker { pub fn free<RetType, T: QPainterPathStroker_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QPainterPathStroker_free<RetType> { fn free(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: void QPainterPathStroker::~QPainterPathStroker(); impl<'a> /*trait*/ QPainterPathStroker_free<()> for () { fn free(self , rsthis: & QPainterPathStroker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStrokerD2Ev()}; unsafe {C_ZN19QPainterPathStrokerD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QPainterPathStroker::setMiterLimit(qreal length); impl /*struct*/ QPainterPathStroker { pub fn setMiterLimit<RetType, T: QPainterPathStroker_setMiterLimit<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMiterLimit(self); // return 1; } } pub trait QPainterPathStroker_setMiterLimit<RetType> { fn setMiterLimit(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: void QPainterPathStroker::setMiterLimit(qreal length); impl<'a> /*trait*/ QPainterPathStroker_setMiterLimit<()> for (f64) { fn setMiterLimit(self , rsthis: & QPainterPathStroker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStroker13setMiterLimitEd()}; let arg0 = self as c_double; unsafe {C_ZN19QPainterPathStroker13setMiterLimitEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPainterPathStroker::QPainterPathStroker(const QPen & pen); impl /*struct*/ QPainterPathStroker { pub fn new<T: QPainterPathStroker_new>(value: T) -> QPainterPathStroker { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QPainterPathStroker_new { fn new(self) -> QPainterPathStroker; } // proto: void QPainterPathStroker::QPainterPathStroker(const QPen & pen); impl<'a> /*trait*/ QPainterPathStroker_new for (&'a QPen) { fn new(self) -> QPainterPathStroker { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStrokerC2ERK4QPen()}; let ctysz: c_int = unsafe{QPainterPathStroker_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN19QPainterPathStrokerC2ERK4QPen(arg0)}; let rsthis = QPainterPathStroker{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QPainterPathStroker::setCurveThreshold(qreal threshold); impl /*struct*/ QPainterPathStroker { pub fn setCurveThreshold<RetType, T: QPainterPathStroker_setCurveThreshold<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCurveThreshold(self); // return 1; } } pub trait QPainterPathStroker_setCurveThreshold<RetType> { fn setCurveThreshold(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: void QPainterPathStroker::setCurveThreshold(qreal threshold); impl<'a> /*trait*/ QPainterPathStroker_setCurveThreshold<()> for (f64) { fn setCurveThreshold(self , rsthis: & QPainterPathStroker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStroker17setCurveThresholdEd()}; let arg0 = self as c_double; unsafe {C_ZN19QPainterPathStroker17setCurveThresholdEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QVector<qreal> QPainterPathStroker::dashPattern(); impl /*struct*/ QPainterPathStroker { pub fn dashPattern<RetType, T: QPainterPathStroker_dashPattern<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dashPattern(self); // return 1; } } pub trait QPainterPathStroker_dashPattern<RetType> { fn dashPattern(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: QVector<qreal> QPainterPathStroker::dashPattern(); impl<'a> /*trait*/ QPainterPathStroker_dashPattern<u64> for () { fn dashPattern(self , rsthis: & QPainterPathStroker) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QPainterPathStroker11dashPatternEv()}; let mut ret = unsafe {C_ZNK19QPainterPathStroker11dashPatternEv(rsthis.qclsinst)}; return ret as u64; // 5 // return 1; } } // proto: qreal QPainterPathStroker::dashOffset(); impl /*struct*/ QPainterPathStroker { pub fn dashOffset<RetType, T: QPainterPathStroker_dashOffset<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dashOffset(self); // return 1; } } pub trait QPainterPathStroker_dashOffset<RetType> { fn dashOffset(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: qreal QPainterPathStroker::dashOffset(); impl<'a> /*trait*/ QPainterPathStroker_dashOffset<f64> for () { fn dashOffset(self , rsthis: & QPainterPathStroker) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QPainterPathStroker10dashOffsetEv()}; let mut ret = unsafe {C_ZNK19QPainterPathStroker10dashOffsetEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: void QPainterPathStroker::QPainterPathStroker(); impl<'a> /*trait*/ QPainterPathStroker_new for () { fn new(self) -> QPainterPathStroker { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStrokerC2Ev()}; let ctysz: c_int = unsafe{QPainterPathStroker_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN19QPainterPathStrokerC2Ev()}; let rsthis = QPainterPathStroker{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QPainterPath QPainterPathStroker::createStroke(const QPainterPath & path); impl /*struct*/ QPainterPathStroker { pub fn createStroke<RetType, T: QPainterPathStroker_createStroke<RetType>>(& self, overload_args: T) -> RetType { return overload_args.createStroke(self); // return 1; } } pub trait QPainterPathStroker_createStroke<RetType> { fn createStroke(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: QPainterPath QPainterPathStroker::createStroke(const QPainterPath & path); impl<'a> /*trait*/ QPainterPathStroker_createStroke<QPainterPath> for (&'a QPainterPath) { fn createStroke(self , rsthis: & QPainterPathStroker) -> QPainterPath { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QPainterPathStroker12createStrokeERK12QPainterPath()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK19QPainterPathStroker12createStrokeERK12QPainterPath(rsthis.qclsinst, arg0)}; let mut ret1 = QPainterPath::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPainterPathStroker::setDashOffset(qreal offset); impl /*struct*/ QPainterPathStroker { pub fn setDashOffset<RetType, T: QPainterPathStroker_setDashOffset<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDashOffset(self); // return 1; } } pub trait QPainterPathStroker_setDashOffset<RetType> { fn setDashOffset(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: void QPainterPathStroker::setDashOffset(qreal offset); impl<'a> /*trait*/ QPainterPathStroker_setDashOffset<()> for (f64) { fn setDashOffset(self , rsthis: & QPainterPathStroker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN19QPainterPathStroker13setDashOffsetEd()}; let arg0 = self as c_double; unsafe {C_ZN19QPainterPathStroker13setDashOffsetEd(rsthis.qclsinst, arg0)}; // return 1; } } // proto: qreal QPainterPathStroker::width(); impl /*struct*/ QPainterPathStroker { pub fn width<RetType, T: QPainterPathStroker_width<RetType>>(& self, overload_args: T) -> RetType { return overload_args.width(self); // return 1; } } pub trait QPainterPathStroker_width<RetType> { fn width(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: qreal QPainterPathStroker::width(); impl<'a> /*trait*/ QPainterPathStroker_width<f64> for () { fn width(self , rsthis: & QPainterPathStroker) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QPainterPathStroker5widthEv()}; let mut ret = unsafe {C_ZNK19QPainterPathStroker5widthEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: qreal QPainterPathStroker::miterLimit(); impl /*struct*/ QPainterPathStroker { pub fn miterLimit<RetType, T: QPainterPathStroker_miterLimit<RetType>>(& self, overload_args: T) -> RetType { return overload_args.miterLimit(self); // return 1; } } pub trait QPainterPathStroker_miterLimit<RetType> { fn miterLimit(self , rsthis: & QPainterPathStroker) -> RetType; } // proto: qreal QPainterPathStroker::miterLimit(); impl<'a> /*trait*/ QPainterPathStroker_miterLimit<f64> for () { fn miterLimit(self , rsthis: & QPainterPathStroker) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK19QPainterPathStroker10miterLimitEv()}; let mut ret = unsafe {C_ZNK19QPainterPathStroker10miterLimitEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // <= body block end
/*! Types implementing the [Mutator] trait. This module provides the following mutators: * mutators for basic types such as * `bool` ([here](crate::mutators::bool::BoolMutator)) * `char` ([here](crate::mutators::char::CharWithinRangeMutator) and [here](crate::mutators::character_classes::CharacterMutator)) * integers ([here](crate::mutators::integer) and [here](crate::mutators::integer_within_range)) * `Vec` ([here](crate::mutators::vector::VecMutator) and [here](crate::mutators::fixed_len_vector::FixedLenVecMutator)) * `Option` ([here](crate::mutators::option::OptionMutator)) * `Result` ([here](crate::mutators::result::ResultMutator)) * `Box` ([here](crate::mutators::boxed)) * tuples of up to 10 elements ([here](crate::mutators::tuples)) * procedural macros to generate mutators for custom types: * [`#[derive(DefaultMutator)]`](fuzzcheck_mutators_derive::DefaultMutator) which works on most structs and enums * [`make_mutator! { .. }`](fuzzcheck_mutators_derive::make_mutator) which works like `#[derive(DefaultMutator)]` but is customisable */ #![cfg_attr( feature = "grammar_mutator", doc = "* grammar-based string and syntax tree mutators ([here](crate::mutators::grammar)) __(supported on crate feature `grammar_mutator` only)__" )] #![cfg_attr( not(feature = "grammar_mutator"), doc = "* ~~grammar-based string and syntax tree mutators~~ (note: you are viewing the documentation of fuzzcheck without the `grammar_mutator` feature. Therefore, grammar-based mutators are not available)" )] /*! - basic blocks to build more complex mutators: * [`AlternationMutator<_, M>`](crate::mutators::alternation::AlternationMutator) to use multiple different mutators acting on the same test case type * [`Either<M1, M2>`](crate::mutators::either::Either) is the regular `Either` type, which also implements `Mutator<T>` if both `M1` and `M2` implement it too * [`RecursiveMutator` and `RecurToMutator`](crate::mutators::recursive) are wrappers allowing mutators to call themselves recursively, which is necessary to mutate recursive types. * [`MapMutator<..>`](crate::mutators::map::MapMutator) wraps a mutator and transforms the generated value using a user-provided function. */ pub const CROSSOVER_RATE: u8 = 10; use std::any::{Any, TypeId}; use std::marker::PhantomData; use std::ops::Range; use ahash::AHashMap; use self::filter::FilterMutator; use self::map::MapMutator; use crate::subvalue_provider::Generation; use crate::{Mutator, SubValueProvider}; pub mod alternation; pub mod arc; pub mod array; pub mod bool; pub mod boxed; pub mod char; pub mod character_classes; pub mod cow; pub mod either; pub mod enums; pub mod filter; pub mod fixed_len_vector; #[cfg(feature = "grammar_mutator")] #[doc(cfg(feature = "grammar_mutator"))] pub mod grammar; pub mod integer; pub mod integer_within_range; pub mod map; pub mod mutations; pub mod never; pub mod option; pub mod range; pub mod rc; pub mod recursive; pub mod result; pub mod string; pub mod tuples; pub mod unique; pub mod unit; pub mod vector; pub mod vose_alias; /// A trait for giving a type a default [Mutator] pub trait DefaultMutator: Clone + 'static { type Mutator: Mutator<Self>; fn default_mutator() -> Self::Mutator; } #[derive(Clone)] pub struct CrossoverStep<T> { steps: AHashMap<usize, (Generation, usize)>, _phantom: PhantomData<T>, } impl<T> Default for CrossoverStep<T> { #[no_coverage] fn default() -> Self { CrossoverStep { steps: <_>::default(), _phantom: <_>::default(), } } } impl<T> CrossoverStep<T> where T: 'static, { #[no_coverage] pub fn get_next_subvalue<'a>( &mut self, subvalue_provider: &'a dyn SubValueProvider, max_cplx: f64, ) -> Option<(&'a T, f64)> { // TODO: mark an entry as exhausted? let id = subvalue_provider.identifier(); let entry = self.steps.entry(id.idx).or_insert((id.generation, 0)); if entry.0 < id.generation { entry.0 = id.generation; entry.1 = 0; } subvalue_provider .get_subvalue(TypeId::of::<T>(), max_cplx, &mut entry.1) .map( #[no_coverage] |(x, cplx)| (x.downcast_ref::<T>().unwrap(), cplx), ) } } #[no_coverage] fn keep_orig_cplx<T>(_x: &T, cplx: f64) -> f64 { cplx } /// A trait for convenience methods automatically implemented for all types that conform to `Mutator<V>` pub trait MutatorExt<T>: Mutator<T> + Sized where T: Clone + 'static, { /// Create a mutator which wraps `self` but only produces values /// for which the given closure returns `true` #[no_coverage] fn filter<F>(self, filter: F) -> FilterMutator<Self, F> where F: Fn(&T) -> bool + 'static, { FilterMutator::new(self, filter) } /// Create a mutator which wraps `self` and transforms the values generated by `self` /// using the `map` closure. The second closure, `parse`, should apply the opposite /// transformation. #[no_coverage] fn map<To, Map, Parse>(self, map: Map, parse: Parse) -> MapMutator<T, To, Self, Parse, Map, fn(&To, f64) -> f64> where To: Clone + 'static, Map: Fn(&T) -> To, Parse: Fn(&To) -> Option<T>, { MapMutator::new(self, parse, map, keep_orig_cplx) } } impl<T, M> MutatorExt<T> for M where M: Mutator<T>, T: Clone + 'static, { } /** A trait for types that are basic wrappers over a mutator, such as `Box<M>`. Such wrapper types automatically implement the [`Mutator`](Mutator) trait. */ pub trait MutatorWrapper { type Wrapped; fn wrapped_mutator(&self) -> &Self::Wrapped; } impl<T: Clone + 'static, W, M> Mutator<T> for M where M: MutatorWrapper<Wrapped = W>, W: Mutator<T>, Self: 'static, { #[doc(hidden)] type Cache = W::Cache; #[doc(hidden)] type MutationStep = W::MutationStep; #[doc(hidden)] type ArbitraryStep = W::ArbitraryStep; #[doc(hidden)] type UnmutateToken = W::UnmutateToken; #[doc(hidden)] #[no_coverage] fn initialize(&self) { self.wrapped_mutator().initialize() } #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { self.wrapped_mutator().default_arbitrary_step() } #[doc(hidden)] #[no_coverage] fn is_valid(&self, value: &T) -> bool { self.wrapped_mutator().is_valid(value) } #[doc(hidden)] #[no_coverage] fn validate_value(&self, value: &T) -> Option<Self::Cache> { self.wrapped_mutator().validate_value(value) } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, value: &T, cache: &Self::Cache) -> Self::MutationStep { self.wrapped_mutator().default_mutation_step(value, cache) } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { self.wrapped_mutator().global_search_space_complexity() } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { self.wrapped_mutator().max_complexity() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { self.wrapped_mutator().min_complexity() } #[doc(hidden)] #[no_coverage] fn complexity(&self, value: &T, cache: &Self::Cache) -> f64 { self.wrapped_mutator().complexity(value, cache) } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(T, f64)> { self.wrapped_mutator().ordered_arbitrary(step, max_cplx) } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, max_cplx: f64) -> (T, f64) { self.wrapped_mutator().random_arbitrary(max_cplx) } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, value: &mut T, cache: &mut Self::Cache, step: &mut Self::MutationStep, subvalue_provider: &dyn crate::SubValueProvider, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { self.wrapped_mutator() .ordered_mutate(value, cache, step, subvalue_provider, max_cplx) } #[doc(hidden)] #[no_coverage] fn random_mutate(&self, value: &mut T, cache: &mut Self::Cache, max_cplx: f64) -> (Self::UnmutateToken, f64) { self.wrapped_mutator().random_mutate(value, cache, max_cplx) } #[doc(hidden)] #[no_coverage] fn unmutate(&self, value: &mut T, cache: &mut Self::Cache, t: Self::UnmutateToken) { self.wrapped_mutator().unmutate(value, cache, t) } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>(&self, value: &'a T, cache: &'a Self::Cache, visit: &mut dyn FnMut(&'a dyn Any, f64)) { self.wrapped_mutator().visit_subvalues(value, cache, visit) } } impl<M> MutatorWrapper for Box<M> { type Wrapped = M; #[no_coverage] fn wrapped_mutator(&self) -> &Self::Wrapped { self.as_ref() } } pub struct Wrapper<T>(pub T); impl<T> MutatorWrapper for Wrapper<T> { type Wrapped = T; #[no_coverage] fn wrapped_mutator(&self) -> &Self::Wrapped { &self.0 } } /// Generate a random f64 within the given range /// The start and end of the range must be finite /// This is a very naive implementation #[no_coverage] #[inline] pub(crate) fn gen_f64(rng: &fastrand::Rng, range: Range<f64>) -> f64 { range.start + rng.f64() * (range.end - range.start) } #[must_use] #[no_coverage] fn size_to_cplxity(size: usize) -> f64 { (usize::BITS - size.leading_zeros()) as f64 } #[cfg(test)] mod test { use crate::mutators::size_to_cplxity; #[allow(clippy::float_cmp)] #[test] #[no_coverage] fn test_size_to_cplxity() { assert_eq!(0.0, size_to_cplxity(0)); assert_eq!(1.0, size_to_cplxity(1)); assert_eq!(2.0, size_to_cplxity(2)); assert_eq!(2.0, size_to_cplxity(3)); assert_eq!(3.0, size_to_cplxity(4)); assert_eq!(3.0, size_to_cplxity(5)); assert_eq!(4.0, size_to_cplxity(8)); assert_eq!(5.0, size_to_cplxity(31)); } } #[doc(hidden)] pub mod testing_utilities { use std::collections::HashSet; use std::fmt::Debug; use std::hash::Hash; use crate::subvalue_provider::EmptySubValueProvider; use crate::Mutator; #[no_coverage] pub fn test_mutator<T, M>( m: M, maximum_complexity_arbitrary: f64, maximum_complexity_mutate: f64, avoid_duplicates: bool, check_consistent_complexities: bool, nbr_arbitraries: usize, nbr_mutations: usize, ) where M: Mutator<T>, T: Clone + Debug + PartialEq + Eq + Hash + 'static, M::Cache: Clone, { m.initialize(); let mut arbitrary_step = m.default_arbitrary_step(); let mut arbitraries = HashSet::new(); for _i in 0..nbr_arbitraries { if let Some((x, cplx)) = m.ordered_arbitrary(&mut arbitrary_step, maximum_complexity_arbitrary) { // assert!( // cplx <= maximum_complexity_arbitrary, // "{} {}", // cplx, // maximum_complexity_arbitrary // ); if avoid_duplicates { let is_new = arbitraries.insert(x.clone()); assert!(is_new); } let cache = m.validate_value(&x).unwrap(); let mut mutation_step = m.default_mutation_step(&x, &cache); let other_cplx = m.complexity(&x, &cache); if check_consistent_complexities { assert!((cplx - other_cplx).abs() < 0.01, "{:.3} != {:.3}", cplx, other_cplx); } let mut mutated = HashSet::new(); if avoid_duplicates { mutated.insert(x.clone()); } let mut x_mut = x.clone(); let mut cache_mut = cache.clone(); for _j in 0..nbr_mutations { if let Some((token, cplx)) = m.ordered_mutate( &mut x_mut, &mut cache_mut, &mut mutation_step, &EmptySubValueProvider, maximum_complexity_mutate, ) { // assert!( // cplx <= maximum_complexity_mutate, // "{} {}", // cplx, // maximum_complexity_mutate // ); if avoid_duplicates { let is_new = mutated.insert(x_mut.clone()); assert!(is_new); } let validated = m.validate_value(&x_mut).unwrap(); let other_cplx = m.complexity(&x_mut, &validated); if check_consistent_complexities { assert!( (cplx - other_cplx).abs() < 0.01, "{:.3} != {:.3} for {:?} mutated from {:?}", cplx, other_cplx, x_mut, x ); } m.unmutate(&mut x_mut, &mut cache_mut, token); assert_eq!(x, x_mut); // assert_eq!(cache, cache_mut); } else { // println!("Stopped mutating at {}", j); break; } } } else { // println!("Stopped arbitraries at {}", i); break; } } // for _i in 0..nbr_arbitraries { // let (x, cplx) = m.random_arbitrary(maximum_complexity_arbitrary); // let cache = m.validate_value(&x).unwrap(); // // let mutation_step = m.default_mutation_step(&x, &cache); // let other_cplx = m.complexity(&x, &cache); // assert!((cplx - other_cplx).abs() < 0.01, "{:.3} != {:.3}", cplx, other_cplx); // let mut x_mut = x.clone(); // let mut cache_mut = cache.clone(); // for _j in 0..nbr_mutations { // let (token, cplx) = m.random_mutate(&mut x_mut, &mut cache_mut, maximum_complexity_mutate); // let validated = m.validate_value(&x_mut).unwrap(); // let other_cplx = m.complexity(&x_mut, &validated); // if check_consistent_complexities { // assert!((cplx - other_cplx).abs() < 0.01, "{:.3} != {:.3}", cplx, other_cplx); // } // m.unmutate(&mut x_mut, &mut cache_mut, token); // assert_eq!(x, x_mut); // // assert_eq!(cache, cache_mut); // } // } } // #[no_coverage] // pub fn bench_mutator<T, M>( // m: M, // maximum_complexity_arbitrary: f64, // maximum_complexity_mutate: f64, // nbr_arbitraries: usize, // nbr_mutations: usize, // ) where // M: Mutator<T>, // T: Clone + Debug + PartialEq + Eq + Hash + 'static, // M::Cache: Clone, // { // let mut arbitrary_step = m.default_arbitrary_step(); // for _i in 0..nbr_arbitraries { // if let Some((mut x, cplx)) = m.ordered_arbitrary(&mut arbitrary_step, maximum_complexity_arbitrary) { // let mut cache = m.validate_value(&x).unwrap(); // let mut mutation_step = m.default_mutation_step(&x, &cache); // let other_cplx = m.complexity(&x, &cache); // for _j in 0..nbr_mutations { // if let Some((token, _cplx)) = // m.ordered_mutate(&mut x, &mut cache, &mut mutation_step, maximum_complexity_mutate) // { // m.unmutate(&mut x, &mut cache, token); // } else { // break; // } // } // } else { // break; // } // } // for _i in 0..nbr_arbitraries { // let (mut x, cplx) = m.random_arbitrary(maximum_complexity_arbitrary); // let mut cache = m.validate_value(&x).unwrap(); // let other_cplx = m.complexity(&x, &cache); // for _j in 0..nbr_mutations { // let (token, _cplx) = m.random_mutate(&mut x, &mut cache, maximum_complexity_mutate); // m.unmutate(&mut x, &mut cache, token); // } // } // } }
pub struct Solution; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Tree, pub right: Tree, } use std::cell::RefCell; use std::rc::Rc; type Tree = Option<Rc<RefCell<TreeNode>>>; fn tree(left: Tree, val: i32, right: Tree) -> Tree { Some(Rc::new(RefCell::new(TreeNode { val, left, right }))) } impl Solution { pub fn generate_trees(n: i32) -> Vec<Tree> { if n == 0 { return Vec::new(); } use std::collections::HashMap; let nums = (1..=n).collect::<Vec<i32>>(); let n = nums.len(); let mut map = HashMap::new(); for i in 0..=n { map.insert((i, i), vec![None]); } for w in 1..=n { for i in 0..=n - w { let mut res = Vec::new(); for j in i..i + w { for left in &map[&(i, j)] { for right in &map[&(j + 1, i + w)] { res.push(tree(left.clone(), nums[j], right.clone())); } } } map.insert((i, i + w), res); } } map.remove(&(0, n)).unwrap() } } #[test] fn test0095() { assert_eq!(Solution::generate_trees(0), vec![]); assert_eq!( Solution::generate_trees(3), vec![ tree(None, 1, tree(None, 2, tree(None, 3, None))), tree(None, 1, tree(tree(None, 2, None), 3, None)), tree(tree(None, 1, None), 2, tree(None, 3, None)), tree(tree(None, 1, tree(None, 2, None)), 3, None), tree(tree(tree(None, 1, None), 2, None), 3, None), ] ); }
#[doc = "Reader of register DATA"] pub type R = crate::R<u32, super::DATA>; #[doc = "Writer for register DATA"] pub type W = crate::W<u32, super::DATA>; #[doc = "Register DATA `reset()`'s with value 0"] impl crate::ResetValue for super::DATA { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RTD`"] pub type RTD_R = crate::R<u32, u32>; #[doc = "Write proxy for field `RTD`"] pub struct RTD_W<'a> { w: &'a mut W, } impl<'a> RTD_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 & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - Hibernation Module NV Data"] #[inline(always)] pub fn rtd(&self) -> RTD_R { RTD_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Hibernation Module NV Data"] #[inline(always)] pub fn rtd(&mut self) -> RTD_W { RTD_W { w: self } } }
use sourcerenderer_core::graphics::AccelerationStructure; pub struct WebGLAccelerationStructureStub {} impl AccelerationStructure for WebGLAccelerationStructureStub {}
use std::env; use actix_web::{get, post, error, web, HttpServer, App, HttpResponse}; use mongodb::{Client, Collection, error::Result as MongoResult}; use serde::{Deserialize, Serialize}; use bson::{Bson, oid::ObjectId}; #[derive(Clone)] struct Store { client: Client, db_name: String, col_name: String, } impl Store { fn collection(&self) -> Collection { self.client.database(&self.db_name) .collection(&self.col_name) } } #[derive(Debug)] struct AppError(Box<dyn std::error::Error>); impl std::fmt::Display for AppError { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { std::fmt::Display::fmt(&self.0, f) } } impl<E> From<E> for AppError where E: std::error::Error + 'static { fn from(err: E) -> Self { Self(Box::new(err)) } } impl error::ResponseError for AppError {} #[derive(Debug, Clone, Deserialize, Serialize)] struct CreateItem { name: String, value: i32, } type AppResult = Result<HttpResponse, AppError>; #[post("/items")] async fn create_item(db: web::Data<Store>, params: web::Json<CreateItem>) -> AppResult { let doc = bson::to_bson(&params.0)?; if let Bson::Document(d) = doc { let col = db.collection(); let res = col.insert_one(d, None)?; let id: ObjectId = bson::from_bson(res.inserted_id)?; Ok(HttpResponse::Created().json(id.to_hex())) } else { Err(error::ErrorInternalServerError("").into()) } } #[get("/items")] async fn all_items(db: web::Data<Store>) -> AppResult { let col = db.collection(); let rs = col.find(None, None) .and_then(|c| c.collect::<MongoResult<Vec<_>>>() )?; Ok(HttpResponse::Ok().json(rs)) } #[actix_rt::main] async fn main() -> std::io::Result<()> { let addr = "127.0.0.1:8080"; let mongo_uri = env::var("MONGO_URI").unwrap_or("mongodb://localhost".to_string()); let db = env::var("MONGO_DB").unwrap_or("items".to_string()); let col = env::var("MONGO_COLLECTION").unwrap_or("data".to_string()); let store = Store { client: Client::with_uri_str(&mongo_uri).unwrap(), db_name: db, col_name: col }; HttpServer::new( move || App::new() .data(store.clone()) .service(create_item) .service(all_items) ).bind(addr)?.run().await }
// Copyright 2015 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. // ignore-cloudabi no environment variables present // ignore-emscripten env vars don't work? use std::env::*; use std::path::PathBuf; #[cfg(unix)] fn main() { let oldhome = var("HOME"); set_var("HOME", "/home/MountainView"); assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); remove_var("HOME"); if cfg!(target_os = "android") { assert!(home_dir().is_none()); } else { // When HOME is not set, some platforms return `None`, // but others return `Some` with a default. // Just check that it is not "/home/MountainView". assert_ne!(home_dir(), Some(PathBuf::from("/home/MountainView"))); } } #[cfg(windows)] fn main() { let oldhome = var("HOME"); let olduserprofile = var("USERPROFILE"); remove_var("HOME"); remove_var("USERPROFILE"); assert!(home_dir().is_some()); set_var("HOME", "/home/MountainView"); assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); remove_var("HOME"); set_var("USERPROFILE", "/home/MountainView"); assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); set_var("HOME", "/home/MountainView"); set_var("USERPROFILE", "/home/PaloAlto"); assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); }
use crate::intcode::IntCodeEmulator; const INPUT: &str = include_str!("../input/2019/day5.txt"); pub fn part1() -> i64 { let mut vm = IntCodeEmulator::from_input(INPUT); vm.stdin().push_back(1); vm.execute(); let result = vm .stdout() .iter() .last() .expect("Expected output but received none"); *result } pub fn part2() -> i64 { let mut vm = IntCodeEmulator::from_input(INPUT); vm.stdin().push_back(5); vm.execute(); let result = vm .stdout() .iter() .last() .expect("Expected output but received none"); *result } #[cfg(test)] mod tests { use super::*; #[test] fn day05_part1() { assert_eq!(part1(), 7_988_899); } #[test] fn day05_part2() { assert_eq!(part2(), 13_758_663); } }
use pnet_datalink::interfaces; use std::time::Duration; use tokio::time::sleep; use wifi_rs::{ prelude::{Config, Connectivity}, WiFi, }; use wifiscanner; pub struct Network(); impl Network { pub async fn connect(ssid: String) -> Result<(), anyhow::Error> { let adapters = Network::list_adapters(); println!("available adapters {:?}", adapters); let adapter = Network::filter_wifi_adapter(adapters); println!("Wifi adapter {:?}", adapter); if let Some(adapter) = adapter { Network::wait_for_ssid(ssid.clone()).await?; Network::connect_wifi(adapter, ssid)?; Ok(()) } else { Err(anyhow::Error::msg("no wifi adapter found")) } } #[allow(dead_code)] pub fn list_adapters() -> Vec<String> { // Get a vector with all network interfaces found let all_interfaces = interfaces(); // Search for the default interface - the one that is // up, not loopback and has an IP. all_interfaces .iter() .filter(|e| e.is_up() && !e.is_loopback()) .map(|interface| interface.name.to_owned()) .collect() } #[allow(dead_code)] pub fn filter_wifi_adapter(all_interfaces: Vec<String>) -> Option<String> { all_interfaces .iter() .find(|adapter| adapter.to_uppercase().starts_with("WL")) .map(|a| a.to_owned()) } #[allow(dead_code)] pub async fn wait_for_ssid(ssid: String) -> Result<(), anyhow::Error> { let mut retries = 0; 'scanLoop: loop { if let Ok(scan) = wifiscanner::scan() { let ssids: Vec<String> = scan.iter().map(|wi| wi.ssid.to_owned()).collect(); println!("found SSIDs {:?} , scann for '{}'", ssids, ssid); if ssids .iter() .any(|w| w.to_uppercase() == ssid.to_uppercase()) { break 'scanLoop Ok(()); } else { if retries == 30 { break 'scanLoop Err(anyhow::Error::msg("timed out")); } else { sleep(Duration::from_millis(1000)).await; retries += 1; } } } else { break 'scanLoop Err(anyhow::Error::msg("failed to scan for networks")); } } } #[allow(dead_code)] pub fn connect_wifi(adapter: String, ssid: String) -> Result<(), anyhow::Error> { let config = Some(Config { interface: Some(&adapter), }); let mut wifi = WiFi::new(config); match wifi.connect(&ssid, "") { Ok(_) => { println!("connect to drones WIFI {}", ssid); Ok(()) } Err(e) => Err(anyhow::Error::msg(format!("wifi error {:?}", e))), } } } #[test] fn list_adapters() { let adapters = Network::list_adapters(); println!("adapters {:?}", adapters); assert!( adapters.len() > 0, "expect a network card on any computer who compiles rust" ); } #[test] fn filter_adapters() { let adapters = Network::filter_wifi_adapter(vec!["enp0s31f6".to_string(), "wlp0s20f3".to_string()]); assert_eq!(adapters, Some("sudoi".to_string())); let adapters = Network::filter_wifi_adapter(vec!["enp0s31f6".to_string()]); assert_eq!(adapters, None); let adapters = Network::filter_wifi_adapter(vec![]); assert_eq!(adapters, None); } #[tokio::test] async fn wait_for_ssid() { let adapters = Network::wait_for_ssid("TELLO-59FF95".to_string()).await; println!("res {:?}", adapters); }
test_stdout!(without_atom_errors_badarg, "{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n"); test_stdout!(with_atom_without_atom_encoding_errors_badarg, "{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n"); test_stdout!( with_atom_with_atom_without_name_encoding_errors_badarg, "{caught, error, badarg}\n" ); test_stdout!( with_atom_with_encoding_atom_returns_name_in_binary, "<<\"one\">>\n<<\"two\">>\n<<\"three\">>\n" );
#![deny(warnings)] #![feature(generic_associated_types)] #![feature(iterator_try_collect)] #![feature(map_first_last)] #![feature(map_try_insert)] #![feature(let_else)] #![feature(box_patterns)] #![feature(assert_matches)] mod bimap; mod ir; pub mod macros; pub mod passes; mod printer; pub use self::bimap::{BiMap, Name}; pub use self::ir::*;
// build.rs fn main() { cc::Build::new() .file("src/udpx/recvmsg.c") .compile("recvmsg"); }
// This sub-crate exists to make sure that everything works well with the `impl-style` flag enabled use humansize::{FormatSize, FormatSizeI, DECIMAL}; #[test] fn test_impl_style() { assert_eq!(1000u64.format_size(DECIMAL), "1 kB"); assert_eq!((-1000).format_size_i(DECIMAL), "-1 kB"); }
use super::system_prelude::*; #[derive(Default)] pub struct HandleSolidCollisionsSystem; impl<'a> System<'a> for HandleSolidCollisionsSystem { type SystemData = ( Entities<'a>, ReadStorage<'a, Collision>, ReadStorage<'a, Solid<SolidTag>>, ReadStorage<'a, Loadable>, ReadStorage<'a, Loaded>, WriteStorage<'a, Velocity>, ); fn run( &mut self, ( entities, collisions, solids, loadables, loadeds, mut velocities ): Self::SystemData, ) { for (collision, solid, mut velocity, loadable_opt, loaded_opt) in ( &collisions, &solids, &mut velocities, loadables.maybe(), loadeds.maybe(), ) .join() { if let (None, None) | (Some(_), Some(_)) = (loadable_opt, loaded_opt) { let sides_touching = SidesTouching::new( &entities, collision, solid, &collisions, &solids, ); if (sides_touching.is_touching_top && velocity.y > 0.0) || (sides_touching.is_touching_bottom && velocity.y < 0.0) { velocity.y = 0.0; } if (sides_touching.is_touching_right && velocity.x > 0.0) || (sides_touching.is_touching_left && velocity.x < 0.0) { velocity.x = 0.0; } } } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::string::String; use alloc::collections::btree_map::BTreeMap; use core::cmp::Ordering; use alloc::sync::Arc; use spin::Mutex; use lazy_static::lazy_static; lazy_static! { pub static ref SIMPLE_DEVICES: Mutex<Registry> = Mutex::new(Registry::New()); pub static ref HOSTFILE_DEVICE: Mutex<MultiDevice> = Mutex::new(NewAnonMultiDevice()); pub static ref PSEUDO_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); pub static ref DEV_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); pub static ref PTS_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); pub static ref PROC_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); pub static ref SHM_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); pub static ref SYS_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); pub static ref TMPFS_DEVICE: Arc<Mutex<Device>> = NewAnonDevice(); } // TTYAUX_MAJOR is the major device number for alternate TTY devices. pub const TTYAUX_MAJOR: u16 = 5; // UNIX98_PTY_MASTER_MAJOR is the initial major device number for // Unix98 PTY masters. pub const UNIX98_PTY_MASTER_MAJOR: u16 = 128; // UNIX98_PTY_SLAVE_MAJOR is the initial major device number for // Unix98 PTY slaves. pub const UNIX98_PTY_SLAVE_MAJOR: u16 = 136; // PTMX_MINOR is the minor device number for /dev/ptmx. pub const PTMX_MINOR: u32 = 2; pub struct Device { pub id: ID, pub last: u64, } impl Device { pub fn NextIno(&mut self) -> u64 { self.last += 1; return self.last; } pub fn DeviceID(&self) -> u64 { return self.id.DeviceID() } } pub struct Registry { pub last: u32, pub devices: BTreeMap<ID, Arc<Mutex<Device>>> } impl Registry { pub fn New() -> Self { return Self { last: 0, devices: BTreeMap::new(), } } fn newAnonID(&mut self) -> ID { self.last += 1; return ID { Major: 0, Minor: self.last, } } pub fn NewAnonDevice(&mut self) -> Arc<Mutex<Device>> { let d = Arc::new(Mutex::new(Device { id: self.newAnonID(), last: 0, })); self.devices.insert(d.lock().id, d.clone()); return d; } } #[derive(Debug, Copy, Clone, Eq)] pub struct ID { pub Major: u16, pub Minor: u32, } impl ID { pub fn New(rdev: u32) -> Self { return ID { Major: ((rdev >> 8) & 0xfff) as u16, Minor: (rdev & 0xff) | ((rdev >> 20) << 8), } } // Bits 7:0 - minor bits 7:0 // Bits 19:8 - major bits 11:0 // Bits 31:20 - minor bits 19:8 pub fn MakeDeviceID(&self) -> u32 { return (self.Minor & 0xff) | ((self.Major as u32 & 0xfff) << 8) | ((self.Minor >> 8) << 20); } pub fn DeviceID(&self) -> u64 { return self.MakeDeviceID() as u64 } } impl Ord for ID { fn cmp(&self, other: &Self) -> Ordering { let MajorCmp = self.Major.cmp(&other.Major); if MajorCmp != Ordering::Equal { return MajorCmp; } let MinorCmp = self.Minor.cmp(&other.Minor); if MinorCmp != Ordering::Equal { return MinorCmp; } return Ordering::Equal } } impl PartialOrd for ID { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for ID { fn eq(&self, other: &Self) -> bool { self.Major == other.Major && self.Minor == other.Minor } } #[derive(Debug, Clone, Eq)] pub struct MultiDeviceKey { pub Device: u64, pub SecondaryDevice: String, pub Inode: u64, } impl Ord for MultiDeviceKey { fn cmp(&self, other: &Self) -> Ordering { let DeviceCmp = self.Device.cmp(&other.Device); if DeviceCmp != Ordering::Equal { return DeviceCmp; } let SecondaryDevicCmp = self.SecondaryDevice.cmp(&other.SecondaryDevice); if SecondaryDevicCmp != Ordering::Equal { return SecondaryDevicCmp; } let InodeCmp = self.Inode.cmp(&other.Inode); if InodeCmp != Ordering::Equal { return InodeCmp; } return Ordering::Equal } } impl PartialOrd for MultiDeviceKey { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for MultiDeviceKey { fn eq(&self, other: &Self) -> bool { self.Device == other.Device && self.SecondaryDevice == other.SecondaryDevice && self.Inode == other.Inode } } pub struct MultiDevice { pub id: ID, pub last: u64, pub cache: BTreeMap<MultiDeviceKey, u64>, pub rcache: BTreeMap<u64, MultiDeviceKey>, } impl MultiDevice { pub fn New(id: ID) -> Self { return Self { id: id, last: 0, cache: BTreeMap::new(), rcache: BTreeMap::new(), } } pub fn Map(&mut self, key: MultiDeviceKey) -> u64 { match self.cache.get(&key) { Some(id) => return *id, None => () } let mut idx = self.last + 1; loop { match self.rcache.get(&idx) { Some(_) => idx += 1, None => break, } } self.last = idx; self.cache.insert(key.clone(), idx); self.rcache.insert(idx, key); return idx; } pub fn DeviceID(&self) -> u64 { return self.id.DeviceID() } } pub fn NewAnonDevice() -> Arc<Mutex<Device>> { return SIMPLE_DEVICES.lock().NewAnonDevice() } pub fn NewAnonMultiDevice() -> MultiDevice { return MultiDevice::New(SIMPLE_DEVICES.lock().newAnonID()) } pub fn MakeDeviceID(major: u16, minor: u32) -> u32 { return (minor & 0xff) | (((major as u32 & 0xfff) << 8) | ((minor >> 8) << 20)) } pub fn DecodeDeviceId(rdev: u32) -> (u16, u32) { let major = ((rdev >> 8) & 0xfff) as u16; let minor = (rdev & 0xff) | ((rdev >> 20) << 8); return (major, minor) }
#[doc = "Reader of register MPCBB1_VCTR35"] pub type R = crate::R<u32, super::MPCBB1_VCTR35>; #[doc = "Writer for register MPCBB1_VCTR35"] pub type W = crate::W<u32, super::MPCBB1_VCTR35>; #[doc = "Register MPCBB1_VCTR35 `reset()`'s with value 0xffff_ffff"] impl crate::ResetValue for super::MPCBB1_VCTR35 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xffff_ffff } } #[doc = "Reader of field `B1120`"] pub type B1120_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1120`"] pub struct B1120_W<'a> { w: &'a mut W, } impl<'a> B1120_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 `B1121`"] pub type B1121_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1121`"] pub struct B1121_W<'a> { w: &'a mut W, } impl<'a> B1121_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `B1122`"] pub type B1122_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1122`"] pub struct B1122_W<'a> { w: &'a mut W, } impl<'a> B1122_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `B1123`"] pub type B1123_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1123`"] pub struct B1123_W<'a> { w: &'a mut W, } impl<'a> B1123_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `B1124`"] pub type B1124_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1124`"] pub struct B1124_W<'a> { w: &'a mut W, } impl<'a> B1124_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `B1125`"] pub type B1125_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1125`"] pub struct B1125_W<'a> { w: &'a mut W, } impl<'a> B1125_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `B1126`"] pub type B1126_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1126`"] pub struct B1126_W<'a> { w: &'a mut W, } impl<'a> B1126_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `B1127`"] pub type B1127_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1127`"] pub struct B1127_W<'a> { w: &'a mut W, } impl<'a> B1127_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `B1128`"] pub type B1128_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1128`"] pub struct B1128_W<'a> { w: &'a mut W, } impl<'a> B1128_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `B1129`"] pub type B1129_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1129`"] pub struct B1129_W<'a> { w: &'a mut W, } impl<'a> B1129_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `B1130`"] pub type B1130_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1130`"] pub struct B1130_W<'a> { w: &'a mut W, } impl<'a> B1130_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `B1131`"] pub type B1131_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1131`"] pub struct B1131_W<'a> { w: &'a mut W, } impl<'a> B1131_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `B1132`"] pub type B1132_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1132`"] pub struct B1132_W<'a> { w: &'a mut W, } impl<'a> B1132_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `B1133`"] pub type B1133_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1133`"] pub struct B1133_W<'a> { w: &'a mut W, } impl<'a> B1133_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `B1134`"] pub type B1134_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1134`"] pub struct B1134_W<'a> { w: &'a mut W, } impl<'a> B1134_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `B1135`"] pub type B1135_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1135`"] pub struct B1135_W<'a> { w: &'a mut W, } impl<'a> B1135_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `B1136`"] pub type B1136_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1136`"] pub struct B1136_W<'a> { w: &'a mut W, } impl<'a> B1136_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `B1137`"] pub type B1137_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1137`"] pub struct B1137_W<'a> { w: &'a mut W, } impl<'a> B1137_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `B1138`"] pub type B1138_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1138`"] pub struct B1138_W<'a> { w: &'a mut W, } impl<'a> B1138_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `B1139`"] pub type B1139_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1139`"] pub struct B1139_W<'a> { w: &'a mut W, } impl<'a> B1139_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `B1140`"] pub type B1140_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1140`"] pub struct B1140_W<'a> { w: &'a mut W, } impl<'a> B1140_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `B1141`"] pub type B1141_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1141`"] pub struct B1141_W<'a> { w: &'a mut W, } impl<'a> B1141_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `B1142`"] pub type B1142_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1142`"] pub struct B1142_W<'a> { w: &'a mut W, } impl<'a> B1142_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `B1143`"] pub type B1143_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1143`"] pub struct B1143_W<'a> { w: &'a mut W, } impl<'a> B1143_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `B1144`"] pub type B1144_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1144`"] pub struct B1144_W<'a> { w: &'a mut W, } impl<'a> B1144_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `B1145`"] pub type B1145_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1145`"] pub struct B1145_W<'a> { w: &'a mut W, } impl<'a> B1145_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `B1146`"] pub type B1146_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1146`"] pub struct B1146_W<'a> { w: &'a mut W, } impl<'a> B1146_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `B1147`"] pub type B1147_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1147`"] pub struct B1147_W<'a> { w: &'a mut W, } impl<'a> B1147_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `B1148`"] pub type B1148_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1148`"] pub struct B1148_W<'a> { w: &'a mut W, } impl<'a> B1148_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `B1149`"] pub type B1149_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1149`"] pub struct B1149_W<'a> { w: &'a mut W, } impl<'a> B1149_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `B1150`"] pub type B1150_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1150`"] pub struct B1150_W<'a> { w: &'a mut W, } impl<'a> B1150_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `B1151`"] pub type B1151_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1151`"] pub struct B1151_W<'a> { w: &'a mut W, } impl<'a> B1151_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - B1120"] #[inline(always)] pub fn b1120(&self) -> B1120_R { B1120_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - B1121"] #[inline(always)] pub fn b1121(&self) -> B1121_R { B1121_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - B1122"] #[inline(always)] pub fn b1122(&self) -> B1122_R { B1122_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - B1123"] #[inline(always)] pub fn b1123(&self) -> B1123_R { B1123_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - B1124"] #[inline(always)] pub fn b1124(&self) -> B1124_R { B1124_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - B1125"] #[inline(always)] pub fn b1125(&self) -> B1125_R { B1125_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - B1126"] #[inline(always)] pub fn b1126(&self) -> B1126_R { B1126_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - B1127"] #[inline(always)] pub fn b1127(&self) -> B1127_R { B1127_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - B1128"] #[inline(always)] pub fn b1128(&self) -> B1128_R { B1128_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - B1129"] #[inline(always)] pub fn b1129(&self) -> B1129_R { B1129_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - B1130"] #[inline(always)] pub fn b1130(&self) -> B1130_R { B1130_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - B1131"] #[inline(always)] pub fn b1131(&self) -> B1131_R { B1131_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - B1132"] #[inline(always)] pub fn b1132(&self) -> B1132_R { B1132_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - B1133"] #[inline(always)] pub fn b1133(&self) -> B1133_R { B1133_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - B1134"] #[inline(always)] pub fn b1134(&self) -> B1134_R { B1134_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - B1135"] #[inline(always)] pub fn b1135(&self) -> B1135_R { B1135_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - B1136"] #[inline(always)] pub fn b1136(&self) -> B1136_R { B1136_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - B1137"] #[inline(always)] pub fn b1137(&self) -> B1137_R { B1137_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - B1138"] #[inline(always)] pub fn b1138(&self) -> B1138_R { B1138_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - B1139"] #[inline(always)] pub fn b1139(&self) -> B1139_R { B1139_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - B1140"] #[inline(always)] pub fn b1140(&self) -> B1140_R { B1140_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - B1141"] #[inline(always)] pub fn b1141(&self) -> B1141_R { B1141_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - B1142"] #[inline(always)] pub fn b1142(&self) -> B1142_R { B1142_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - B1143"] #[inline(always)] pub fn b1143(&self) -> B1143_R { B1143_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - B1144"] #[inline(always)] pub fn b1144(&self) -> B1144_R { B1144_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - B1145"] #[inline(always)] pub fn b1145(&self) -> B1145_R { B1145_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - B1146"] #[inline(always)] pub fn b1146(&self) -> B1146_R { B1146_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - B1147"] #[inline(always)] pub fn b1147(&self) -> B1147_R { B1147_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - B1148"] #[inline(always)] pub fn b1148(&self) -> B1148_R { B1148_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - B1149"] #[inline(always)] pub fn b1149(&self) -> B1149_R { B1149_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - B1150"] #[inline(always)] pub fn b1150(&self) -> B1150_R { B1150_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - B1151"] #[inline(always)] pub fn b1151(&self) -> B1151_R { B1151_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - B1120"] #[inline(always)] pub fn b1120(&mut self) -> B1120_W { B1120_W { w: self } } #[doc = "Bit 1 - B1121"] #[inline(always)] pub fn b1121(&mut self) -> B1121_W { B1121_W { w: self } } #[doc = "Bit 2 - B1122"] #[inline(always)] pub fn b1122(&mut self) -> B1122_W { B1122_W { w: self } } #[doc = "Bit 3 - B1123"] #[inline(always)] pub fn b1123(&mut self) -> B1123_W { B1123_W { w: self } } #[doc = "Bit 4 - B1124"] #[inline(always)] pub fn b1124(&mut self) -> B1124_W { B1124_W { w: self } } #[doc = "Bit 5 - B1125"] #[inline(always)] pub fn b1125(&mut self) -> B1125_W { B1125_W { w: self } } #[doc = "Bit 6 - B1126"] #[inline(always)] pub fn b1126(&mut self) -> B1126_W { B1126_W { w: self } } #[doc = "Bit 7 - B1127"] #[inline(always)] pub fn b1127(&mut self) -> B1127_W { B1127_W { w: self } } #[doc = "Bit 8 - B1128"] #[inline(always)] pub fn b1128(&mut self) -> B1128_W { B1128_W { w: self } } #[doc = "Bit 9 - B1129"] #[inline(always)] pub fn b1129(&mut self) -> B1129_W { B1129_W { w: self } } #[doc = "Bit 10 - B1130"] #[inline(always)] pub fn b1130(&mut self) -> B1130_W { B1130_W { w: self } } #[doc = "Bit 11 - B1131"] #[inline(always)] pub fn b1131(&mut self) -> B1131_W { B1131_W { w: self } } #[doc = "Bit 12 - B1132"] #[inline(always)] pub fn b1132(&mut self) -> B1132_W { B1132_W { w: self } } #[doc = "Bit 13 - B1133"] #[inline(always)] pub fn b1133(&mut self) -> B1133_W { B1133_W { w: self } } #[doc = "Bit 14 - B1134"] #[inline(always)] pub fn b1134(&mut self) -> B1134_W { B1134_W { w: self } } #[doc = "Bit 15 - B1135"] #[inline(always)] pub fn b1135(&mut self) -> B1135_W { B1135_W { w: self } } #[doc = "Bit 16 - B1136"] #[inline(always)] pub fn b1136(&mut self) -> B1136_W { B1136_W { w: self } } #[doc = "Bit 17 - B1137"] #[inline(always)] pub fn b1137(&mut self) -> B1137_W { B1137_W { w: self } } #[doc = "Bit 18 - B1138"] #[inline(always)] pub fn b1138(&mut self) -> B1138_W { B1138_W { w: self } } #[doc = "Bit 19 - B1139"] #[inline(always)] pub fn b1139(&mut self) -> B1139_W { B1139_W { w: self } } #[doc = "Bit 20 - B1140"] #[inline(always)] pub fn b1140(&mut self) -> B1140_W { B1140_W { w: self } } #[doc = "Bit 21 - B1141"] #[inline(always)] pub fn b1141(&mut self) -> B1141_W { B1141_W { w: self } } #[doc = "Bit 22 - B1142"] #[inline(always)] pub fn b1142(&mut self) -> B1142_W { B1142_W { w: self } } #[doc = "Bit 23 - B1143"] #[inline(always)] pub fn b1143(&mut self) -> B1143_W { B1143_W { w: self } } #[doc = "Bit 24 - B1144"] #[inline(always)] pub fn b1144(&mut self) -> B1144_W { B1144_W { w: self } } #[doc = "Bit 25 - B1145"] #[inline(always)] pub fn b1145(&mut self) -> B1145_W { B1145_W { w: self } } #[doc = "Bit 26 - B1146"] #[inline(always)] pub fn b1146(&mut self) -> B1146_W { B1146_W { w: self } } #[doc = "Bit 27 - B1147"] #[inline(always)] pub fn b1147(&mut self) -> B1147_W { B1147_W { w: self } } #[doc = "Bit 28 - B1148"] #[inline(always)] pub fn b1148(&mut self) -> B1148_W { B1148_W { w: self } } #[doc = "Bit 29 - B1149"] #[inline(always)] pub fn b1149(&mut self) -> B1149_W { B1149_W { w: self } } #[doc = "Bit 30 - B1150"] #[inline(always)] pub fn b1150(&mut self) -> B1150_W { B1150_W { w: self } } #[doc = "Bit 31 - B1151"] #[inline(always)] pub fn b1151(&mut self) -> B1151_W { B1151_W { w: self } } }
use diesel; use diesel::delete; use diesel::prelude::*; use db::models::*; use rand::{thread_rng, Rng}; use db::schema::*; use diesel::result::Error as DieselError; /// Creates a new quote and saves it into the database. pub fn create_quote(conn: &PgConnection, quote: &NewQuote) -> Result<Quote, diesel::result::Error> { find_author(conn, quote.quoted_by_id)?; find_author(conn, quote.created_by_id)?; diesel::insert(quote).into(quotes::table).get_result(conn) } /// Find a quote, return Some(Quote) if found or None, else an error. pub fn find_quote(conn: &PgConnection, id_target: i32) -> Result<Option<Quote>, DieselError> { use db::schema::quotes::dsl::*; let quote_res = quotes.find(id_target).first(conn); match quote_res { Ok(v) => Ok(Some(v)), Err(ref e) if *e == DieselError::NotFound => Ok(None), Err(e) => Err(e), } } pub fn delete_quote(conn: &PgConnection, quote_target: &Quote) -> Result<bool, DieselError> { delete(quote_target).execute(conn).map(|n| n > 0) } /// Finds an author in the database, if they do not exist, create a new one. pub fn find_author(conn: &PgConnection, author_id: &str) -> Result<Author, diesel::result::Error> { use db::schema::authors; use db::schema::authors::dsl::*; let author = authors.find(author_id.to_string()).first::<Author>(conn); match author { Ok(u) => Ok(u), Err(ref e) if *e == DieselError::NotFound => diesel::insert(&NewAuthor { id: author_id }) .into(authors::table) .get_result(conn), Err(e) => return Err(e), } } /// Finds a random quote from the user. pub fn find_rand_quote( conn: &PgConnection, author_id: &str, guild_id: &str, ) -> Result<Option<Quote>, DieselError> { let mut rng = thread_rng(); let author = find_author(conn, author_id)?; let mut quotes = Quote::belonging_to(&author) .filter(quotes::guild_id.eq(guild_id)) .load::<Quote>(conn)?; let mut quotes = quotes.as_mut_slice(); rng.shuffle(&mut quotes); let first = quotes.first(); match first { Some(q) => Ok(Some(q.clone())), None => Ok(None), } } /// Searches for a max of 5 quotes that contain the given string query. pub fn find_contains_quotes( conn: &PgConnection, author_id: &str, guild_id: &str, query: &str, ) -> Result<Vec<Quote>, DieselError> { let author = find_author(conn, author_id)?; Quote::belonging_to(&author) .filter(quotes::quote.ilike(format!("%{}%", query))) .filter(quotes::guild_id.eq(guild_id)) .limit(5) .get_results::<Quote>(conn) } pub struct ListParams { pub amount: Option<i64>, /// a **1** indexed page number pub page: Option<i64>, } pub fn find_listed_quotes( conn: &PgConnection, author_id: &str, guild_id: &str, params: ListParams, ) -> Result<Vec<Quote>, DieselError> { let author = find_author(conn, author_id)?; let limit = params.amount.unwrap_or(5); Quote::belonging_to(&author) .limit(limit) .filter(quotes::guild_id.eq(guild_id)) .offset((params.page.unwrap_or(1) * limit) - limit) .get_results::<Quote>(conn) } #[cfg(test)] mod tests { use super::*; use db::Connector; #[test] fn it_can_make_quotes() { let connector = Connector::new(); let conn = connector.get_conn().unwrap(); conn.begin_test_transaction().unwrap(); let user_1 = "1"; let user_2 = "2"; create_quote( &conn, &NewQuote { created_by_id: user_1, quoted_by_id: user_2, quote: "Hello world!", message_id: "12345", guild_id: "1", }, ).unwrap(); let quote = find_rand_quote(&conn, user_1, "1").unwrap(); assert_eq!(quote.unwrap().quote, "Hello world!"); } #[test] fn it_can_list_quotes() { let connector = Connector::new(); let conn = connector.get_conn().unwrap(); conn.begin_test_transaction().unwrap(); let user_1 = "1"; let user_2 = "2"; let (quote_1, quote_2) = ("Hello world", "How fantastic!"); create_quote( &conn, &NewQuote { created_by_id: user_1, quoted_by_id: user_2, quote: quote_1, message_id: "12345", guild_id: "1", }, ).unwrap(); create_quote( &conn, &NewQuote { created_by_id: user_1, quoted_by_id: user_2, quote: quote_2, message_id: "56789", guild_id: "1", }, ).unwrap(); let quotes = find_listed_quotes( &conn, user_1, "1", ListParams { amount: Some(2), page: Some(1), }, ).unwrap(); let quotes_flat = quotes .iter() .map(|q| q.quote.to_string()) .collect::<Vec<String>>(); for quote in vec![quote_1, quote_2] { assert!(quotes_flat.contains(&quote.to_string())) } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub struct CommunicationBlockingAccessManager {} impl CommunicationBlockingAccessManager { pub fn IsBlockingActive() -> ::windows::core::Result<bool> { Self::ICommunicationBlockingAccessManagerStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) }) } #[cfg(feature = "Foundation")] pub fn IsBlockedNumberAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(number: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { Self::ICommunicationBlockingAccessManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), number.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn ShowBlockNumbersUI<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(phonenumbers: Param0) -> ::windows::core::Result<bool> { Self::ICommunicationBlockingAccessManagerStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), phonenumbers.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn ShowUnblockNumbersUI<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(phonenumbers: Param0) -> ::windows::core::Result<bool> { Self::ICommunicationBlockingAccessManagerStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), phonenumbers.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn ShowBlockedCallsUI() -> ::windows::core::Result<()> { Self::ICommunicationBlockingAccessManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() }) } pub fn ShowBlockedMessagesUI() -> ::windows::core::Result<()> { Self::ICommunicationBlockingAccessManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() }) } pub fn ICommunicationBlockingAccessManagerStatics<R, F: FnOnce(&ICommunicationBlockingAccessManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CommunicationBlockingAccessManager, ICommunicationBlockingAccessManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for CommunicationBlockingAccessManager { const NAME: &'static str = "Windows.ApplicationModel.CommunicationBlocking.CommunicationBlockingAccessManager"; } pub struct CommunicationBlockingAppManager {} impl CommunicationBlockingAppManager { pub fn IsCurrentAppActiveBlockingApp() -> ::windows::core::Result<bool> { Self::ICommunicationBlockingAppManagerStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) }) } pub fn ShowCommunicationBlockingSettingsUI() -> ::windows::core::Result<()> { Self::ICommunicationBlockingAppManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }) } #[cfg(feature = "Foundation")] pub fn RequestSetAsActiveBlockingAppAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { Self::ICommunicationBlockingAppManagerStatics2(|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<bool>>(result__) }) } pub fn ICommunicationBlockingAppManagerStatics<R, F: FnOnce(&ICommunicationBlockingAppManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CommunicationBlockingAppManager, ICommunicationBlockingAppManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ICommunicationBlockingAppManagerStatics2<R, F: FnOnce(&ICommunicationBlockingAppManagerStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CommunicationBlockingAppManager, ICommunicationBlockingAppManagerStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for CommunicationBlockingAppManager { const NAME: &'static str = "Windows.ApplicationModel.CommunicationBlocking.CommunicationBlockingAppManager"; } #[repr(transparent)] #[doc(hidden)] pub struct ICommunicationBlockingAccessManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICommunicationBlockingAccessManagerStatics { type Vtable = ICommunicationBlockingAccessManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1c969998_9d2a_5db7_edd5_0ce407fc2595); } #[repr(C)] #[doc(hidden)] pub struct ICommunicationBlockingAccessManagerStatics_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 bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, number: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phonenumbers: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phonenumbers: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICommunicationBlockingAppManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICommunicationBlockingAppManagerStatics { type Vtable = ICommunicationBlockingAppManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x77db58ec_14a6_4baa_942a_6a673d999bf2); } #[repr(C)] #[doc(hidden)] pub struct ICommunicationBlockingAppManagerStatics_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 bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ICommunicationBlockingAppManagerStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICommunicationBlockingAppManagerStatics2 { type Vtable = ICommunicationBlockingAppManagerStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x14a68edd_ed88_457a_a364_a3634d6f166d); } #[repr(C)] #[doc(hidden)] pub struct ICommunicationBlockingAppManagerStatics2_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, );
#![allow(unused_imports, unreachable_code, unused_variables, dead_code)] use apiw; use apiw::shared::ManagedStrategy; use apiw::Result; use crate::Game; use crate::THE_GAME; use crate::controller::{self, ControllerInput}; use crate::model; use crate::view; use crate::view::ViewCommand; use crate::view_assets; use apiw::application_support_functions::MessageBoxBuilder; use apiw::timer_proc; use apiw::window_proc; use domino::mvc::ViewToken; pub type UiWindow = apiw::windows_subsystem::window::ForeignWindow; pub type UiScopedDC<'a> = apiw::graphics_subsystem::device_context::ScopedDeviceContext<'a>; pub type UiLocalDC = apiw::graphics_subsystem::device_context::LocalDeviceContext; pub type UiResult<T> = apiw::Result<T>; pub type Size = apiw::graphics_subsystem::Size; pub type Point = apiw::graphics_subsystem::Point; pub type Rect = apiw::graphics_subsystem::Rect; pub type RGBColor = apiw::graphics_subsystem::RGBColor; use crate::model_config; use apiw::application_support_functions::OpenFileDialogBuilder; use apiw::application_support_functions::OpenFileDialogFlags; use apiw::application_support_functions::SaveFileDialogBuilder; use apiw::application_support_functions::SaveFileDialogFlags; pub use apiw::graphics_subsystem::draw::Draw as UiDraw; use std::path::PathBuf; pub fn ui_alert(msg: &str) { MessageBoxBuilder::new().message(msg).invoke().unwrap(); } pub struct Ui; impl Ui { pub(crate) fn initialization() -> apiw::Result<()> { #[cfg(windows)] { use apiw::full_windows_api::shared::ntdef::LANG_ENGLISH; use apiw::full_windows_api::shared::ntdef::SUBLANG_ENGLISH_US; use apiw::full_windows_api::um::winnls::SetThreadUILanguage; use apiw::full_windows_api::um::winnt::MAKELANGID; //unsafe { // SetThreadUILanguage(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)); //} } Self::create_main_window()?; THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::Initialize); Ok(()) })?; Ok(()) } fn call_open_file_dialog( parent: &UiWindow, filter_res_id: usize, default_ext: &str, ) -> Option<PathBuf> { //FIXME: filter. OpenFileDialogBuilder::new() .parent(parent) .default_extension(default_ext) .flags( OpenFileDialogFlags::SHOW_HELP | OpenFileDialogFlags::PATH_MUST_EXIST | OpenFileDialogFlags::FILE_MUST_EXIST | OpenFileDialogFlags::EXPLORER, ) .show_dialog() .expect("Error occurred") } fn call_save_file_dialog( parent: &UiWindow, filter_res_id: usize, default_ext: &str, ) -> Option<PathBuf> { //FIXME: filter. SaveFileDialogBuilder::new() .parent(parent) .default_extension(default_ext) .flags( SaveFileDialogFlags::SHOW_HELP | SaveFileDialogFlags::PATH_MUST_EXIST | SaveFileDialogFlags::EXPLORER, ) .show_dialog() .expect("Error occurred") } /* BOOL HandleMapFile(bool bSave, UINT nFilterResID, LPCTSTR lpszDefExt, LPTSTR lpszFile) { OPENFILENAME ofn; TCHAR szFilter[MAX_LOADSTRING]; ZeroMemory(&ofn, sizeof(ofn)); ofn.hwndOwner = hGame_MainWnd; ofn.lStructSize = sizeof(ofn); ofn.lpstrFile = lpszFile; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = MAX_PATH; LoadString(hInst, nFilterResID, szFilter, MAX_LOADSTRING); for (int i=0; szFilter[i]!='\0'; i++) if (szFilter[i] == '|') szFilter[i] = '\0'; ofn.lpstrFilter = szFilter; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.lpstrDefExt = lpszDefExt; if(bSave) { ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT | OFN_EXPLORER; return GetSaveFileName(&ofn); } else { ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER; return GetOpenFileName(&ofn); } } */ fn create_main_window() -> apiw::Result<()> { use apiw; use apiw::windows_subsystem::window::ForeignWindow; use apiw::windows_subsystem::window::WindowBuilder; use apiw::windows_subsystem::window::WindowClassBuilder; use apiw::windows_subsystem::window::WindowProcRequest; use apiw::windows_subsystem::window::WindowStyles; fn main_window_handler(mut request: WindowProcRequest) { use apiw::windows_subsystem::window::CommandEventArgs; use apiw::windows_subsystem::window::MouseEventArgs; request .route_create(|window: &ForeignWindow, _| -> apiw::Result<bool> { THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.redirect_output_target(Some(window.clone())); window.invalidate()?; Ok(()) })?; Ok(true) }) .route_paint(|window: &ForeignWindow| -> apiw::Result<()> { let mut paint_dc = window.do_paint()?; THE_GAME.with(|game| { let game = game.try_borrow().or_else(|_| apiw::internal_error())?; game.mvc.sync_output_with_parameter(&mut paint_dc); Ok(()) })?; Ok(()) }) .route_mouse( |_window: &ForeignWindow, mouse_args: MouseEventArgs| -> apiw::Result<bool> { THE_GAME.with(|game| { use apiw::windows_subsystem::window::MouseEventArgType; let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; let mut target = None; if let Some(point) = mouse_args.cursor_coordinate() { target = Some(game.mvc.view().hit_test(point)); } use crate::controller::KeyKind; use concerto::ActionInput; if let Some(target) = target.as_ref() { game.mvc.process_input(ControllerInput::ActionInput( ActionInput::CursorCoordinate(target.clone()), )); } if let Some(key_input) = match mouse_args.kind() { Some(MouseEventArgType::LeftButtonDown) => { Some(ActionInput::KeyDown(KeyKind::LButton)) } Some(MouseEventArgType::LeftButtonUp) => { Some(ActionInput::KeyUp(KeyKind::LButton)) } Some(MouseEventArgType::RightButtonDown) => { Some(ActionInput::KeyDown(KeyKind::RButton)) } Some(MouseEventArgType::RightButtonUp) => { Some(ActionInput::KeyUp(KeyKind::RButton)) } _ => None, } { game.mvc .process_input(ControllerInput::ActionInput(key_input)); if let Some(target) = target.as_ref() { game.mvc.process_input(ControllerInput::ActionInput( ActionInput::CursorCoordinate(target.clone()), )); } } Ok(()) })?; Ok(true) }, ) .route_command( |window: &ForeignWindow, args: CommandEventArgs| -> apiw::Result<()> { use crate::model::ModelCommand; use crate::view_assets::resources; match args.id() as isize { resources::IDM_FILE_NEW => { THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::NewGame, )); Ok(()) })?; } resources::IDM_FILE_GAME_EASY | resources::IDM_FILE_GAME_MEDIUM | resources::IDM_FILE_GAME_HARD => { THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; let boardsetting = match args.id() as isize { resources::IDM_FILE_GAME_EASY => { model_config::BoardSetting::EASY } resources::IDM_FILE_GAME_MEDIUM => { model_config::BoardSetting::NORMAL } resources::IDM_FILE_GAME_HARD => { model_config::BoardSetting::HARD } _ => unreachable!(), }; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::NewGameWithBoard(boardsetting), )); Ok(()) })?; } resources::IDM_FILE_MARK => { THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::ToggleAllowMarks, )); Ok(()) })?; } resources::IDM_ADVANCED_ZOOM_1x | resources::IDM_ADVANCED_ZOOM_2x | resources::IDM_ADVANCED_ZOOM_3x => { THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::UpdateZoomRatio(match args.id() as isize { resources::IDM_ADVANCED_ZOOM_1x => { model_config::ZoomRatio::Zoom1x } resources::IDM_ADVANCED_ZOOM_2x => { model_config::ZoomRatio::Zoom2x } resources::IDM_ADVANCED_ZOOM_3x => { model_config::ZoomRatio::Zoom3x } _ => unreachable!(), }), )); Ok(()) })?; } resources::IDM_FILE_EXIT => { window.destroy()?; } resources::IDM_ADVANCED_LOADMAP => { if let Some(path) = Ui::call_open_file_dialog(window, 0, "cmm") { THE_GAME.with(|game| { let mut game = game .try_borrow_mut() .or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::LoadMap(path), )); Ok(()) })?; } } resources::IDM_ADVANCED_SAVEMAP => { if let Some(path) = Ui::call_save_file_dialog(window, 0, "cmm") { THE_GAME.with(|game| { let mut game = game .try_borrow_mut() .or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::SaveMap(path), )); Ok(()) })?; } } resources::IDM_ADVANCED_RESTART => { THE_GAME.with(|game| { let mut game = game.try_borrow_mut().or_else(|_| apiw::internal_error())?; let game = &mut *game; game.mvc.process_input(ControllerInput::ModelCommand( ModelCommand::RestartGame, )); Ok(()) })?; } resources::IDM_HELP_ABOUT => { use apiw::windows_subsystem::dialog::DialogBuilder; DialogBuilder::new_from_resource_id(resources::IDD_ABOUTBOX as _) .invoke()?; } _ => {} } Ok(()) }, ) .route_destroy(|_window: &ForeignWindow| -> apiw::Result<()> { use apiw::windows_subsystem::message::ForeignMessageLoop; ForeignMessageLoop::request_quit(); Ok(()) }); } use apiw::windows_subsystem::window::TimerProcRequest; fn main_window_timer_handler(request: TimerProcRequest) { if let Some(window) = request.window() { let _ = window.invalidate(); } } let window_class = WindowClassBuilder::new("CharlesMineWnd") .background_brush_from_syscolor(apiw::windows_subsystem::window::SysColor::BUTTON_FACE) .cursor_from_syscursor(apiw::windows_subsystem::window::SysCursor::ARROW) .icon_from_resource_id(view_assets::resources::IDI_CHARLESMINE as _) .menu_from_resource_id(view_assets::resources::IDC_CHARLESMINE as _) .window_proc(window_proc!(main_window_handler)) .create_managed()?; /* wcex.style = CS_HREDRAW | CS_VREDRAW; */ let window = WindowBuilder::new(&window_class) .name("CharlesMine") .style( WindowStyles::CAPTION | WindowStyles::VISIBLE | WindowStyles::CLIPSIBLINGS | WindowStyles::SYSMENU | WindowStyles::OVERLAPPED | WindowStyles::MINIMIZEBOX, ) .create()?; use std::num::NonZeroUsize; use std::time::Duration; window .set_timer_with_id( NonZeroUsize::new(1).unwrap(), Duration::from_millis(100), timer_proc!(main_window_timer_handler), )? .show(apiw::shared::exe_cmd_show())? .update()?; Ok(()) } pub(crate) fn run_event_loop() -> apiw::Result<()> { use apiw::windows_subsystem::message::ForeignMessageLoop; let mut msgloop = ForeignMessageLoop::for_current_thread(); while let Some(msg) = msgloop.poll_wait()?.not_quit() { let _ = msg.dispatch(); } Ok(()) } }
use crate::messages::messages::Message; #[derive(Debug, Clone, PartialEq)] pub enum OpType { OpMessage(Message), OpDisconnect, OpPiece(u32, Vec<u8>), // idx * payload OpRequest(u32, u32, u32), // idx * offset * len OpDownStop, OpStop, } #[derive(Debug, Clone, PartialEq)] pub struct Op { pub id: u64, pub op_type: OpType, }
use crate::auth; use crate::handlers::types::*; use crate::Pool; use actix_web::{web, Error, HttpResponse}; use actix_web_httpauth::extractors::bearer::BearerAuth; use crate::controllers::channel_chat_controller::*; use crate::diesel::QueryDsl; use crate::diesel::RunQueryDsl; use crate::helpers::socket::push_channel_message; use crate::model::{ChannelChat, NewChannelChat, Space, SpaceChannel, User}; use crate::schema::channel_chats::dsl::*; use crate::schema::spaces::dsl::*; use crate::schema::spaces_channel::dsl::*; use crate::schema::users::dsl::*; use diesel::dsl::insert_into; use diesel::prelude::*; pub async fn send_message( db: web::Data<Pool>, token: BearerAuth, space_details: web::Path<ChannelPathInfo>, item: web::Json<ChatMessage>, ) -> Result<HttpResponse, Error> { match auth::validate_token(&token.token().to_string()) { Ok(res) => { if res == true { let conn = db.get().unwrap(); let decoded_token = auth::decode_token(&token.token().to_string()); let user = users .find(decoded_token.parse::<i32>().unwrap()) .first::<User>(&conn); let space: Space = spaces .filter(spaces_name.ilike(&space_details.info)) .first::<Space>(&conn) .unwrap(); let channel: SpaceChannel = spaces_channel .filter(space_id.eq(&space.id)) .filter(channel_name.ilike(&space_details.channel)) .first::<SpaceChannel>(&conn) .unwrap(); match user { Ok(user) => { let new_chat = NewChannelChat { user_id: &user.id, space_channel_id: &channel.id, chat: &item.chat, created_at: chrono::Local::now().naive_local(), }; let socket_channel = format!( "channel-chat-{}-{}", &space.spaces_name, channel.channel_name ); let response: Result<ChannelChat, diesel::result::Error> = insert_into(channel_chats) .values(&new_chat) .get_result(&conn); match response { Ok(response) => { let socket_message = ChannelMessage { message: response, user: user, }; push_channel_message( &socket_channel, &"channel_chat_created".to_string(), &socket_message, ) .await; Ok(HttpResponse::Ok().json(Response::new( true, "message sent successfully".to_string(), ))) } _ => Ok(HttpResponse::Ok() .json(ResponseError::new(false, "error adding chat".to_string()))), } } _ => Ok(HttpResponse::Ok().json(ResponseError::new( false, "error getting user details".to_string(), ))), } } else { Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))) } } Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))), } } pub async fn update_message( db: web::Data<Pool>, token: BearerAuth, space_details: web::Path<ChannelPathInfoWithId>, item: web::Json<ChatMessage>, ) -> Result<HttpResponse, Error> { match auth::validate_token(&token.token().to_string()) { Ok(res) => { if res == true { let conn = db.get().unwrap(); let decoded_token = auth::decode_token(&token.token().to_string()); let user = users .find(decoded_token.parse::<i32>().unwrap()) .first::<User>(&conn); match user { Ok(user) => { let updated_chat = diesel::update(channel_chats.find(space_details.id)) .set(chat.eq(&item.chat)) .execute(&conn); match updated_chat { Ok(_updated_chat) => { let message = channel_chats .find(space_details.id) .first::<ChannelChat>(&conn) .unwrap(); let socket_channel = format!( "channel-chat-{}-{}", &space_details.info, space_details.channel ); let socket_message = ChannelMessage { message: message, user: user, }; push_channel_message( &socket_channel, &"channel_chat_update".to_string(), &socket_message, ) .await; Ok(HttpResponse::Ok().json(Response::new( true, "message updated successfully".to_string(), ))) } _ => Ok(HttpResponse::Ok() .json(Response::new(false, "error updating chat".to_string()))), } } _ => Ok(HttpResponse::Ok().json(ResponseError::new( false, "error getting user details".to_string(), ))), } } else { Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))) } } Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))), } } pub async fn get_all_message( db: web::Data<Pool>, auth: BearerAuth, space_name_path: web::Path<ChannelPathInfo>, item: web::Query<PaginateQuery>, ) -> Result<HttpResponse, Error> { match auth::validate_token(&auth.token().to_string()) { Ok(res) => { if res == true { Ok(web::block(move || { get_all_message_db(db, auth.token().to_string(), space_name_path, item) }) .await .map(|response| HttpResponse::Ok().json(response)) .map_err(|_| { HttpResponse::Ok().json(Response::new(false, "Error getting chat".to_string())) })?) } else { Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))) } } Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))), } } pub async fn delete_message( db: web::Data<Pool>, auth: BearerAuth, channel_details: web::Path<IdPathInfo>, ) -> Result<HttpResponse, Error> { match auth::validate_token(&auth.token().to_string()) { Ok(res) => { if res == true { Ok(web::block(move || { delete_message_db(db, auth.token().to_string(), channel_details) }) .await .map(|response| HttpResponse::Ok().json(response)) .map_err(|_| { HttpResponse::Ok().json(Response::new(false, "Error deleting chat".to_string())) })?) } else { Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))) } } Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))), } }
use std::cell::RefCell; use ash::vk; use gpu_allocator::{vulkan::AllocationCreateDesc, AllocatorDebugSettings}; use super::error::GraphicsResult; pub struct Allocator { alloc: RefCell<gpu_allocator::vulkan::Allocator>, device: ash::Device, } impl Allocator { pub fn new( instance: ash::Instance, physical_device: vk::PhysicalDevice, device: ash::Device, ) -> Self { let debug = cfg!(debug_assertions); let alloc = gpu_allocator::vulkan::Allocator::new(&gpu_allocator::vulkan::AllocatorCreateDesc { instance, device: device.clone(), physical_device, debug_settings: AllocatorDebugSettings { log_memory_information: debug, log_leaks_on_shutdown: debug, store_stack_traces: false, log_allocations: debug, log_frees: debug, log_stack_traces: false, }, buffer_device_address: false, }) .unwrap(); Self { alloc: alloc.into(), device, } } pub fn create_buffer( &self, size: vk::DeviceSize, usage: vk::BufferUsageFlags, location: gpu_allocator::MemoryLocation, ) -> GraphicsResult<(vk::Buffer, gpu_allocator::vulkan::Allocation)> { let buffer_info = vk::BufferCreateInfo::builder() .size(size) .usage(usage) .sharing_mode(vk::SharingMode::EXCLUSIVE) .build(); let buffer = unsafe { self.device.create_buffer(&buffer_info, None) }?; let requirements = unsafe { self.device.get_buffer_memory_requirements(buffer) }; let alloc = self.alloc.borrow_mut().allocate(&AllocationCreateDesc { name: "Buffer allocation", requirements, location, linear: true, })?; unsafe { self.device .bind_buffer_memory(buffer, alloc.memory(), alloc.offset())?; } Ok((buffer, alloc)) } pub fn destroy_buffer(&self, buffer: vk::Buffer, alloc: gpu_allocator::vulkan::Allocation) { unsafe { self.device.destroy_buffer(buffer, None); } self.alloc.borrow_mut().free(alloc).unwrap(); } pub fn create_image( &self, width: u32, height: u32, format: vk::Format, usage: vk::ImageUsageFlags, location: gpu_allocator::MemoryLocation, ) -> GraphicsResult<(vk::Image, gpu_allocator::vulkan::Allocation)> { let image_info = vk::ImageCreateInfo::builder() .image_type(vk::ImageType::TYPE_2D) .format(format) .extent(vk::Extent3D { width, height, depth: 1, }) .mip_levels(1) .array_layers(1) .samples(vk::SampleCountFlags::TYPE_1) .tiling(vk::ImageTiling::OPTIMAL) .usage(usage) .sharing_mode(vk::SharingMode::EXCLUSIVE) .initial_layout(vk::ImageLayout::UNDEFINED) .build(); let image = unsafe { self.device.create_image(&image_info, None) }?; let requirements = unsafe { self.device.get_image_memory_requirements(image) }; let alloc = self.alloc.borrow_mut().allocate(&AllocationCreateDesc { name: "Image allocation", requirements, location, linear: false, })?; unsafe { self.device .bind_image_memory(image, alloc.memory(), alloc.offset())?; } Ok((image, alloc)) } pub fn destroy_image(&self, image: vk::Image, alloc: gpu_allocator::vulkan::Allocation) { unsafe { self.device.destroy_image(image, None); } self.alloc.borrow_mut().free(alloc).unwrap(); } pub fn free(&self, alloc: gpu_allocator::vulkan::Allocation) { self.alloc.borrow_mut().free(alloc).unwrap(); } }
use crate::{ drawing::PyDrawing, graph::{GraphType, PyGraphAdapter}, }; use petgraph::visit::EdgeRef; use petgraph_layout_kamada_kawai::KamadaKawai; use pyo3::prelude::*; #[pyclass] #[pyo3(name = "KamadaKawai")] struct PyKamadaKawai { kamada_kawai: KamadaKawai, } #[pymethods] impl PyKamadaKawai { #[new] fn new(graph: &PyGraphAdapter, f: &PyAny) -> PyKamadaKawai { PyKamadaKawai { kamada_kawai: match graph.graph() { GraphType::Graph(native_graph) => KamadaKawai::new(native_graph, |e| { f.call1((e.id().index(),)).unwrap().extract().unwrap() }), _ => panic!("unsupported graph type"), }, } } fn select_node(&self, drawing: &PyDrawing) -> Option<usize> { self.kamada_kawai.select_node(drawing.drawing()) } fn apply_to_node(&self, m: usize, drawing: &mut PyDrawing) { self.kamada_kawai.apply_to_node(m, drawing.drawing_mut()); } fn run(&self, drawing: &mut PyDrawing) { self.kamada_kawai.run(drawing.drawing_mut()); } #[getter] fn eps(&self) -> f32 { self.kamada_kawai.eps } #[setter] fn set_eps(&mut self, value: f32) { self.kamada_kawai.eps = value; } } pub fn register(_py: Python<'_>, m: &PyModule) -> PyResult<()> { m.add_class::<PyKamadaKawai>()?; Ok(()) }
pub mod task1; pub mod task2; pub mod task3; pub mod post_b1_task;
use std::path; use crate::commands::{CommandLine, LllCommand, LllRunnable}; use crate::context::LllContext; use crate::error::LllError; use crate::window::LllView; use rustyline::completion::{escape, Quote}; #[cfg(unix)] static DEFAULT_BREAK_CHARS: [u8; 18] = [ b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', ]; #[cfg(unix)] static ESCAPE_CHAR: Option<char> = Some('\\'); #[derive(Clone, Debug)] pub struct RenameFile { path: path::PathBuf, } impl RenameFile { pub fn new(path: path::PathBuf) -> Self { RenameFile { path } } pub const fn command() -> &'static str { "rename" } pub fn rename_file( &self, path: &path::PathBuf, context: &mut LllContext, view: &LllView, ) -> std::io::Result<()> { let new_path = &self.path; if new_path.exists() { let err = std::io::Error::new(std::io::ErrorKind::AlreadyExists, "Filename already exists"); return Err(err); } std::fs::rename(&path, &new_path)?; let curr_tab = &mut context.tabs[context.curr_tab_index]; curr_tab .curr_list .update_contents(&context.config_t.sort_option)?; curr_tab.refresh_curr(&view.mid_win, &context.config_t); Ok(()) } } impl LllCommand for RenameFile {} impl std::fmt::Display for RenameFile { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", Self::command()) } } impl LllRunnable for RenameFile { fn execute(&self, context: &mut LllContext, view: &LllView) -> Result<(), LllError> { let mut path: Option<path::PathBuf> = None; let curr_list = &context.tabs[context.curr_tab_index].curr_list; if let Some(s) = curr_list.get_curr_ref() { path = Some(s.file_path().clone()); } if let Some(path) = path { match self.rename_file(&path, context, view) { Ok(_) => {} Err(e) => return Err(LllError::IO(e)), } ncurses::doupdate(); } Ok(()) } } #[derive(Clone, Debug)] pub struct RenameFileAppend; impl RenameFileAppend { pub fn new() -> Self { RenameFileAppend {} } pub const fn command() -> &'static str { "rename_append" } pub fn rename_file( &self, context: &mut LllContext, view: &LllView, file_name: String, ) -> Result<(), LllError> { let prefix; let suffix; if let Some(ext) = file_name.rfind('.') { prefix = format!("rename {}", &file_name[0..ext]); suffix = String::from(&file_name[ext..]); } else { prefix = format!("rename {}", file_name); suffix = String::new(); } let command = CommandLine::new(prefix, suffix); command.readline(context, view) } } impl LllCommand for RenameFileAppend {} impl std::fmt::Display for RenameFileAppend { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", Self::command()) } } impl LllRunnable for RenameFileAppend { fn execute(&self, context: &mut LllContext, view: &LllView) -> Result<(), LllError> { let curr_list = &context.tabs[context.curr_tab_index].curr_list; let file_name = match curr_list.get_curr_ref() { Some(s) => { let escaped = escape( String::from(s.file_name()), ESCAPE_CHAR, &DEFAULT_BREAK_CHARS, Quote::None, ); Some(escaped) } None => None, }; if let Some(file_name) = file_name { self.rename_file(context, view, file_name)?; ncurses::doupdate(); } Ok(()) } } #[derive(Clone, Debug)] pub struct RenameFilePrepend; impl RenameFilePrepend { pub fn new() -> Self { RenameFilePrepend {} } pub const fn command() -> &'static str { "rename_prepend" } pub fn rename_file( &self, context: &mut LllContext, view: &LllView, file_name: String, ) -> Result<(), LllError> { let prefix = String::from("rename "); let suffix = file_name; let command = CommandLine::new(prefix, suffix); command.readline(context, view) } } impl LllCommand for RenameFilePrepend {} impl std::fmt::Display for RenameFilePrepend { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", Self::command()) } } impl LllRunnable for RenameFilePrepend { fn execute(&self, context: &mut LllContext, view: &LllView) -> Result<(), LllError> { let curr_list = &context.tabs[context.curr_tab_index].curr_list; let file_name = match curr_list.get_curr_ref() { Some(s) => { let escaped = escape( String::from(s.file_name()), ESCAPE_CHAR, &DEFAULT_BREAK_CHARS, Quote::None, ); Some(escaped) } None => None, }; if let Some(file_name) = file_name { self.rename_file(context, view, file_name)?; ncurses::doupdate(); } Ok(()) } }
#[doc = "Reader of register PP"] pub type R = crate::R<u32, super::PP>; #[doc = "Reader of field `SC`"] pub type SC_R = crate::R<bool, bool>; #[doc = "Reader of field `NB`"] pub type NB_R = crate::R<bool, bool>; #[doc = "Reader of field `MS`"] pub type MS_R = crate::R<bool, bool>; #[doc = "Reader of field `MSE`"] pub type MSE_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Smart Card Support"] #[inline(always)] pub fn sc(&self) -> SC_R { SC_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - 9-Bit Support"] #[inline(always)] pub fn nb(&self) -> NB_R { NB_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Modem Support"] #[inline(always)] pub fn ms(&self) -> MS_R { MS_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Modem Support Extended"] #[inline(always)] pub fn mse(&self) -> MSE_R { MSE_R::new(((self.bits >> 3) & 0x01) != 0) } }
use std::collections::HashSet; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; fn read_lines<P>(filename: P) -> Vec<String> where P: AsRef<Path>, { let file = File::open(filename).expect("Error opening file!"); BufReader::new(file) .lines() .map(|line| line.expect("Error reading line!")) .collect() } fn part1(lines: &Vec<String>) { let earliest: isize = lines[0].parse().unwrap(); let busses: Vec<isize> = lines[1] .split(',') .filter(|bus| *bus != "x") .map(|bus| bus.parse().unwrap()) .collect(); if let Some(best_bus) = busses.iter().fold(None, |best, bus| { if let Some(best_bus) = best { let best_wait: isize = (earliest % best_bus) - best_bus; let wait = (earliest % bus) - bus; if wait.abs() < best_wait.abs() { Some(bus) } else { Some(best_bus) } } else { Some(bus) } }) { let x = (earliest / best_bus) + 1; // integer division! println!("{}", ((best_bus * x) - earliest) * best_bus) } } fn part2(lines: &Vec<String>) { let busses: Vec<(usize, usize)> = lines[1] .split(',') .enumerate() .filter(|(_, bus)| *bus != "x") .map(|(i, bus)| (i, bus.parse::<usize>().unwrap())) .collect(); let (_, first_arrival) = busses[0]; let mut step_size = first_arrival; let mut already_arrived_busses: HashSet<usize> = HashSet::new(); // start with the first one; we're already there already_arrived_busses.insert(first_arrival); let mut time: usize = first_arrival; loop { // get the busses that arrived here for the first time and multiply them to step size let arrived_busses: HashSet<usize> = busses .iter() .filter(|(offset, bus)| (time + offset) % bus == 0) .map(|(_, bus)| *bus) .collect(); // if all busses arrived, we're done if arrived_busses.len() == busses.len() { println!("{}", time); return; } // get busses that arrived for the first time here and add them to the step size (thanks cavey) for bus in arrived_busses.difference(&already_arrived_busses) { step_size *= bus; } already_arrived_busses.extend(&arrived_busses); time += step_size; } } // fn part2_slow(lines: &Vec<String>) { // let busses: Vec<(usize, usize)> = lines[1] // .split(',') // .enumerate() // .filter(|(_, bus)| *bus != "x") // .map(|(i, bus)| (i, bus.parse::<usize>().unwrap())) // .collect(); // let (_, first_arrival) = busses[0]; // // zero would technically mean everyting matches, so start with the first arrival // let mut time: usize = first_arrival; // loop { // let mut done = true; // for (offset, bus) in &busses { // if (time + offset) % bus != 0 { // done = false; // break; // } // // let delta = (time % bus) - bus; // // dbg!(delta); // } // if done { // println!("{}", time); // return; // } else { // time += first_arrival; // } // } // } fn main() { let lines = read_lines("input.txt"); part1(&lines); part2(&lines); }
use std::borrow::Cow; /// A classification of if a given request was successful /// /// Note: the variant order defines the override order for classification /// e.g. a request that encounters both a ClientErr and a ServerErr will /// be recorded as a ServerErr #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub enum Classification { /// Successful request Ok, /// The request was to an unrecognised path /// /// This is used by the metrics collection to avoid generating a new set of metrics /// for a request path that doesn't correspond to a valid route PathNotFound, /// The request was unsuccessful but it was not the fault of the service ClientErr, /// The request was unsuccessful and it was the fault of the service ServerErr, } pub fn classify_response<B>(response: &http::Response<B>) -> (Cow<'static, str>, Classification) { let status = response.status(); match status { http::StatusCode::OK | http::StatusCode::CREATED | http::StatusCode::NO_CONTENT => { classify_headers(Some(response.headers())) } http::StatusCode::BAD_REQUEST => ("bad request".into(), Classification::ClientErr), // This is potentially over-zealous but errs on the side of caution http::StatusCode::NOT_FOUND => ("not found".into(), Classification::PathNotFound), http::StatusCode::TOO_MANY_REQUESTS => { ("too many requests".into(), Classification::ClientErr) } http::StatusCode::INTERNAL_SERVER_ERROR => { ("internal server error".into(), Classification::ServerErr) } _ => ( format!("unexpected status code: {status}").into(), Classification::ServerErr, ), } } /// gRPC indicates failure via a [special][1] header allowing it to signal an error /// at the end of an HTTP chunked stream as part of the [response trailer][2] /// /// [1]: https://grpc.github.io/grpc/core/md_doc_statuscodes.html /// [2]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Trailer pub fn classify_headers( headers: Option<&http::header::HeaderMap>, ) -> (Cow<'static, str>, Classification) { match headers.and_then(|headers| headers.get("grpc-status")) { Some(header) => { let value = match header.to_str() { Ok(value) => value, Err(_) => return ("grpc status not string".into(), Classification::ServerErr), }; let value: i32 = match value.parse() { Ok(value) => value, Err(_) => return ("grpc status not integer".into(), Classification::ServerErr), }; match value { 0 => ("ok".into(), Classification::Ok), 1 => ("cancelled".into(), Classification::ClientErr), 2 => ("unknown".into(), Classification::ServerErr), 3 => ("invalid argument".into(), Classification::ClientErr), 4 => ("deadline exceeded".into(), Classification::ServerErr), 5 => ("not found".into(), Classification::ClientErr), 6 => ("already exists".into(), Classification::ClientErr), 7 => ("permission denied".into(), Classification::ClientErr), 8 => ("resource exhausted".into(), Classification::ServerErr), 9 => ("failed precondition".into(), Classification::ClientErr), 10 => ("aborted".into(), Classification::ClientErr), 11 => ("out of range".into(), Classification::ClientErr), 12 => ("unimplemented".into(), Classification::ServerErr), 13 => ("internal".into(), Classification::ServerErr), 14 => ("unavailable".into(), Classification::ServerErr), 15 => ("data loss".into(), Classification::ServerErr), 16 => ("unauthenticated".into(), Classification::ClientErr), _ => ( format!("unrecognised status code: {value}").into(), Classification::ServerErr, ), } } None => ("ok".into(), Classification::Ok), } }
#[doc = r"Value read from the register"] pub struct R { bits: u8, } #[doc = r"Value to write to the register"] pub struct W { bits: u8, } impl super::RXCSRH2 { #[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() -> u8 { 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 USB_RXCSRH2_INCOMPRXR { bits: bool, } impl USB_RXCSRH2_INCOMPRXR { #[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 _USB_RXCSRH2_INCOMPRXW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_INCOMPRXW<'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 u8) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_DTR { bits: bool, } impl USB_RXCSRH2_DTR { #[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 _USB_RXCSRH2_DTW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_DTW<'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 u8) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_DTWER { bits: bool, } impl USB_RXCSRH2_DTWER { #[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 _USB_RXCSRH2_DTWEW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_DTWEW<'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 u8) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_DMAMODR { bits: bool, } impl USB_RXCSRH2_DMAMODR { #[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 _USB_RXCSRH2_DMAMODW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_DMAMODW<'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 u8) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_PIDERRR { bits: bool, } impl USB_RXCSRH2_PIDERRR { #[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 _USB_RXCSRH2_PIDERRW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_PIDERRW<'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 u8) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_DMAENR { bits: bool, } impl USB_RXCSRH2_DMAENR { #[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 _USB_RXCSRH2_DMAENW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_DMAENW<'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 u8) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_AUTORQR { bits: bool, } impl USB_RXCSRH2_AUTORQR { #[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 _USB_RXCSRH2_AUTORQW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_AUTORQW<'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 << 6); self.w.bits |= ((value as u8) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_AUTOCLR { bits: bool, } impl USB_RXCSRH2_AUTOCLR { #[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 _USB_RXCSRH2_AUTOCLW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_AUTOCLW<'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 << 7); self.w.bits |= ((value as u8) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_DISNYETR { bits: bool, } impl USB_RXCSRH2_DISNYETR { #[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 _USB_RXCSRH2_DISNYETW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_DISNYETW<'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 u8) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH2_ISOR { bits: bool, } impl USB_RXCSRH2_ISOR { #[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 _USB_RXCSRH2_ISOW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH2_ISOW<'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 << 6); self.w.bits |= ((value as u8) & 1) << 6; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } #[doc = "Bit 0 - Incomplete RX Transmission Status"] #[inline(always)] pub fn usb_rxcsrh2_incomprx(&self) -> USB_RXCSRH2_INCOMPRXR { let bits = ((self.bits >> 0) & 1) != 0; USB_RXCSRH2_INCOMPRXR { bits } } #[doc = "Bit 1 - Data Toggle"] #[inline(always)] pub fn usb_rxcsrh2_dt(&self) -> USB_RXCSRH2_DTR { let bits = ((self.bits >> 1) & 1) != 0; USB_RXCSRH2_DTR { bits } } #[doc = "Bit 2 - Data Toggle Write Enable"] #[inline(always)] pub fn usb_rxcsrh2_dtwe(&self) -> USB_RXCSRH2_DTWER { let bits = ((self.bits >> 2) & 1) != 0; USB_RXCSRH2_DTWER { bits } } #[doc = "Bit 3 - DMA Request Mode"] #[inline(always)] pub fn usb_rxcsrh2_dmamod(&self) -> USB_RXCSRH2_DMAMODR { let bits = ((self.bits >> 3) & 1) != 0; USB_RXCSRH2_DMAMODR { bits } } #[doc = "Bit 4 - PID Error"] #[inline(always)] pub fn usb_rxcsrh2_piderr(&self) -> USB_RXCSRH2_PIDERRR { let bits = ((self.bits >> 4) & 1) != 0; USB_RXCSRH2_PIDERRR { bits } } #[doc = "Bit 5 - DMA Request Enable"] #[inline(always)] pub fn usb_rxcsrh2_dmaen(&self) -> USB_RXCSRH2_DMAENR { let bits = ((self.bits >> 5) & 1) != 0; USB_RXCSRH2_DMAENR { bits } } #[doc = "Bit 6 - Auto Request"] #[inline(always)] pub fn usb_rxcsrh2_autorq(&self) -> USB_RXCSRH2_AUTORQR { let bits = ((self.bits >> 6) & 1) != 0; USB_RXCSRH2_AUTORQR { bits } } #[doc = "Bit 7 - Auto Clear"] #[inline(always)] pub fn usb_rxcsrh2_autocl(&self) -> USB_RXCSRH2_AUTOCLR { let bits = ((self.bits >> 7) & 1) != 0; USB_RXCSRH2_AUTOCLR { bits } } #[doc = "Bit 4 - Disable NYET"] #[inline(always)] pub fn usb_rxcsrh2_disnyet(&self) -> USB_RXCSRH2_DISNYETR { let bits = ((self.bits >> 4) & 1) != 0; USB_RXCSRH2_DISNYETR { bits } } #[doc = "Bit 6 - Isochronous Transfers"] #[inline(always)] pub fn usb_rxcsrh2_iso(&self) -> USB_RXCSRH2_ISOR { let bits = ((self.bits >> 6) & 1) != 0; USB_RXCSRH2_ISOR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Incomplete RX Transmission Status"] #[inline(always)] pub fn usb_rxcsrh2_incomprx(&mut self) -> _USB_RXCSRH2_INCOMPRXW { _USB_RXCSRH2_INCOMPRXW { w: self } } #[doc = "Bit 1 - Data Toggle"] #[inline(always)] pub fn usb_rxcsrh2_dt(&mut self) -> _USB_RXCSRH2_DTW { _USB_RXCSRH2_DTW { w: self } } #[doc = "Bit 2 - Data Toggle Write Enable"] #[inline(always)] pub fn usb_rxcsrh2_dtwe(&mut self) -> _USB_RXCSRH2_DTWEW { _USB_RXCSRH2_DTWEW { w: self } } #[doc = "Bit 3 - DMA Request Mode"] #[inline(always)] pub fn usb_rxcsrh2_dmamod(&mut self) -> _USB_RXCSRH2_DMAMODW { _USB_RXCSRH2_DMAMODW { w: self } } #[doc = "Bit 4 - PID Error"] #[inline(always)] pub fn usb_rxcsrh2_piderr(&mut self) -> _USB_RXCSRH2_PIDERRW { _USB_RXCSRH2_PIDERRW { w: self } } #[doc = "Bit 5 - DMA Request Enable"] #[inline(always)] pub fn usb_rxcsrh2_dmaen(&mut self) -> _USB_RXCSRH2_DMAENW { _USB_RXCSRH2_DMAENW { w: self } } #[doc = "Bit 6 - Auto Request"] #[inline(always)] pub fn usb_rxcsrh2_autorq(&mut self) -> _USB_RXCSRH2_AUTORQW { _USB_RXCSRH2_AUTORQW { w: self } } #[doc = "Bit 7 - Auto Clear"] #[inline(always)] pub fn usb_rxcsrh2_autocl(&mut self) -> _USB_RXCSRH2_AUTOCLW { _USB_RXCSRH2_AUTOCLW { w: self } } #[doc = "Bit 4 - Disable NYET"] #[inline(always)] pub fn usb_rxcsrh2_disnyet(&mut self) -> _USB_RXCSRH2_DISNYETW { _USB_RXCSRH2_DISNYETW { w: self } } #[doc = "Bit 6 - Isochronous Transfers"] #[inline(always)] pub fn usb_rxcsrh2_iso(&mut self) -> _USB_RXCSRH2_ISOW { _USB_RXCSRH2_ISOW { w: self } } }
use std::collections::HashMap; use std::str::FromStr; use crate::ast::*; use crate::connection::Connection; use crate::errors::PsqlpackErrorKind::*; use crate::errors::{PsqlpackError, PsqlpackResult, PsqlpackResultExt}; use crate::model::Extension; use crate::semver::Semver; use crate::sql::lexer; use crate::sql::parser::{FunctionArgumentListParser, FunctionReturnTypeParser, SqlTypeParser}; use postgres::row::Row; use postgres::types::{FromSql, Type}; use postgres::Client as PostgresClient; use regex::Regex; use slog::Logger; pub struct Capabilities { pub server_version: Semver, pub extensions: Vec<Extension>, pub database_exists: bool, } impl Capabilities { pub fn from_connection(log: &Logger, connection: &Connection) -> PsqlpackResult<Capabilities> { let log = log.new(o!("capabilities" => "from_connection")); trace!(log, "Connecting to host"); let mut client = connection.connect_host()?; let version = Self::server_version(&mut client)?; let db_result = dbtry!(client.query(Q_DATABASE_EXISTS, &[&connection.database()])); let exists = !db_result.is_empty(); // If it exists, then connect directly as we'll get better results if exists { client = connection.connect_database()?; } let extensions = client .query(Q_EXTENSIONS, &[]) .chain_err(|| QueryExtensionsError)? .iter() .map(|row| row.into()) .collect(); Ok(Capabilities { server_version: version, extensions, database_exists: exists, }) } fn server_version(client: &mut PostgresClient) -> PsqlpackResult<Semver> { let rows = client .query("SHOW SERVER_VERSION;", &[]) .map_err(|e| DatabaseError(format!("Failed to retrieve server version: {}", e)))?; let row = rows.iter().last(); if let Some(row) = row { let version: Semver = row.get(0); Ok(version) } else { bail!(DatabaseError("Failed to retrieve version from server".into())) } } pub fn available_extensions(&self, name: &str, version: Option<Semver>) -> Vec<&Extension> { let mut available = self .extensions .iter() .filter(|x| x.name.eq(name) && (version.is_none() || version.unwrap().eq(&x.version))) .collect::<Vec<_>>(); available.sort_by(|a, b| b.version.cmp(&a.version)); available } // I'm not incredibly happy with this name, but it'll work for now pub(crate) fn with_context<'a>(&'a self, extension: &'a Extension) -> ExtensionCapabilities<'a> { ExtensionCapabilities { capabilities: self, extension, } } } pub(crate) struct ExtensionCapabilities<'a> { capabilities: &'a Capabilities, extension: &'a Extension, } pub trait DefinableCatalog { fn schemata(&self, client: &mut PostgresClient, database: &str) -> PsqlpackResult<Vec<SchemaDefinition>>; fn types(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<TypeDefinition>>; fn functions(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<FunctionDefinition>>; fn tables(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<TableDefinition>>; fn indexes(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<IndexDefinition>>; } impl DefinableCatalog for Capabilities { fn schemata(&self, client: &mut PostgresClient, database: &str) -> PsqlpackResult<Vec<SchemaDefinition>> { let schemata = client .query(Q_SCHEMAS, &[&database]) .chain_err(|| PackageQuerySchemasError)? .iter() .map(|row| row.into()) .collect(); Ok(schemata) } fn types(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<TypeDefinition>> { let types = client .query(&format!("{} {}", CTE_TYPES, Q_CTE_STANDARD)[..], &[]) .chain_err(|| PackageQueryTypesError)? .iter() .map(|row| row.into()) .collect(); Ok(types) } fn functions(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<FunctionDefinition>> { let mut functions = Vec::new(); let query = &client .query(&format!("{} {}", CTE_FUNCTIONS, Q_CTE_STANDARD)[..], &[]) .chain_err(|| PackageQueryFunctionsError)?; for row in query { let function = parse_function(&row)?; functions.push(function); } Ok(functions) } fn tables(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<TableDefinition>> { let mut tables = HashMap::new(); let query = &client .query(&format!("{} {}", CTE_TABLES, Q_CTE_STANDARD)[..], &[]) .chain_err(|| PackageQueryTablesError)?; for row in query { let table: TableDefinition = row.into(); tables.insert(table.name.to_string(), table); } // Get a list of columns and map them to the appropriate tables let query = &client .query( &format!("{} {} ORDER BY fqn, num", CTE_COLUMNS, Q_CTE_STANDARD)[..], &[], ) .chain_err(|| PackageQueryColumnsError)?; for row in query { let fqn: String = row.get(1); if let Some(definition) = tables.get_mut(&fqn) { definition.columns.push(row.into()); } } // Get a list of table constraints let query = &client .query( &format!("{} {} ORDER BY fqn", CTE_TABLE_CONSTRAINTS, Q_CTE_STANDARD)[..], &[], ) .chain_err(|| PackageQueryTableConstraintsError)?; for row in query { let fqn: String = row.get(1); if let Some(definition) = tables.get_mut(&fqn) { definition.constraints.push(row.into()); } } Ok(tables.into_iter().map(|(_, b)| b).collect()) } fn indexes(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<IndexDefinition>> { // Get a list of indexes let mut indexes = Vec::new(); let cte = match self.server_version.cmp(&Semver::new(9, 6, None)) { ::std::cmp::Ordering::Less => CTE_INDEXES_94_THRU_96, _ => CTE_INDEXES, }; let query = &client .query(&format!("{} {}", cte, Q_CTE_STANDARD)[..], &[]) .chain_err(|| PackageQueryIndexesError)?; for row in query { let index: IndexDefinition = row.into(); indexes.push(index); } Ok(indexes) } } impl<'a> DefinableCatalog for ExtensionCapabilities<'a> { fn schemata(&self, _client: &mut PostgresClient, _database: &str) -> PsqlpackResult<Vec<SchemaDefinition>> { // Schema is hard to retrieve. Let's assume it's not necessary for extensions for now. Ok(Vec::new()) } fn types(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<TypeDefinition>> { let types = client .query( &format!("{} {}", CTE_TYPES, Q_CTE_EXTENSION)[..], &[&self.extension.name], ) .chain_err(|| PackageQueryTypesError)? .iter() .map(|row| row.into()) .collect(); Ok(types) } fn functions(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<FunctionDefinition>> { let mut functions = Vec::new(); let query = &client .query( &format!("{} {}", CTE_FUNCTIONS, Q_CTE_EXTENSION)[..], &[&self.extension.name], ) .chain_err(|| PackageQueryFunctionsError)?; for row in query { let function = parse_function(&row)?; functions.push(function); } Ok(functions) } fn tables(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<TableDefinition>> { let mut tables = HashMap::new(); let query = &client .query( &format!("{} {}", CTE_TABLES, Q_CTE_EXTENSION)[..], &[&self.extension.name], ) .chain_err(|| PackageQueryTablesError)?; for row in query { let table: TableDefinition = row.into(); tables.insert(table.name.to_string(), table); } // Get a list of columns and map them to the appropriate tables let query = &client .query( &format!("{} {} ORDER BY fqn, num", CTE_COLUMNS, Q_CTE_EXTENSION)[..], &[&self.extension.name], ) .chain_err(|| PackageQueryColumnsError)?; for row in query { let fqn: String = row.get(1); if let Some(definition) = tables.get_mut(&fqn) { definition.columns.push(row.into()); } } // Get a list of table constraints let query = &client .query( &format!("{} {} ORDER BY fqn", CTE_TABLE_CONSTRAINTS, Q_CTE_EXTENSION)[..], &[&self.extension.name], ) .chain_err(|| PackageQueryTableConstraintsError)?; for row in query { let fqn: String = row.get(1); if let Some(definition) = tables.get_mut(&fqn) { definition.constraints.push(row.into()); } } Ok(tables.into_iter().map(|(_, b)| b).collect()) } fn indexes(&self, client: &mut PostgresClient) -> PsqlpackResult<Vec<IndexDefinition>> { // Get a list of indexes let mut indexes = Vec::new(); let cte = match self.capabilities.server_version.cmp(&Semver::new(9, 6, None)) { ::std::cmp::Ordering::Less => CTE_INDEXES_94_THRU_96, _ => CTE_INDEXES, }; let query = &client .query(&format!("{} {}", cte, Q_CTE_EXTENSION)[..], &[&self.extension.name]) .chain_err(|| PackageQueryIndexesError)?; for row in query { let index: IndexDefinition = row.into(); indexes.push(index); } Ok(indexes) } } impl<'a> FromSql<'a> for Semver { // TODO: Better error handling fn from_sql(_: &Type, raw: &[u8]) -> Result<Semver, Box<dyn ::std::error::Error + Sync + Send>> { let version = String::from_utf8_lossy(raw); Ok(Semver::from_str(&version).unwrap()) } fn accepts(ty: &Type) -> bool { *ty == Type::TEXT } } static Q_DATABASE_EXISTS: &str = "SELECT 1 FROM pg_database WHERE datname=$1;"; static Q_EXTENSIONS: &str = "SELECT name, version, installed, requires FROM pg_available_extension_versions "; static Q_CTE_STANDARD: &str = " SELECT c.* FROM cte c WHERE NOT EXISTS (SELECT 1 FROM pg_depend WHERE pg_depend.objid=c.oid AND deptype IN ('e','i'))"; static Q_CTE_EXTENSION: &str = " SELECT c.* FROM cte c INNER JOIN pg_depend d ON d.objid=c.oid INNER JOIN pg_extension e ON d.refobjid = e.oid WHERE d.deptype = 'e' and e.extname = $1"; impl<'row> From<&Row> for Extension { fn from(row: &Row) -> Self { Extension { name: row.get(0), version: row.get(1), installed: row.get(2), } } } static Q_SCHEMAS: &str = "SELECT schema_name FROM information_schema.schemata WHERE catalog_name = $1 AND schema_name !~* 'pg_|information_schema'"; impl<'row> From<&Row> for SchemaDefinition { fn from(row: &Row) -> Self { SchemaDefinition { name: row.get(0) } } } // Types: https://www.postgresql.org/docs/9.6/sql-createtype.html // typcategory: https://www.postgresql.org/docs/9.6/catalog-pg-type.html#CATALOG-TYPCATEGORY-TABLE static CTE_TYPES: &str = " WITH cte AS ( SELECT pg_type.oid, typcategory, nspname, typname, array_agg(labels.enumlabel) AS enumlabels FROM pg_type INNER JOIN pg_namespace ON pg_namespace.oid=typnamespace LEFT JOIN ( SELECT enumtypid, enumlabel FROM pg_catalog.pg_enum ORDER BY enumtypid, enumsortorder ) labels ON labels.enumtypid=pg_type.oid WHERE -- exclude pg schemas and information catalog nspname !~* 'pg_|information_schema' AND -- Types beginning with _ are auto created (e.g. arrays) typname !~ '^_' GROUP BY pg_type.oid, typcategory, nspname, typname ORDER BY pg_type.oid, typcategory, nspname, typname ) "; impl<'row> From<&Row> for TypeDefinition { fn from(row: &Row) -> Self { let category: i8 = row.get(1); let category = category as u8; let schema = row.get(2); let name = row.get(3); let kind = match category as char { // TODO: All types 'C' => TypeDefinitionKind::Composite, // TODO add composite details 'E' => TypeDefinitionKind::Enum(row.get(4)), 'R' => TypeDefinitionKind::Range, // TODO add range details 'U' => TypeDefinitionKind::UserDefined, kind => panic!("Unexpected kind: {}", kind), }; TypeDefinition { name: ObjectName { schema, name }, kind, } } } static CTE_FUNCTIONS: &str = " WITH cte AS ( SELECT pg_proc.oid, nspname, proname, prosrc, pg_get_function_arguments(pg_proc.oid), lanname, pg_get_function_result(pg_proc.oid) FROM pg_proc JOIN pg_namespace ON pg_namespace.oid = pg_proc.pronamespace JOIN pg_language ON pg_language.oid = pg_proc.prolang WHERE nspname !~* 'pg_|information_schema' AND proname !~ '^_' )"; fn parse_function(row: &Row) -> PsqlpackResult<FunctionDefinition> { let schema_name: String = row.get(1); let function_name: String = row.get(2); let function_src: String = row.get(3); let raw_args: String = row.get(4); let lan_name: String = row.get(5); let raw_result: String = row.get(6); // Parse some of the results let language = match &lan_name[..] { "internal" => FunctionLanguage::Internal, "c" => FunctionLanguage::C, "sql" => FunctionLanguage::SQL, _ => FunctionLanguage::PostgreSQL, }; fn lexical(err: lexer::LexicalError) -> PsqlpackError { LexicalError( err.reason.to_owned(), err.line.to_owned(), err.line_number, err.start_pos, err.end_pos, ) .into() } fn parse(err: lalrpop_util::ParseError<(), lexer::Token, &'static str>) -> PsqlpackError { InlineParseError(err).into() } let function_args = if raw_args.is_empty() { Vec::new() } else { lexer::tokenize_body(&raw_args) .map_err(lexical) .and_then(|tokens| FunctionArgumentListParser::new().parse(tokens).map_err(parse)) .chain_err(|| PackageFunctionArgsInspectError(raw_args))? }; let return_type = lexer::tokenize_body(&raw_result) .map_err(&lexical) .and_then(|tokens| FunctionReturnTypeParser::new().parse(tokens).map_err(parse)) .chain_err(|| PackageFunctionReturnTypeInspectError(raw_result))?; // Set up the function definition Ok(FunctionDefinition { name: ObjectName { schema: Some(schema_name), name: function_name, }, arguments: function_args, return_type, body: function_src, language, }) } static CTE_TABLES: &str = " WITH cte AS ( SELECT pg_class.oid, nspname, relname FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace WHERE pg_class.relkind='r' AND nspname !~* 'pg_|information_schema' )"; impl<'row> From<&Row> for TableDefinition { fn from(row: &Row) -> Self { TableDefinition { name: ObjectName { schema: Some(row.get(1)), name: row.get(2), }, columns: Vec::new(), // This gets loaded later constraints: Vec::new(), // This gets loaded later } } } static CTE_COLUMNS: &str = " WITH cte AS ( SELECT DISTINCT pgc.oid, CONCAT(ns.nspname, '.', pgc.relname) as fqn, ns.nspname as schema_name, pgc.relname as table_name, a.attnum as num, a.attname as name, CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) AND pg_get_expr(def.adbin, def.adrelid) = 'nextval(''' || (pg_get_serial_sequence (a.attrelid::regclass::text, a.attname))::regclass || '''::regclass)' THEN CASE a.atttypid WHEN 'int'::regtype THEN 'serial' WHEN 'int8'::regtype THEN 'bigserial' WHEN 'int2'::regtype THEN 'smallserial' END ELSE format_type(a.atttypid, a.atttypmod) END AS data_type, a.attnotnull as notnull, coalesce(i.indisprimary,false) as primary_key, pg_get_expr(def.adbin, def.adrelid) as default FROM pg_attribute a INNER JOIN pg_class pgc ON pgc.oid = a.attrelid INNER JOIN pg_namespace ns ON ns.oid = pgc.relnamespace LEFT JOIN pg_index i ON pgc.oid = i.indrelid AND i.indkey[0] = a.attnum LEFT JOIN pg_attrdef def ON a.attrelid = def.adrelid AND a.attnum = def.adnum WHERE attnum > 0 AND pgc.relkind='r' AND NOT a.attisdropped AND ns.nspname !~* 'pg_|information_schema' ORDER BY pgc.relname, a.attnum )"; impl<'row> From<&Row> for ColumnDefinition { fn from(row: &Row) -> Self { // Do the column constraints first let mut constraints = Vec::new(); let not_null: bool = row.get(7); let primary_key: bool = row.get(8); // TODO: Default value + unique constraints.push(if not_null { ColumnConstraint::NotNull } else { ColumnConstraint::Null }); if primary_key { constraints.push(ColumnConstraint::PrimaryKey); } let sql_type: String = row.get(6); ColumnDefinition { name: row.get(5), sql_type: sql_type.into(), constraints, } } } static CTE_TABLE_CONSTRAINTS: &str = " WITH cte AS ( SELECT tcls.oid, CONCAT(tc.table_schema, '.', tc.table_name) fqn, tc.constraint_schema, tc.table_name, tc.constraint_type, tc.constraint_name, string_agg(DISTINCT kcu.column_name, ',') as column_names, ccu.table_name as foreign_table_name, string_agg(DISTINCT ccu.column_name, ',') as foreign_column_names, pgcls.reloptions as pk_parameters, confupdtype, confdeltype, confmatchtype::text FROM information_schema.table_constraints as tc JOIN (SELECT DISTINCT column_name, constraint_name, table_name, ordinal_position FROM information_schema.key_column_usage ORDER BY ordinal_position ASC) kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage as ccu on ccu.constraint_name = tc.constraint_name JOIN pg_catalog.pg_namespace pgn ON pgn.nspname = tc.constraint_schema JOIN pg_catalog.pg_namespace tn ON tn.nspname = tc.table_schema JOIN pg_catalog.pg_class tcls ON tcls.relname=tc.table_name AND tcls.relnamespace=tn.oid LEFT JOIN pg_catalog.pg_class pgcls ON pgcls.relname=tc.constraint_name AND pgcls.relnamespace = pgn.oid LEFT JOIN pg_catalog.pg_constraint pgcon ON pgcon.conname=tc.constraint_name AND pgcon.connamespace = pgn.oid WHERE constraint_type in ('PRIMARY KEY','FOREIGN KEY') GROUP BY tcls.oid, fqn, tc.constraint_schema, tc.table_name, tc.constraint_type, tc.constraint_name, ccu.table_name, pgcls.reloptions, confupdtype, confdeltype, confmatchtype::text )"; lazy_static! { static ref FILL_FACTOR: Regex = Regex::new("fillfactor=(\\d+)").unwrap(); } fn parse_index_parameters(raw_parameters: Option<Vec<String>>) -> Option<Vec<IndexParameter>> { match raw_parameters { Some(parameters) => { // We only have one type at the moment if let Some(parameters) = parameters.first() { let ff = FILL_FACTOR.captures(&parameters[..]); if let Some(ff) = ff { Some(vec![IndexParameter::FillFactor(ff[1].parse::<u32>().unwrap())]) } else { None } } else { None } } None => None, } } impl<'row> From<&Row> for TableConstraint { fn from(row: &Row) -> Self { let schema: String = row.get(2); let constraint_type: String = row.get(4); let constraint_name: String = row.get(5); let raw_column_names: String = row.get(6); let column_names: Vec<String> = raw_column_names.split_terminator(',').map(|s| s.into()).collect(); match &constraint_type[..] { "PRIMARY KEY" => TableConstraint::Primary { name: constraint_name, columns: column_names, parameters: parse_index_parameters(row.get(9)), }, "FOREIGN KEY" => { let foreign_table_name: String = row.get(7); let raw_foreign_column_names: String = row.get(8); let foreign_column_names: Vec<String> = raw_foreign_column_names .split_terminator(',') .map(|s| s.into()) .collect(); let ev: String = row.get(12); let match_type = match &ev[..] { "f" => Some(ForeignConstraintMatchType::Full), "s" => Some(ForeignConstraintMatchType::Simple), "p" => Some(ForeignConstraintMatchType::Partial), _ => None, }; let mut events = Vec::new(); let update_event: i8 = row.get(10); match update_event as u8 as char { 'r' => events.push(ForeignConstraintEvent::Update(ForeignConstraintAction::Restrict)), 'c' => events.push(ForeignConstraintEvent::Update(ForeignConstraintAction::Cascade)), 'd' => events.push(ForeignConstraintEvent::Update(ForeignConstraintAction::SetDefault)), 'n' => events.push(ForeignConstraintEvent::Update(ForeignConstraintAction::SetNull)), 'a' => events.push(ForeignConstraintEvent::Update(ForeignConstraintAction::NoAction)), _ => {} } let delete_event: i8 = row.get(11); match delete_event as u8 as char { 'r' => events.push(ForeignConstraintEvent::Delete(ForeignConstraintAction::Restrict)), 'c' => events.push(ForeignConstraintEvent::Delete(ForeignConstraintAction::Cascade)), 'd' => events.push(ForeignConstraintEvent::Delete(ForeignConstraintAction::SetDefault)), 'n' => events.push(ForeignConstraintEvent::Delete(ForeignConstraintAction::SetNull)), 'a' => events.push(ForeignConstraintEvent::Delete(ForeignConstraintAction::NoAction)), _ => {} } TableConstraint::Foreign { name: constraint_name, columns: column_names, ref_table: ObjectName { schema: Some(schema), name: foreign_table_name, }, ref_columns: foreign_column_names, match_type, events: if events.is_empty() { None } else { Some(events) }, } } unknown => panic!("Unknown constraint type: {}", unknown), } } } static CTE_INDEXES_94_THRU_96: &str = " WITH cte AS ( SELECT tc.oid, ns.nspname AS schema_name, tc.relname AS table_name, ic.relname AS index_name, idx.indisunique AS is_unique, am.amname AS index_type, ARRAY( SELECT json_build_object( 'colname', pg_get_indexdef(idx.indexrelid, k + 1, TRUE), 'orderable', am.amcanorder, 'asc', CASE WHEN idx.indoption[k] & 1 = 0 THEN true ELSE false END, 'desc', CASE WHEN idx.indoption[k] & 1 = 1 THEN true ELSE false END, 'nulls_first', CASE WHEN idx.indoption[k] & 2 = 2 THEN true ELSE false END, 'nulls_last', CASE WHEN idx.indoption[k] & 2 = 0 THEN true ELSE false END ) FROM generate_subscripts(idx.indkey, 1) AS k ORDER BY k ) AS index_keys, ic.reloptions AS storage_parameters FROM pg_index AS idx JOIN pg_class AS ic ON ic.oid = idx.indexrelid JOIN pg_am AS am ON ic.relam = am.oid JOIN pg_namespace AS ns ON ic.relnamespace = ns.OID JOIN pg_class AS tc ON tc.oid = idx.indrelid WHERE ns.nspname !~* 'pg_|information_schema' AND idx.indisprimary = false ) "; // Index query >= 9.6 static CTE_INDEXES: &str = " WITH cte AS ( SELECT tc.oid, ns.nspname AS schema_name, tc.relname AS table_name, ic.relname AS index_name, idx.indisunique AS is_unique, am.amname AS index_type, ARRAY( SELECT json_build_object( 'colname', pg_get_indexdef(idx.indexrelid, k + 1, TRUE), 'orderable', pg_index_column_has_property(idx.indexrelid, k + 1, 'orderable'), 'asc', pg_index_column_has_property(idx.indexrelid, k + 1, 'asc'), 'desc', pg_index_column_has_property(idx.indexrelid, k + 1, 'desc'), 'nulls_first', pg_index_column_has_property(idx.indexrelid, k + 1, 'nulls_first'), 'nulls_last', pg_index_column_has_property(idx.indexrelid, k + 1, 'nulls_last') ) FROM generate_subscripts(idx.indkey, 1) AS k ORDER BY k ) AS index_keys, ic.reloptions AS storage_parameters FROM pg_index AS idx JOIN pg_class AS ic ON ic.oid = idx.indexrelid JOIN pg_am AS am ON ic.relam = am.oid JOIN pg_namespace AS ns ON ic.relnamespace = ns.OID JOIN pg_class AS tc ON tc.oid = idx.indrelid WHERE ns.nspname !~* 'pg_|information_schema' AND idx.indisprimary = false ) "; impl<'row> From<&Row> for IndexDefinition { fn from(row: &Row) -> Self { let schema: String = row.get(1); let table: String = row.get(2); let name: String = row.get(3); let unique: bool = row.get(4); let index_type: String = row.get(5); let index_type = match &index_type[..] { "btree" => Some(IndexType::BTree), "gin" => Some(IndexType::Gin), "gist" => Some(IndexType::Gist), "hash" => Some(IndexType::Hash), _ => None, }; let columns: Vec<serde_json::Value> = row.get(6); let columns = columns .iter() .map(|c| c.as_object().unwrap()) .map(|map| IndexColumn { name: map["colname"].as_str().unwrap().to_owned(), order: if map["orderable"].as_bool().unwrap_or(false) { if map["asc"].as_bool().unwrap_or(false) { Some(IndexOrder::Ascending) } else if map["desc"].as_bool().unwrap_or(false) { Some(IndexOrder::Descending) } else { None } } else { None }, null_position: if map["orderable"].as_bool().unwrap_or(false) { if map["nulls_first"].as_bool().unwrap_or(false) { Some(IndexPosition::First) } else if map["nulls_last"].as_bool().unwrap_or(false) { Some(IndexPosition::Last) } else { None } } else { None }, }) .collect(); let storage_parameters = parse_index_parameters(row.get(7)); IndexDefinition { name, table: ObjectName { schema: Some(schema), name: table, }, columns, unique, index_type, storage_parameters, } } } impl From<String> for SqlType { fn from(s: String) -> Self { // TODO: Error handling for this let tokens = lexer::tokenize_body(&s).unwrap(); SqlTypeParser::new().parse(tokens).unwrap() } }
// 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::vec::Vec; use super::super::fs::dentry::*; use super::super::fd::*; use super::super::task::*; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::qlib::mem::io::*; use super::super::syscalls::syscalls::*; pub fn SysGetDents(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let addr = args.arg1 as u64; let size = args.arg2 as i32; return GetDents(task, fd, addr, size); } pub fn GetDents(task: &Task, fd: i32, addr: u64, size: i32) -> Result<i64> { let minSize = Dirent::SmallestDirent() as i32; if minSize > size { return Err(Error::SysError(SysErr::EINVAL)) } let n = getDents(task, fd, addr, size, Serialize)?; return Ok(n) } pub fn SysGetDents64(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let addr = args.arg1 as u64; let size = args.arg2 as i32; return GetDents64(task, fd, addr, size); } pub fn GetDents64(task: &Task, fd: i32, addr: u64, size: i32) -> Result<i64> { let minSize = Dirent::SmallestDirent64() as i32; if minSize > size { return Err(Error::SysError(SysErr::EINVAL)) } let n = getDents(task, fd, addr, size, Serialize64)?; return Ok(n) } const WIDTH: u32 = 8; fn getDents(task: &Task, fd: i32, addr: u64, size: i32, f: fn(&Task, &Dirent, &mut IOWriter) -> Result<i32>) -> Result<i64> { let dir = task.GetFile(fd)?; task.CheckPermission(addr, size as u64, true, false)?; let mut writer : MemBuf = MemBuf::New(size as usize); let len = size; // writer.Len() as i32; let mut ds = HostDirentSerializer::New(f, &mut writer, WIDTH, len); let err = dir.ReadDir(task, &mut ds); match err { Ok(()) => { let buf = &writer.data; task.CopyOutSlice(buf, addr, size as usize)?; return Ok(buf.len() as i64) }, Err(Error::EOF) => return Ok(0), Err(e) => return Err(e) } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] struct OldDirentHdr { pub Ino: u64, pub Off: u64, pub Reclen: u16, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] struct DirentHdr { pub OldHdr: OldDirentHdr, pub Type: u8, } #[repr(C)] #[derive(Debug, Default, Clone)] struct Dirent { pub Hdr: DirentHdr, pub Name: Vec<u8>, } impl Dirent { pub fn New(width: u32, name: &str, attr: &DentAttr, offset: u64) -> Self { let mut d = Dirent { Hdr: DirentHdr { OldHdr: OldDirentHdr { Ino: attr.InodeId, Off: offset, Reclen: 0, }, Type: attr.Type.ToType(), }, Name: name.as_bytes().to_vec(), }; d.Name.push(0); d.Hdr.OldHdr.Reclen = d.padRec(width as usize); return d; } fn padRec(&mut self, width: usize) -> u16 { //let a = mem::size_of::<DirentHdr>() + self.Name.len(); let a = 19 + self.Name.len(); let r = (a + width) & !(width - 1); let padding = r - a; self.Name.append(&mut vec![0; padding]); return r as u16; } pub fn SmallestDirent() -> u32 { return 18 + WIDTH + 1; } pub fn SmallestDirent64() -> u32 { return 19 + WIDTH; } } fn Serialize64(task: &Task, dir: &Dirent, w: &mut IOWriter) -> Result<i32> { let addr = &dir.Hdr as *const _ as u64; let size = 18; //mem::size_of::<DirentHdr>(); //let slice = task.GetSlice::<u8>(addr, size)?; let buf = task.CopyInVec::<u8>(addr, size)?; let n1 = w.Write(&buf)?; let n3 = w.Write(&[dir.Hdr.Type; 1])?; let n2 = w.Write(&dir.Name)?; return Ok((n1 + n2 + n3) as i32) } fn Serialize(task: &Task, dir: &Dirent, w: &mut IOWriter) -> Result<i32> { let addr = &dir.Hdr as *const _ as u64; let size = 18; //mem::size_of::<OldDirentHdr>(); //let slice = task.GetSlice::<u8>(addr, size)?; let buf = task.CopyInVec::<u8>(addr, size)?; let n1 = w.Write(&buf)?; let n2 = w.Write(&dir.Name)?; let n3 = w.Write(&[dir.Hdr.Type; 1])?; return Ok((n1 + n2 + n3) as i32) } struct HostDirentSerializer<'a> { pub serialize: fn(&Task, &Dirent, &mut IOWriter) -> Result<i32>, pub w: &'a mut IOWriter, pub width: u32, pub offset: u64, pub written: i32, pub size: i32, } impl<'a> HostDirentSerializer<'a> { pub fn New(f: fn(&Task, &Dirent, &mut IOWriter) -> Result<i32>, w: &'a mut IOWriter, width: u32, size: i32) -> Self { return Self { serialize: f, w: w, width: width, offset: 0, written: 0, size: size } } } impl<'a> DentrySerializer for HostDirentSerializer<'a> { fn CopyOut(&mut self, task: &Task, name: &str, attr: &DentAttr) -> Result<()> { self.offset += 1; let d = Dirent::New(self.width, name, attr, self.offset); let mut writer = MemBuf::New(1024); let res = (self.serialize)(task, &d, &mut writer); let n = match res { Ok(n) => n, Err(e) => { self.offset -= 1; return Err(e) } }; if n as i32 > self.size - self.written { self.offset -= 1; return Err(Error::EOF) } let b = &writer.data; match self.w.Write(&b[..n as usize]) { Ok(_) => (), Err(e) => { self.offset -= 1; return Err(e); } } self.written += n as i32; return Ok(()) } fn Written(&self) -> usize { return self.written as usize } }
use super::*; use std::ops::*; impl BitAnd<BlackMask> for WhiteMask { type Output = Mask; fn bitand(self, rhs: BlackMask) -> Self::Output { self.0 & rhs.0 } } impl BitAnd<WhiteMask> for BlackMask { type Output = Mask; fn bitand(self, rhs: WhiteMask) -> Self::Output { self.0 & rhs.0 } }
mod systems; mod components; mod renderables; mod state; pub use crate::prelude::*; pub mod prelude { pub use crate::systems::*; pub use crate::components::*; pub use crate::renderables::*; pub use crate::state::*; pub use vermarine_engine::prelude::*; }
use input_i_scanner::{scan_with, InputIScanner}; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); let n = scan_with!(_i_i, usize); let ab = scan_with!(_i_i, (f64, f64); n); let f = |mut t: f64| -> f64 { let mut res = 0.0; for &(a, b) in &ab { if t >= a / b { t -= a / b; res += a; } else { res += b * t; // b * t < a break; } } res }; let g = |mut t: f64| -> f64 { let mut res = 0.0; for &(a, b) in ab.iter().rev() { if t >= a / b { t -= a / b; res += a; } else { res += b * t; // b * t < a break; } } res }; let mut total = 0.0; for &(a, _) in &ab { total += a; } let mut ng = 0.0; let mut ok = 1e10; for _ in 0..100 { let mid = (ng + ok) / 2.0; if f(mid) + g(mid) >= total { ok = mid; } else { ng = mid; } } println!("{}", f(ok)); }
//! A module for groups /// A `Monoid` trait is implemented for types that is possible to have /// a associative binary operation and an identity element. /// /// So, in orther to implement this trait, a type should follow these rules: /// 1. `a ⊗ b ⊗ c == (a ⊗ b) ⊗ c == a ⊗ (b ⊗ c)` where `a`, `b` and `c` of the /// same type and `⊗` a associative binary operation /// 2. `a ⊗ ε == ε ⊗ a == a` where `ε` is the identity element of the type /// /// **Note:** The identity element is implemented as function cause not all types that /// are `Monoid`s in the Rust standard library have a `const fn` constructor, like `Vec` /// and `LinkedList`. If they became `const fn` (Vec is already in the process to become), /// it will be updated to use associated constant. pub trait Monoid: Sized { const IDENTITY: Self; /// A function that return the identity value/element of the `Monoid` fn identity_value() -> Self { Self::IDENTITY } /// A `Monoid` method that represents a associative binary operation fn associate(self, other: &Self) -> Self; /// A function that folds over using the `associate`function and the `identity_value` #[inline] fn mfold(xs: &[Self]) -> Self { xs.iter().fold(Self::identity_value(), Self::associate) } }
pub mod dto; pub mod config; #[macro_use] pub mod utils; pub mod fetcher; pub mod display; pub mod parser; pub mod http; pub mod viewer; #[cfg(test)] #[macro_use] extern crate hamcrest;
use std::thread::current; use rand::Rng; use crate::cell::Cell; use crate::grid::Grid; use crate::row::Row; use crate::automaton::Automaton; use crate::renderer::Renderer; pub struct BriansBrain { grid: Grid, } impl BriansBrain { pub fn new(n_rows: usize, n_cols: usize) -> BriansBrain { let mut rows = vec![ Row { cells: vec![Cell { value: 0 }; n_cols] }; n_rows ]; // Blinker // rows[4].cells[4].value = 1; // rows[4].cells[5].value = 1; // rows[4].cells[6].value = 1; // Glider // rows[4].cells[4].value = 2; // rows[4].cells[5].value = 2; // rows[4].cells[6].value = 2; // rows[3].cells[6].value = 2; // rows[2].cells[5].value = 2; // Random // let mut rng = rand::thread_rng(); // for row in rows.iter_mut() { // for col in row.cells.iter_mut() { // let b: bool = rng.gen(); // if b { // col.value = 2; // } // } // } rows[n_rows / 2].cells[n_cols / 2 - 1].value = 2; rows[n_rows / 2].cells[n_cols / 2].value = 2; // rows[n_rows / 2].cells[n_cols / 2 + 1].value = 2; rows[n_rows / 2 - 1].cells[n_cols / 2 - 1].value = 2; rows[n_rows / 2 - 1].cells[n_cols / 2].value = 2; // rows[n_rows / 2 - 1].cells[n_cols / 2 + 1].value = 2; // rows[n_rows / 2 - 2].cells[n_cols / 2 - 1].value = 2; // rows[n_rows / 2 - 2].cells[n_cols / 2].value = 2; // rows[n_rows / 2 - 2].cells[n_cols / 2 + 1].value = 2; // rows[n_rows / 2 - 3].cells[n_cols / 2 - 1].value = 2; // rows[n_rows / 2 - 3].cells[n_cols / 2].value = 2; // rows[n_rows / 2 - 3].cells[n_cols / 2 + 1].value = 2; BriansBrain { grid: Grid { rows }, } } fn next_iteration(grid: &Grid) -> Grid { let mut new_rows = Vec::new(); for row in grid.rows.iter().enumerate() { let mut new_row = Row { cells: Vec::new() }; for col in row.1.cells.iter().enumerate() { // A cell turns on if it was off and has exactly two neighbors // All other on cells become dying. // All dying cells become off. let mut living_neighbours = 0; for dir in 0..=7 { let (x, y) = grid.neib(col.0, row.0, dir).unwrap(); if grid.rows[y].cells[x].value == 2 { living_neighbours += 1; } } let current_value = col.1.value; match living_neighbours { 2 => { match current_value { 0 => new_row.cells.push(Cell { value: 2 }), 1 => new_row.cells.push(Cell { value: 0 }), 2 => new_row.cells.push(Cell { value: 1 }), _ => (), } }, _ => { match current_value { 0 => new_row.cells.push(Cell { value: 0 }), 1 => new_row.cells.push(Cell { value: 0 }), 2 => new_row.cells.push(Cell { value: 1 }), _ => (), } } } } new_rows.push(new_row); } Grid { rows: new_rows } } } impl Automaton for BriansBrain { fn next(&mut self) { self.grid = BriansBrain::next_iteration(&self.grid); } fn render(&self, renderer: &mut dyn Renderer) { renderer.render_grid(&self.grid); } }
extern crate lisp; use lisp::util::interner::Interner; use lisp::syntax::codemap::Source; use lisp::syntax::parse; use lisp::syntax::pp; fn eq(source: &str, expected_repr: &str, interner: &mut Interner) { let source = Source::new(source); let expr = parse::expr(source, interner).unwrap(); let repr = pp::expr(&expr, source); assert_eq!(repr, expected_repr) } #[test] fn nil_true_false() { let ref mut interner = Interner::new(); eq("nil", "nil", interner); eq("true", "true", interner); eq("false", "false", interner); } #[test] fn numbers() { let ref mut interner = Interner::new(); eq("1", "1", interner); eq(" 7 ", "7", interner); } #[test] fn symbols() { let ref mut interner = Interner::new(); eq("+", "+", interner); eq("abc", "abc", interner); eq(" abc ", "abc", interner); eq("abc5", "abc5", interner); eq("abc-def", "abc-def", interner); } #[test] fn string() { let ref mut interner = Interner::new(); eq("\"abc\"", "\"abc\"", interner); eq(" \"abc\" ", "\"abc\"", interner); eq("\"abc (with parens)\"", "\"abc (with parens)\"", interner); // TODO handle escaping //eq(r#""abc\"def""#, "", interner); eq(r#""abc\ndef""#, "\"abc\\ndef\"", interner); } #[test] fn lists() { let ref mut interner = Interner::new(); eq("(+ 1 2)", "(+ 1 2)", interner); eq("((3 4))", "((3 4))", interner); eq("(+ 1 (+ 2 3))", "(+ 1 (+ 2 3))", interner); eq(" ( + 1 (+ 2 3 ) ) ", "(+ 1 (+ 2 3))", interner); eq("(* 1 2)", "(* 1 2)", interner); eq("(** 1 2)", "(** 1 2)", interner); } #[test] fn commas() { let ref mut interner = Interner::new(); eq("(1 2, 3,,,,),,", "(1 2 3)", interner); } // TODO implement quoting #[test] #[ignore] fn quoting() { let ref mut interner = Interner::new(); eq(("'1"), "(quote 1)", interner); eq(("'(1 2 3)"), "(quote (1 2 3))", interner); eq(("`1"), "(quasiquote 1)", interner); eq(("`(1 2 3)"), "(quasiquote (1 2 3))", interner); eq(("~1"), "(unquote 1)", interner); eq(("~(1 2 3)"), "(unquote (1 2 3))", interner); eq(("~@(1 2 3)"), "(splice-unquote (1 2 3))", interner); } #[test] fn errors() { let ref mut interner = Interner::new(); assert!(parse::expr(Source::new("(1 2"), interner).is_err()); assert!(parse::expr(Source::new("[1 2"), interner).is_err()); assert!(parse::expr(Source::new("\"abc"), interner).is_err()); } // TODO optional tests
use failure_derive::*; use std::io; #[derive(Fail, Debug)] pub enum BlobError { #[fail(display = "No Room")] NoRoom, #[fail(display = "Too Big {}", 0)] TooBig(u64), #[fail(display = "Not Found")] NotFound, #[fail(display = "Bincode {}", 0)] Bincode(bincode::Error), #[fail(display = "IO {}", 0)] IO(io::Error), } impl From<bincode::Error> for BlobError { fn from(e: bincode::Error) -> Self { Self::Bincode(e) } } impl From<io::Error> for BlobError { fn from(e: io::Error) -> Self { Self::IO(e) } }
use crate::PluginRegistrar; use crate::{ ReporterFunction, ReporterInitFunction }; use crate::{ PublisherFunction, PublisherInitFunction }; use crate::PluginError; use crate::FunctionType; use std::collections::HashMap; use std::sync::Arc; use libloading::Library; #[derive(Default)] pub struct DefaultPluginRegistrar { reporter_init: HashMap<String, Box<dyn ReporterInitFunction + Send>>, reporter: HashMap<String, Box<dyn ReporterFunction + Send>>, publisher_init: HashMap<String, Box<dyn PublisherInitFunction + Send>>, publisher: HashMap<String, Box<dyn PublisherFunction + Send>>, libs: Vec<Arc<Library>> } impl DefaultPluginRegistrar { pub fn new() -> DefaultPluginRegistrar { DefaultPluginRegistrar::default() } } impl PluginRegistrar for DefaultPluginRegistrar { fn register_plugin(&mut self, name: &str, func: FunctionType) { match func { FunctionType::Publisher(f) => { self.publisher.insert(name.to_string(), f); }, FunctionType::PublisherInit(f) => { self.publisher_init.insert(name.to_string(), f); }, FunctionType::Reporter(f) => { self.reporter.insert(name.to_string(), f); }, FunctionType::ReporterInit(f) => { self.reporter_init.insert(name.to_string(), f); } }; } fn register_lib(&mut self, lib: Arc<libloading::Library>) { self.libs.push(lib); } fn get_reporter_init(&self, name: &str) -> Result<&Box<dyn ReporterInitFunction + Send>, PluginError> { if self.reporter_init.contains_key(name) { Ok(self.reporter_init.get(name).unwrap()) } else { Err(PluginError::FunctionNotFound { p: name.to_string(), fname: "Reporter Init Function".to_string() }) } } fn get_reporter(&self, name: &str) -> Result<&Box<dyn ReporterFunction + Send>, PluginError> { if self.reporter.contains_key(name) { Ok(self.reporter.get(name).unwrap()) } else { Err(PluginError::FunctionNotFound { p: name.to_string(), fname: "Reporter Function".to_string() }) } } fn get_publisher_init(&self, name: &str) -> Result<&Box<dyn PublisherInitFunction + Send>, PluginError> { if self.publisher_init.contains_key(name) { Ok(self.publisher_init.get(name).unwrap()) } else { Err(PluginError::FunctionNotFound { p: name.to_string(), fname: "Publisher init function".to_string() }) } } fn get_publisher(&self, name: &str) -> Result<&Box<dyn PublisherFunction + Send>, PluginError> { if self.publisher.contains_key(name) { Ok(self.publisher.get(name).unwrap()) } else { Err(PluginError::FunctionNotFound { p: name.to_string(), fname: "Publisher function".to_string() }) } } }
use num::{BigUint, BigInt, ToPrimitive, FromPrimitive}; use num::traits::{One, Zero}; use crate::rand; use crate::primes; use crate::num::bigint::ToBigInt; const KEY_SIZE: usize = 1024; const BLOCK_SIZE: usize = 4; // Block size in increments of 8 bytes /// Return greatest common divisor of elements a and b as a BigUint fn _gcd(a: BigUint, b: BigUint) -> BigUint { return if b == Zero::zero() { a.clone() } else { _gcd(b.clone(), a % b.clone()) } } /// Return modular multiplicative inverse of a and m as a BigUint fn _modular_multiplicative_inverse(mut a: BigUint, mut m: BigUint) -> BigUint { // This code adapted from GeeksForGeeks: https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ let mut a = a.to_bigint().unwrap(); let mut m = m.to_bigint().unwrap(); let mut m0 = m.clone(); let mut y: BigInt = BigInt::zero(); let mut x: BigInt = BigInt::one(); if m == x { return y.to_biguint().unwrap(); } while a > BigInt::one() { let mut q: BigInt = a.clone() / m.clone(); let mut t: BigInt = m.clone(); // m is remainder now, process same as Euclid's algo m = a % m; a = t; t = y.clone(); y = x - q * y.clone(); x = t; } // Make x positive if needed if x < BigInt::zero() { x = x + m0; } return x.to_biguint().unwrap(); } fn _gen_key(num_prime_bits: usize) -> ((BigUint, BigUint), BigUint) { // Algorithm adapted from https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Key_generation let mut rng = rand::new(); let one: BigUint = One::one(); let mut prime_rng = rand::new(); // 1. Choose distinct prime numbers prime_one and prime_two let prime_one = primes::gen_large_prime(num_prime_bits, &mut prime_rng); let mut prime_two = primes::gen_large_prime(num_prime_bits, &mut prime_rng); while prime_one == prime_two { prime_two = primes::gen_large_prime(num_prime_bits, &mut prime_rng); } // 2. Compute n = prime_one * prime_two (only needed as return val, computed below) // n is used as the modulus for both the public and private keys. // 3. Compute lambda_n = lcm(p-1, q-1). Note that lcm(a, b) = abs(a*b} / gcd(a, b). // Here, prime_one > 0 and prime_two > 0, so prime_one*prime_two = abs(prime_one*prime_two) let prod: BigUint = (prime_one.clone() - one.clone()) * (prime_two.clone() - one.clone()); let lambda_n = prod / _gcd(prime_one.clone() - one.clone(), prime_two.clone() - one.clone()); // 4. Choose an integer e s.t. 1 < e < lambda_n, and s.t. e and lambda_n are co-prime let mut exponent = BigUint::from_i32(65_537).unwrap(); assert!(one.clone() < exponent.clone() && exponent.clone() < lambda_n.clone()); assert_eq!(_gcd(exponent.clone(), lambda_n.clone()), One::one()); // 5. Compute d s.t. d * e ≡ 1 mod lambda_n. d is modular multiplicative inverse of e, lambda_n // d is the private key exponent let d: BigUint = _modular_multiplicative_inverse(exponent.clone(), lambda_n.clone()); // Return tuple of (public_key, private_key) ((&prime_one * &prime_two, exponent), d) } pub fn gen_key() -> ((BigUint, BigUint), BigUint) { _gen_key(KEY_SIZE / 2) } /// Helper function, encrypts bytes contained in blocks using the given publickey, returns cipher as /// a vector of `BigUint` /// /// # Arguments /// * `blocks` - Packed vector of `u32`. The encryption algorith is run on each block, resulting in a /// corresponding output block in the returned vector /// * `key` - Public key to encrypt with, tuple of the form (modulus, exponent) where both are BigUints fn _encrypt_bytes(blocks: Vec<u32>, key: (BigUint, BigUint)) -> Vec<BigUint> { print!("Pre-Encrypt Blocks: [ "); for b in &blocks { print!("{:#b}, ", b); } println!("]"); let mut output: Vec<BigUint> = vec![BigUint::from_i32(0).unwrap(); blocks.len()]; for (i, block) in blocks.iter().enumerate() { output[i] = BigUint::from_u32(block.clone()).unwrap() .modpow(&key.1.clone(), &key.0.clone()); } output } /// Helper function, decrypts cipher blocks using the given private key and exponent, returning the decrypted /// blocks as a vector of `u32` /// /// # Arguments /// * `cipher` - The cipher to decrypt, as a reference to a vector of BigUint encrypted blocks /// * `privkey` - The private key to use when decrypting the given cipher /// * `modulus` - The "modulus" component of the public key, also used for decryption fn _decrypt_bytes(cipher: &Vec<BigUint>, privkey: BigUint, modulus: BigUint) -> Vec<u32> { let mut dec_blocks = vec![0_u32; cipher.len()]; for (i, enc_block) in cipher.iter().enumerate() { match enc_block.modpow(&privkey.clone(), &modulus.clone()) .to_u32() { Some(thing) => dec_blocks[i] = thing, None => { println!("> Error: Found garbage value when attempting to decrypt. Your key is probably incorrect."); dec_blocks[i] = 0; } } } print!("Post-Decrypt Blocks: [ "); for b in &dec_blocks { print!("{:#b}, ", b); } println!("]"); dec_blocks } /// Helper function, packs a string into a vector of `u32` (which is the return value) to pass to encryption /// function /// /// # Arguments /// * `msg` - The string to pack into `Vec<u32>` fn _pack_string(msg: &str) -> Vec<u32> { let offset: usize = if (msg.len() % BLOCK_SIZE) == 0 { 0 } else { 1 }; let mut blocks = vec![0_u32; (msg.len() / BLOCK_SIZE) + offset]; let mut block_index = 0; let mut block_count = 0; for c in msg.chars() { blocks[block_index] ^= c as u32; block_count += 1; if block_count == BLOCK_SIZE { block_index += 1; block_count = 0; } else { blocks[block_index] <<= 8; } } blocks } /// Helper function, unpacks and returns a string from a vector of `u32` returned by decryption function. /// /// # Arguments /// * `blocks` - `Vec<u32>` to unpack characters from fn _unpack_string(mut blocks: Vec<u32>) -> String { let mut res: String = String::new(); for mut c in blocks.iter_mut().rev() { let mut c = *c; while c > 0 { let new_char = (c & 0b11111111) as u8; res = char::from(new_char).to_string().to_owned() + &res; // Mask to get rid of the bytes representing the character we just pulled out of this u32 c &= 0b11111111111111111111111100000000; c = c.overflowing_shr(8).0; } } res } /// Encrypts string `msg` using given public key /// /// # Arguments /// * `msg` - String to encrypt /// * `pubkey` - Publickey to use to encrypt `msg`, in format (modulus: `BigUint`, exponent: `BigUint') pub fn encrypt_str(msg: &str, pubkey: (BigUint, BigUint)) -> Vec<BigUint> { let packed_string = _pack_string(msg); _encrypt_bytes(packed_string, pubkey) } /// Returns cipher decrypted and unpacked as string /// /// # Arguments /// * `cipher` - Vector of `BigUint` representing encrypted string /// * `privkey` - The private key to use for decryption /// * `modulus` - The modulus component of the public key, also used in decryption pub fn decrypt_str(cipher: &Vec<BigUint>, privkey: BigUint, modulus: BigUint) -> String { let dec_blocks = _decrypt_bytes(cipher, privkey, modulus); _unpack_string(dec_blocks) } pub fn test_thing() { let (pubkey, privkey) = _gen_key(KEY_SIZE / 2); let cipher = encrypt_str(&"Hello world, how are you today?".to_string(), pubkey.clone()); let dec_result = decrypt_str(&cipher, privkey, pubkey.0); println!("Result: {}", dec_result); }
#![feature(llvm_asm)] extern "C" fn foo() {} fn main() { unsafe { llvm_asm!("mov x0, $0" :: "r"(foo) :: "volatile"); } }
// 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. #![allow(non_camel_case_types)] use alloc::string::String; use alloc::collections::btree_map::BTreeMap; use alloc::vec::Vec; fn is_false(b: &bool) -> bool { !b } #[derive(Debug)] pub struct Platform { pub os: String, pub arch: String, } #[derive(Default, PartialEq, Debug)] pub struct Box { pub height: u64, pub width: u64, } fn is_default<T: Default + PartialEq>(b: &T) -> bool { *b == T::default() } #[derive(Debug)] pub struct User { pub uid: u32, pub gid: u32, pub additional_gids: Vec<u32>, pub username: String, } // this converts directly to the correct int #[derive(Debug, Clone, Copy)] pub enum LinuxRlimitType { RLIMIT_CPU, // CPU time in sec RLIMIT_FSIZE, // Maximum filesize RLIMIT_DATA, // max data size RLIMIT_STACK, // max stack size RLIMIT_CORE, // max core file size RLIMIT_RSS, // max resident set size RLIMIT_NPROC, // max number of processes RLIMIT_NOFILE, // max number of open files RLIMIT_MEMLOCK, // max locked-in-memory address space RLIMIT_AS, // address space limit RLIMIT_LOCKS, // maximum file locks held RLIMIT_SIGPENDING, // max number of pending signals RLIMIT_MSGQUEUE, // maximum bytes in POSIX mqueues RLIMIT_NICE, // max nice prio allowed to raise to RLIMIT_RTPRIO, // maximum realtime priority RLIMIT_RTTIME, // timeout for RT tasks in us } #[derive(Debug)] pub struct LinuxRlimit { pub typ: LinuxRlimitType, pub hard: u64, pub soft: u64, } #[derive(Debug, Clone, Copy)] #[repr(u8)] pub enum LinuxCapabilityType { CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH, CAP_FOWNER, CAP_FSETID, CAP_KILL, CAP_SETGID, CAP_SETUID, CAP_SETPCAP, CAP_LINUX_IMMUTABLE, CAP_NET_BIND_SERVICE, CAP_NET_BROADCAST, CAP_NET_ADMIN, CAP_NET_RAW, CAP_IPC_LOCK, CAP_IPC_OWNER, CAP_SYS_MODULE, CAP_SYS_RAWIO, CAP_SYS_CHROOT, CAP_SYS_PTRACE, CAP_SYS_PACCT, CAP_SYS_ADMIN, CAP_SYS_BOOT, CAP_SYS_NICE, CAP_SYS_RESOURCE, CAP_SYS_TIME, CAP_SYS_TTY_CONFIG, CAP_MKNOD, CAP_LEASE, CAP_AUDIT_WRITE, CAP_AUDIT_CONTROL, CAP_SETFCAP, CAP_MAC_OVERRIDE, CAP_MAC_ADMIN, CAP_SYSLOG, CAP_WAKE_ALARM, CAP_BLOCK_SUSPEND, CAP_AUDIT_READ, } #[derive(Debug)] pub struct LinuxCapabilities { pub bounding: Vec<LinuxCapabilityType>, pub effective: Vec<LinuxCapabilityType>, pub inheritable: Vec<LinuxCapabilityType>, pub permitted: Vec<LinuxCapabilityType>, pub ambient: Vec<LinuxCapabilityType>, } #[derive(Debug)] pub struct Process { pub terminal: bool, pub console_size: Box, pub user: User, pub args: Vec<String>, pub env: Vec<String>, pub cwd: String, pub capabilities: Option<LinuxCapabilities>, pub rlimits: Vec<LinuxRlimit>, pub no_new_privileges: bool, pub apparmor_profile: String, pub selinux_label: String, } #[derive(Debug)] pub struct Root { pub path: String, pub readonly: bool, } #[derive(Debug, Clone)] pub struct Mount { pub destination: String, pub typ: String, pub source: String, pub options: Vec<String>, } #[derive(Debug)] pub struct Hook { pub path: String, pub args: Vec<String>, pub env: Vec<String>, pub timeout: Option<i64>, } #[derive(Debug)] pub struct Hooks { pub prestart: Vec<Hook>, pub poststart: Vec<Hook>, pub poststop: Vec<Hook>, } #[derive(Debug, Clone)] pub struct LinuxIDMapping { pub host_id: u32, pub container_id: u32, pub size: u32, } // a is for LinuxDeviceCgroup #[derive(Debug, Clone, Copy)] pub enum LinuxDeviceType { b, c, u, p, a, } impl Default for LinuxDeviceType { fn default() -> LinuxDeviceType { LinuxDeviceType::a } } #[derive(Debug)] pub struct LinuxDeviceCgroup { pub allow: bool, pub typ: LinuxDeviceType, pub major: Option<i64>, pub minor: Option<i64>, pub access: String, } #[derive(Debug)] pub struct LinuxMemory { pub limit: Option<i64>, pub reservation: Option<i64>, pub swap: Option<i64>, pub kernel: Option<i64>, pub kernel_tcp: Option<i64>, pub swappiness: Option<u64>, } #[derive(Debug)] pub struct LinuxCPU { pub shares: Option<u64>, pub quota: Option<i64>, pub period: Option<u64>, pub realtime_runtime: Option<i64>, pub realtime_period: Option<u64>, pub cpus: String, pub mems: String, } #[derive(Debug)] pub struct LinuxPids { pub limit: i64, } #[derive(Debug)] pub struct LinuxWeightDevice { pub major: i64, pub minor: i64, pub weight: Option<u16>, pub leaf_weight: Option<u16>, } #[derive(Debug)] pub struct LinuxThrottleDevice { pub major: i64, pub minor: i64, pub rate: u64, } #[derive(Debug)] pub struct LinuxBlockIO { pub weight: Option<u16>, pub leaf_weight: Option<u16>, pub weight_device: Vec<LinuxWeightDevice>, pub throttle_read_bps_device: Vec<LinuxThrottleDevice>, pub throttle_write_bps_device: Vec<LinuxThrottleDevice>, pub throttle_read_iops_device: Vec<LinuxThrottleDevice>, pub throttle_write_iops_device: Vec<LinuxThrottleDevice>, } #[derive(Debug)] pub struct LinuxHugepageLimit { pub page_size: String, pub limit: i64, } #[derive(Debug)] pub struct LinuxInterfacePriority { pub name: String, pub priority: u32, } #[derive(Debug)] pub struct LinuxNetwork { pub class_id: Option<u32>, pub priorities: Vec<LinuxInterfacePriority>, } #[derive(Default, Debug)] pub struct LinuxResources { pub devices: Vec<LinuxDeviceCgroup>, // NOTE: spec uses a pointer here, so perhaps this should be an Option, but // false == unset so we don't bother. pub disable_oom_killer: bool, // NOTE: spec refers to this as an isize but the range is -1000 to 1000, so // an i32 seems just fine pub oom_score_adj: Option<i32>, pub memory: Option<LinuxMemory>, pub cpu: Option<LinuxCPU>, pub pids: Option<LinuxPids>, pub block_io: Option<LinuxBlockIO>, pub hugepage_limits: Vec<LinuxHugepageLimit>, pub network: Option<LinuxNetwork>, } #[derive(Debug, Clone, Copy)] pub enum LinuxNamespaceType { mount = 0x00020000, /* New mount namespace group */ cgroup = 0x02000000, /* New cgroup namespace */ uts = 0x04000000, /* New utsname namespace */ ipc = 0x08000000, /* New ipc namespace */ user = 0x10000000, /* New user namespace */ pid = 0x20000000, /* New pid namespace */ network = 0x40000000, /* New network namespace */ } #[derive(Debug)] pub struct LinuxNamespace { pub typ: LinuxNamespaceType, pub path: String, } #[derive(Debug)] pub struct LinuxDevice { pub path: String, pub typ: LinuxDeviceType, pub major: u64, pub minor: u64, pub file_mode: Option<u32>, pub uid: Option<u32>, pub gid: Option<u32>, } #[derive(Debug, Clone, Copy)] #[repr(u32)] pub enum LinuxSeccompAction { SCMP_ACT_KILL = 0x00000000, SCMP_ACT_TRAP = 0x00030000, SCMP_ACT_ERRNO = 0x00050001, /* ERRNO + EPERM */ SCMP_ACT_TRACE = 0x7ff00001, /* TRACE + EPERM */ SCMP_ACT_ALLOW = 0x7fff0000, } #[derive(Debug, Clone, Copy)] pub enum Arch { SCMP_ARCH_NATIVE = 0x00000000, SCMP_ARCH_X86 = 0x40000003, SCMP_ARCH_X86_64 = 0xc000003e, SCMP_ARCH_X32 = 0x4000003e, SCMP_ARCH_ARM = 0x40000028, SCMP_ARCH_AARCH64 = 0xc00000b7, SCMP_ARCH_MIPS = 0x00000008, SCMP_ARCH_MIPS64 = 0x80000008, SCMP_ARCH_MIPS64N32 = 0xa0000008, SCMP_ARCH_MIPSEL = 0x40000008, SCMP_ARCH_MIPSEL64 = 0xc0000008, SCMP_ARCH_MIPSEL64N32 = 0xe0000008, SCMP_ARCH_PPC = 0x00000014, SCMP_ARCH_PPC64 = 0x80000015, SCMP_ARCH_PPC64LE = 0xc0000015, SCMP_ARCH_S390 = 0x00000016, SCMP_ARCH_S390X = 0x80000016, } #[derive(Debug, Clone, Copy)] #[repr(u32)] pub enum LinuxSeccompOperator { SCMP_CMP_NE = 1, /* not equal */ SCMP_CMP_LT = 2, /* less than */ SCMP_CMP_LE = 3, /* less than or equal */ SCMP_CMP_EQ = 4, /* equal */ SCMP_CMP_GE = 5, /* greater than or equal */ SCMP_CMP_GT = 6, /* greater than */ SCMP_CMP_MASKED_EQ = 7, /* masked equality */ } #[derive(Debug)] pub struct LinuxSeccompArg { pub index: usize, pub value: u64, pub value_two: u64, pub op: LinuxSeccompOperator, } #[derive(Debug)] pub struct LinuxSyscall { // old version used name pub name: String, pub names: Vec<String>, pub action: LinuxSeccompAction, pub args: Vec<LinuxSeccompArg>, } #[derive(Debug)] pub struct LinuxSeccomp { pub default_action: LinuxSeccompAction, pub architectures: Vec<Arch>, pub syscalls: Vec<LinuxSyscall>, } #[derive(Debug)] pub struct Linux { pub uid_mappings: Vec<LinuxIDMapping>, pub gid_mappings: Vec<LinuxIDMapping>, pub sysctl: BTreeMap<String, String>, pub resources: Option<LinuxResources>, pub cgroups_path: String, pub namespaces: Vec<LinuxNamespace>, pub devices: Vec<LinuxDevice>, pub seccomp: Option<LinuxSeccomp>, pub rootfs_propagation: String, pub masked_paths: Vec<String>, pub readonly_paths: Vec<String>, pub mount_label: String, } // NOTE: Solaris and Windows are ignored for the moment pub type Solaris = Value; pub type Windows = Value; pub type Value = i32; #[derive(Debug)] pub struct Spec { pub version: String, // NOTE: Platform was removed, but keeping it as an option // to support older docker versions pub platform: Option<Platform>, //pub process: Process, pub root: Root, pub hostname: String, pub mounts: Vec<Mount>, pub hooks: Option<Hooks>, pub annotations: BTreeMap<String, String>, pub linux: Option<Linux>, pub solaris: Option<Solaris>, pub windows: Option<Windows>, } #[derive(Debug)] pub struct State { pub version: String, pub id: String, pub status: String, pub pid: i32, pub bundle: String, pub annotations: BTreeMap<String, String>, }
/*! Keys相关的命令定义、解析 所有涉及到的命令参考[Redis Command Reference] [Redis Command Reference]: https://redis.io/commands#generic */ use std::slice::Iter; use crate::cmd::keys::ORDER::{ASC, DESC}; #[derive(Debug)] pub struct DEL<'a> { pub keys: Vec<&'a Vec<u8>>, } pub(crate) fn parse_del(iter: Iter<Vec<u8>>) -> DEL { let mut keys = Vec::new(); for next_key in iter { keys.push(next_key); } DEL { keys } } #[derive(Debug)] pub struct PERSIST<'a> { pub key: &'a [u8], } pub(crate) fn parse_persist(mut iter: Iter<Vec<u8>>) -> PERSIST { let key = iter.next().unwrap(); PERSIST { key } } #[derive(Debug)] pub struct EXPIRE<'a> { pub key: &'a [u8], pub seconds: &'a [u8], } pub(crate) fn parse_expire(mut iter: Iter<Vec<u8>>) -> EXPIRE { let key = iter.next().unwrap(); let seconds = iter.next().unwrap(); EXPIRE { key, seconds } } #[derive(Debug)] pub struct PEXPIRE<'a> { pub key: &'a [u8], pub milliseconds: &'a [u8], } pub(crate) fn parse_pexpire(mut iter: Iter<Vec<u8>>) -> PEXPIRE { let key = iter.next().unwrap(); let milliseconds = iter.next().unwrap(); PEXPIRE { key, milliseconds } } #[derive(Debug)] pub struct EXPIREAT<'a> { pub key: &'a [u8], pub timestamp: &'a [u8], } pub(crate) fn parse_expireat(mut iter: Iter<Vec<u8>>) -> EXPIREAT { let key = iter.next().unwrap(); let timestamp = iter.next().unwrap(); EXPIREAT { key, timestamp } } #[derive(Debug)] pub struct PEXPIREAT<'a> { pub key: &'a [u8], pub mill_timestamp: &'a [u8], } pub(crate) fn parse_pexpireat(mut iter: Iter<Vec<u8>>) -> PEXPIREAT { let key = iter.next().unwrap(); let mill_timestamp = iter.next().unwrap(); PEXPIREAT { key, mill_timestamp } } #[derive(Debug)] pub struct MOVE<'a> { pub key: &'a [u8], pub db: &'a [u8], } pub(crate) fn parse_move(mut iter: Iter<Vec<u8>>) -> MOVE { let key = iter.next().unwrap(); let db = iter.next().unwrap(); MOVE { key, db } } #[derive(Debug)] pub struct RENAME<'a> { pub key: &'a [u8], pub new_key: &'a [u8], } pub(crate) fn parse_rename(mut iter: Iter<Vec<u8>>) -> RENAME { let key = iter.next().unwrap(); let new_key = iter.next().unwrap(); RENAME { key, new_key } } #[derive(Debug)] pub struct RENAMENX<'a> { pub key: &'a [u8], pub new_key: &'a [u8], } pub(crate) fn parse_renamenx(mut iter: Iter<Vec<u8>>) -> RENAMENX { let key = iter.next().unwrap(); let new_key = iter.next().unwrap(); RENAMENX { key, new_key } } #[derive(Debug)] pub struct RESTORE<'a> { pub key: &'a [u8], pub ttl: &'a [u8], pub value: &'a [u8], pub replace: Option<bool>, pub abs_ttl: Option<bool>, pub idle_time: Option<&'a [u8]>, pub freq: Option<&'a [u8]>, } pub(crate) fn parse_restore(mut iter: Iter<Vec<u8>>) -> RESTORE { let key = iter.next().unwrap(); let ttl = iter.next().unwrap(); let value = iter.next().unwrap(); let mut replace = None; let mut abs_ttl = None; let mut idle_time = None; let mut freq = None; while let Some(next_arg) = iter.next() { let arg = String::from_utf8_lossy(next_arg).to_uppercase(); if &arg == "REPLACE" { replace = Some(true); } else if &arg == "ABSTTL" { abs_ttl = Some(true); } else if &arg == "IDLETIME" { idle_time = Some(iter.next().unwrap().as_slice()); } else if &arg == "FREQ" { freq = Some(iter.next().unwrap().as_slice()); } } RESTORE { key, ttl, value, replace, abs_ttl, idle_time, freq, } } #[derive(Debug)] pub struct SORT<'a> { pub key: &'a [u8], pub by_pattern: Option<&'a [u8]>, pub limit: Option<LIMIT<'a>>, pub get_patterns: Option<Vec<&'a [u8]>>, pub order: Option<ORDER>, pub alpha: Option<bool>, pub destination: Option<&'a [u8]>, } #[derive(Debug)] pub struct LIMIT<'a> { pub offset: &'a [u8], pub count: &'a [u8], } #[derive(Debug)] pub enum ORDER { ASC, DESC, } pub(crate) fn parse_sort(mut iter: Iter<Vec<u8>>) -> SORT { let key = iter.next().unwrap(); let mut order = None; let mut alpha = None; let mut limit = None; let mut destination = None; let mut by_pattern = None; let mut patterns = Vec::new(); let mut get_patterns = None; while let Some(next_arg) = iter.next() { let arg_upper = String::from_utf8_lossy(next_arg).to_uppercase(); if &arg_upper == "ASC" { order = Some(ASC); } else if &arg_upper == "DESC" { order = Some(DESC); } else if &arg_upper == "ALPHA" { alpha = Some(true); } else if &arg_upper == "LIMIT" { let offset = iter.next().unwrap(); let count = iter.next().unwrap(); limit = Some(LIMIT { offset, count }); } else if &arg_upper == "STORE" { let store = iter.next().unwrap(); destination = Some(store.as_slice()); } else if &arg_upper == "BY" { let pattern = iter.next().unwrap(); by_pattern = Some(pattern.as_slice()); } else if &arg_upper == "GET" { let next_pattern = iter.next().unwrap(); patterns.push(next_pattern.as_slice()); } } if !patterns.is_empty() { get_patterns = Some(patterns); } SORT { key, by_pattern, limit, get_patterns, order, alpha, destination, } } #[derive(Debug)] pub struct UNLINK<'a> { pub keys: Vec<&'a [u8]>, } pub(crate) fn parse_unlink(mut iter: Iter<Vec<u8>>) -> UNLINK { let mut keys = Vec::new(); while let Some(next_key) = iter.next() { keys.push(next_key.as_slice()); } UNLINK { keys } }
#[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::console::_print(format_args!($($arg)*))); } #[macro_export] macro_rules! println { () => (print!("\n")); ($fmt:expr) => (print!(concat!("[Info] ", $fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => (print!(concat!("[Info] ", $fmt, "\n"), $($arg)*)); } #[macro_export] macro_rules! scanf { ( $string:expr, $sep:expr, $($x:ty),+ ) => {{ let mut iter = $string.split($sep); ($(iter.next().and_then(|word| word.parse::<$x>().ok()),)*) }} }
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ /// Region Providers pub mod region; /// Credential Providers pub mod credentials;
use game::factory::produce_refrigerators as a; use game::factory::produce_washing_machine as b; mod mod_a { #[derive(Debug)] pub struct A{ pub number: i32, name: String } impl A { pub fn new_a() -> A{ A{ number:1, name:String::from("A"), } } pub fn print_a(&self) { println!("number: {}, name: {}", self.number, self.name); } } pub mod mod_b{ pub fn print_b() { println!("b"); } pub mod mod_c{ pub fn print_c() { super::print_b(); println!("c"); } } } } fn main() { a::produce_re(); b::produce_washing_machine(); let a = mod_a::A::new_a(); a.print_a(); use mod_a::A; let b = A::new_a(); b.print_a(); let number = b.number; println!("{}", number); mod_a::mod_b::mod_c::print_c(); }
// Copyright 2018 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. #![deny(warnings)] #![feature(async_await, await_macro, futures_api)] use { failure::{format_err, Error, ResultExt}, fidl::endpoints::{RequestStream, ServiceMarker}, fidl_fidl_test_compatibility::{ EchoEvent, EchoMarker, EchoProxy, EchoRequest, EchoRequestStream, }, fuchsia_app::{ client::Launcher, client::App, server::ServicesServer, }, fuchsia_async as fasync, futures::TryStreamExt, }; fn launch_and_connect_to_echo(launcher: &Launcher, url: String) -> Result<(EchoProxy, App), Error> { let app = launcher.launch(url, None)?; let echo = app.connect_to_service(EchoMarker)?; Ok((echo, app)) } async fn echo_server(chan: fasync::Channel, launcher: &Launcher) -> Result<(), Error> { const CONCURRENT_REQ_LIMIT: Option<usize> = None; let handler = move |request| Box::pin(async move { match request { EchoRequest::EchoStruct { mut value, forward_to_server, responder } => { if !forward_to_server.is_empty() { let (echo, app) = launch_and_connect_to_echo(launcher, forward_to_server) .context("Error connecting to proxy")?; value = await!(echo.echo_struct(&mut value, "")) .context("Error calling echo_struct on proxy")?; drop(app); } responder.send(&mut value) .context("Error responding")?; } EchoRequest::EchoStructNoRetVal { mut value, forward_to_server, control_handle } => { if !forward_to_server.is_empty() { let (echo, app) = launch_and_connect_to_echo(launcher, forward_to_server) .context("Error connecting to proxy")?; echo.echo_struct_no_ret_val(&mut value, "") .context("Error sending echo_struct_no_ret_val to proxy")?; let mut event_stream = echo.take_event_stream(); let EchoEvent::EchoEvent { value: response_val } = await!(event_stream.try_next()) .context("Error getting event response from proxy")? .ok_or_else(|| format_err!("Proxy sent no events"))?; value = response_val; drop(app); } control_handle.send_echo_event(&mut value) .context("Error responding with event")?; } } Ok(()) }); let handle_requests_fut = EchoRequestStream::from_channel(chan) .err_into() // change error type from fidl::Error to failure::Error .try_for_each_concurrent(CONCURRENT_REQ_LIMIT, handler); await!(handle_requests_fut) } fn main() -> Result<(), Error> { let mut executor = fasync::Executor::new().context("Error creating executor")?; let launcher = Launcher::new().context("Error connecting to application launcher")?; let fut = ServicesServer::new() .add_service((EchoMarker::NAME, move |chan| { let launcher = launcher.clone(); fasync::spawn(async move { if let Err(e) = await!(echo_server(chan, &launcher)) { eprintln!("Closing echo server {:?}", e); } }) })) .start() .context("Error starting compatibility echo ServicesServer")?; executor.run_singlethreaded(fut).context("failed to execute echo future")?; Ok(()) }
use std::collections::BTreeSet; use std::sync::Arc; use druid::kurbo::{BezPath, Point, Rect, Shape, Size, Vec2}; use druid::{Data, Lens}; use norad::glyph::Outline; use norad::{Glyph, GlyphName}; use crate::component::Component; use crate::data::Workspace; use crate::design_space::{DPoint, DVec2, ViewPort}; use crate::guides::Guide; use crate::path::{Path, Segment}; use crate::point::{EntityId, PathPoint}; use crate::quadrant::Quadrant; use crate::selection::Selection; /// Minimum distance in screen units that a click must occur to be considered /// on a point? //TODO: this doesn't feel very robust; items themselves should have hitzones? pub const MIN_CLICK_DISTANCE: f64 = 10.0; pub const SEGMENT_CLICK_DISTANCE: f64 = 6.0; /// Amount of bias penalizing on-curve points; we want to break ties in favor /// of off-curve. pub const ON_CURVE_PENALTY: f64 = MIN_CLICK_DISTANCE / 2.0; /// A unique identifier for a session. A session keeps the same identifier /// even if the name of the glyph changes. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub struct SessionId(usize); impl SessionId { pub(crate) fn next() -> SessionId { use std::sync::atomic::{AtomicUsize, Ordering}; static NEXT_ID: AtomicUsize = AtomicUsize::new(0); SessionId(NEXT_ID.fetch_add(1, Ordering::Relaxed)) } } /// The editing state of a particular glyph. #[derive(Debug, Clone, Data)] pub struct EditSession { #[data(ignore)] pub id: SessionId, pub name: GlyphName, pub glyph: Arc<Glyph>, pub paths: Arc<Vec<Path>>, pub selection: Selection, pub components: Arc<Vec<Component>>, pub guides: Arc<Vec<Guide>>, pub viewport: ViewPort, work_bounds: Rect, quadrant: Quadrant, } /// A type that is only created by a lens, for our coordinate editing panel #[derive(Debug, Clone, Copy, Data, Lens)] pub struct CoordinateSelection { /// the number of selected points pub count: usize, /// the bounding box of the selection pub frame: Rect, pub quadrant: Quadrant, } impl EditSession { /// a lens to return info on the current selection #[allow(non_upper_case_globals)] pub const selected_coord: lenses::CoordSelection = lenses::CoordSelection; pub fn new(name: &GlyphName, glyphs: &Workspace) -> Self { let name = name.to_owned(); let glyph = glyphs.font.ufo.get_glyph(&name).unwrap().to_owned(); let paths: Vec<Path> = glyph .outline .as_ref() .map(|ol| ol.contours.iter().map(Path::from_norad).collect()) .unwrap_or_default(); let components = glyph .outline .as_ref() .map(|ol| ol.components.iter().map(Component::from_norad).collect()) .unwrap_or_default(); let guides = glyph .guidelines .as_ref() .map(|guides| guides.iter().map(Guide::from_norad).collect()) .unwrap_or_default(); //FIXME: this is never updated, and shouldn't be relied on let work_bounds = glyphs .get_bezier(&name) .map(|b| b.bounding_box()) .unwrap_or_default(); EditSession { id: SessionId::next(), name, glyph, paths: Arc::new(paths), selection: Selection::new(), components: Arc::new(components), guides: Arc::new(guides), viewport: ViewPort::default(), quadrant: Quadrant::Center, work_bounds, } } /// Construct a bezier of the paths in this glyph, ignoring components. pub fn to_bezier(&self) -> BezPath { let mut bez = BezPath::new(); for path in self.paths.iter() { path.append_to_bezier(&mut bez); } bez } pub fn rebuild_glyph(&mut self) { let new_glyph = self.to_norad_glyph(); *Arc::make_mut(&mut self.glyph) = new_glyph; } /// called if metadata changes elsewhere, such as in the main view. pub fn update_glyph_metadata(&mut self, changed: &Arc<Glyph>) { let glyph = Arc::make_mut(&mut self.glyph); glyph.advance = changed.advance.clone(); } pub fn rename(&mut self, name: GlyphName) { self.name = name.clone(); let glyph = Arc::make_mut(&mut self.glyph); glyph.codepoints = crate::glyph_names::codepoints_for_glyph(&name); glyph.name = name; } /// Returns the current layout bounds of the 'work', that is, all the things /// that are 'part of the glyph'. pub fn work_bounds(&self) -> Rect { self.work_bounds } pub fn paths_mut(&mut self) -> &mut Vec<Path> { Arc::make_mut(&mut self.paths) } pub fn components_mut(&mut self) -> &mut Vec<Component> { Arc::make_mut(&mut self.components) } pub fn guides_mut(&mut self) -> &mut Vec<Guide> { Arc::make_mut(&mut self.guides) } pub fn iter_points(&self) -> impl Iterator<Item = &PathPoint> { self.paths.iter().flat_map(|p| p.points().iter()) } pub(crate) fn paths_for_selection(&self) -> Vec<Path> { let mut result = Vec::new(); for paths in self .paths .iter() .map(|p| p.paths_for_selection(&self.selection)) { result.extend(paths); } result } // Replaced by hit test methods. /* /// For hit testing; iterates 'clickable items' (right now just points /// and guides) near a given point. pub fn iter_items_near_point<'a>( &'a self, point: Point, max_dist: Option<f64>, ) -> impl Iterator<Item = EntityId> + 'a { let max_dist = max_dist.unwrap_or(MIN_CLICK_DISTANCE); self.paths .iter() .flat_map(|p| p.points().iter()) .filter(move |p| p.screen_dist(self.viewport, point) <= max_dist) .map(|p| p.id) .chain( self.guides .iter() .filter(move |g| g.screen_dist(self.viewport, point) <= max_dist) .map(|g| g.id), ) } */ /// Find the best hit, considering all items. pub fn hit_test_all(&self, point: Point, max_dist: Option<f64>) -> Option<EntityId> { if let Some(hit) = self.hit_test_filtered(point, max_dist, |_| true) { return Some(hit); } let max_dist = max_dist.unwrap_or(MIN_CLICK_DISTANCE); let mut best = None; for g in &*self.guides { let dist = g.screen_dist(self.viewport, point); if dist < max_dist && best.map(|(d, _id)| dist < d).unwrap_or(true) { best = Some((dist, g.id)) } } best.map(|(_dist, id)| id) } /// Hit test a point against points. /// /// This method finds the closest point, but applies a penalty to prioritize /// off-curve points. /// /// A more sophisticated approach would be to reward on-curve points that are /// not already selected, but penalize them if they are selected. That would /// require a way to plumb in selection info. pub fn hit_test_filtered( &self, point: Point, max_dist: Option<f64>, mut f: impl FnMut(&PathPoint) -> bool, ) -> Option<EntityId> { let max_dist = max_dist.unwrap_or(MIN_CLICK_DISTANCE); let mut best = None; for p in self.iter_points() { if f(p) { let dist = p.screen_dist(self.viewport, point); let score = dist + if p.is_on_curve() { ON_CURVE_PENALTY } else { 0.0 }; if dist < max_dist && best.map(|(s, _id)| score < s).unwrap_or(true) { best = Some((score, p.id)) } } } best.map(|(_score, id)| id) } /// Hit test a point against the path segments. pub fn hit_test_segments(&self, point: Point, max_dist: Option<f64>) -> Option<(Segment, f64)> { let max_dist = max_dist.unwrap_or(MIN_CLICK_DISTANCE); let dpt = self.viewport.from_screen(point); let mut best = None; for path in &*self.paths { for seg in path.iter_segments() { let (t, d2) = seg.nearest(dpt); if best.as_ref().map(|(_seg, _t, d)| d2 < *d).unwrap_or(true) { best = Some((seg, t, d2)); } } } if let Some((seg, t, d2)) = best { if d2 * self.viewport.zoom.powi(2) < max_dist.powi(2) { return Some((seg, t)); } } None } /// Return the index of the path that is currently drawing. To be currently /// drawing, there must be a single currently selected point. fn active_path_idx(&self) -> Option<usize> { if self.selection.len() == 1 { let active = self.selection.iter().next().unwrap(); self.paths.iter().position(|p| p.contains(active)) } else { None } } pub fn active_path_mut(&mut self) -> Option<&mut Path> { match self.active_path_idx() { Some(idx) => self.paths_mut().get_mut(idx), None => None, } } pub fn active_path(&self) -> Option<&Path> { match self.active_path_idx() { Some(idx) => self.paths.get(idx), None => None, } } pub fn path_point_for_id(&self, id: EntityId) -> Option<PathPoint> { self.path_for_point(id) .and_then(|path| path.path_point_for_id(id)) } pub fn path_for_point(&self, point: EntityId) -> Option<&Path> { self.path_idx_for_point(point) .and_then(|idx| self.paths.get(idx)) } pub fn path_for_point_mut(&mut self, point: EntityId) -> Option<&mut Path> { let idx = self.path_idx_for_point(point)?; self.paths_mut().get_mut(idx) } fn path_idx_for_point(&self, point: EntityId) -> Option<usize> { self.paths.iter().position(|p| p.contains(&point)) } pub(crate) fn add_path(&mut self, path: Path) { let point = path.points()[0].id; self.paths_mut().push(path); self.selection.select_one(point); } pub fn paste_paths(&mut self, paths: Vec<Path>) { self.selection.clear(); self.selection .extend(paths.iter().flat_map(|p| p.points().iter().map(|pt| pt.id))); self.paths_mut().extend(paths); } pub fn toggle_point_type(&mut self, id: EntityId) { if let Some(path) = self.path_for_point_mut(id) { path.toggle_point_type(id) } } /// if a guide his horizontal or vertical, toggle between the two. pub fn toggle_guide(&mut self, id: EntityId, pos: Point) { let pos = self.viewport.from_screen(pos); if let Some(guide) = self.guides_mut().iter_mut().find(|g| g.id == id) { guide.toggle_vertical_horiz(pos); } } pub fn delete_selection(&mut self) { let to_delete = self.selection.per_path_selection(); self.selection.clear(); // if only deleting points from a single path, we will select a point // in that path afterwards. let set_sel = to_delete.path_len() == 1; for path_points in to_delete.iter() { if let Some(path) = self.path_for_point_mut(path_points[0]) { if let Some(new_sel) = path.delete_points(path_points) { if set_sel { self.selection.select_one(new_sel); } } } else if path_points[0].is_guide() { self.guides_mut().retain(|g| !path_points.contains(&g.id)); } } self.paths_mut().retain(|p| !p.points().is_empty()); } /// Select all points. //NOTE: should this select other things too? Which ones? pub fn select_all(&mut self) { self.selection.clear(); self.selection = self.iter_points().map(|p| p.id).collect(); } /// returns a rect representing the containing rect of the current selection /// /// Will return Rect::ZERO if nothing is selected. pub(crate) fn selection_dpoint_bbox(&self) -> Rect { let mut iter = self .selection .iter() .flat_map(|id| self.path_point_for_id(*id).map(|pt| pt.point.to_raw())); let first_point = iter.next().unwrap_or_default(); let bbox = Rect::ZERO.with_origin(first_point); iter.fold(bbox, |bb, pt| bb.union_pt(pt)) } /// If the current selection is a single point, select the next point /// on that path. pub fn select_next(&mut self) { if self.selection.len() != 1 { return; } let id = self.selection.iter().next().copied().unwrap(); let id = self .path_for_point(id) .and_then(|path| path.next_point(id).map(|pp| pp.id)) .unwrap_or(id); self.selection.select_one(id); } /// If the current selection is a single point, select the previous point /// on that path. pub fn select_prev(&mut self) { if self.selection.len() != 1 { return; } let id = self.selection.iter().next().copied().unwrap(); let id = self .path_for_point(id) .and_then(|path| path.prev_point(id).map(|pp| pp.id)) .unwrap_or(id); self.selection.select_one(id); } pub fn select_path(&mut self, id: EntityId, toggle: bool) -> bool { let path = match self.paths.iter().find(|path| path.id() == id) { Some(path) => path, None => return false, }; for point in path.points() { if !self.selection.insert(point.id) && toggle { self.selection.remove(&point.id); } } true } pub(crate) fn nudge_selection(&mut self, nudge: DVec2) { if self.selection.is_empty() { return; } let to_nudge = self.selection.per_path_selection(); for path_points in to_nudge.iter() { if let Some(path) = self.path_for_point_mut(path_points[0]) { path.nudge_points(path_points, nudge); } else if path_points[0].is_guide() { for id in path_points { if let Some(guide) = self.guides_mut().iter_mut().find(|g| g.id == *id) { guide.nudge(nudge); } } } } } pub(crate) fn nudge_everything(&mut self, nudge: DVec2) { for path in self.paths_mut() { path.nudge_all_points(nudge); } for component in self.components_mut() { component.nudge(nudge); } } pub(crate) fn adjust_sidebearing(&mut self, delta: f64, is_left: bool) { let glyph = Arc::make_mut(&mut self.glyph); if let Some(advance) = glyph.advance.as_mut() { // clamp the delta; we can't have an advance width < 0. let delta = if (advance.width + delta as f32) < 0.0 { -advance.width as f64 } else { delta }; advance.width += delta as f32; if is_left { self.nudge_everything(DVec2::from_raw((delta, 0.0))); } } } pub(crate) fn scale_selection(&mut self, scale: Vec2, anchor: DPoint) { assert!(scale.x.is_finite() && scale.y.is_finite()); if !self.selection.is_empty() { let sel = self.selection.per_path_selection(); for path_points in sel.iter() { if let Some(path) = self.path_for_point_mut(path_points[0]) { path.scale_points(path_points, scale, anchor); } } } } pub(crate) fn align_selection(&mut self) { let bbox = self.selection_dpoint_bbox(); // TODO: is_empty() would be cleaner but hasn't landed yet if bbox.area() == 0.0 { return; } let (val, set_x) = if bbox.width() < bbox.height() { (0.5 * (bbox.x0 + bbox.x1), true) } else { (0.5 * (bbox.y0 + bbox.y1), false) }; let val = val.round(); // make borrow checker happy; we could state-split the paths instead, but meh let ids: Vec<EntityId> = self.selection.iter().copied().collect(); for id in ids { if let Some(path) = self.path_for_point_mut(id) { path.align_point(id, val, set_x); } } } pub(crate) fn reverse_contours(&mut self) { let mut path_ixs = BTreeSet::new(); for entity in self.selection.iter() { if let Some(path_ix) = self.path_idx_for_point(*entity) { path_ixs.insert(path_ix); } } if path_ixs.is_empty() { path_ixs.extend(0..self.paths.len()); } let paths = self.paths_mut(); for ix in path_ixs { paths[ix].reverse_contour(); } } pub(crate) fn add_guide(&mut self, point: Point) { // if one or two points are selected, use them. else use argument point. let guide = match self.selection.len() { 1 => { let id = *self.selection.iter().next().unwrap(); if !id.is_guide() { let p = self.path_point_for_id(id).map(|pp| pp.point).unwrap(); Some(Guide::horiz(p)) } else { None } } 2 => { let mut iter = self.selection.iter().cloned(); let id1 = iter.next().unwrap(); let id2 = iter.next().unwrap(); if !id1.is_guide() && !id2.is_guide() { let p1 = self.path_point_for_id(id1).map(|pp| pp.point).unwrap(); let p2 = self.path_point_for_id(id2).map(|pp| pp.point).unwrap(); Some(Guide::angle(p1, p2)) } else { None } } _ => None, }; let guide = guide.unwrap_or_else(|| Guide::horiz(DPoint::from_screen(point, self.viewport))); self.selection.select_one(guide.id); self.guides_mut().push(guide); } /// Convert the current session back into a norad `Glyph`, for saving. pub fn to_norad_glyph(&self) -> Glyph { let mut glyph = Glyph::new_named(""); glyph.name = self.name.clone(); glyph.advance = self.glyph.advance.clone(); glyph.codepoints = self.glyph.codepoints.clone(); let contours: Vec<_> = self.paths.iter().map(Path::to_norad).collect(); let components: Vec<_> = self.components.iter().map(Component::to_norad).collect(); if !contours.is_empty() || !components.is_empty() { glyph.outline = Some(Outline { components, contours, }); } let guidelines: Vec<_> = self.guides.iter().map(Guide::to_norad).collect(); if !guidelines.is_empty() { glyph.guidelines = Some(guidelines); } glyph } } impl CoordinateSelection { /// a lens to return the point representation of the current selected coord(s) #[allow(non_upper_case_globals)] pub const quadrant_coord: lenses::QuadrantCoord = lenses::QuadrantCoord; /// a lens to return the bbox of the current selection #[allow(non_upper_case_globals)] pub const quadrant_bbox: lenses::QuadrantBbox = lenses::QuadrantBbox; } pub mod lenses { use super::*; use druid::Lens; pub struct CoordSelection; impl Lens<EditSession, CoordinateSelection> for CoordSelection { fn with<V, F: FnOnce(&CoordinateSelection) -> V>(&self, data: &EditSession, f: F) -> V { let count = data.selection.len(); let frame = data.selection_dpoint_bbox(); let quadrant = data.quadrant; f(&CoordinateSelection { count, frame, quadrant, }) } fn with_mut<V, F: FnOnce(&mut CoordinateSelection) -> V>( &self, data: &mut EditSession, f: F, ) -> V { let count = data.selection.len(); let frame = data.selection_dpoint_bbox(); let quadrant = data.quadrant; let mut sel = CoordinateSelection { count, frame, quadrant, }; let r = f(&mut sel); data.quadrant = sel.quadrant; r } } pub struct QuadrantCoord; impl Lens<CoordinateSelection, Point> for QuadrantCoord { fn with<V, F: FnOnce(&Point) -> V>(&self, data: &CoordinateSelection, f: F) -> V { let point = data.quadrant.point_in_dspace_rect(data.frame); f(&point) } fn with_mut<V, F: FnOnce(&mut Point) -> V>( &self, data: &mut CoordinateSelection, f: F, ) -> V { let point = data.quadrant.point_in_dspace_rect(data.frame); let mut point2 = point; let r = f(&mut point2); if point != point2 { let delta = point2 - point; data.frame = data.frame.with_origin(data.frame.origin() + delta); } r } } pub struct QuadrantBbox; impl Lens<CoordinateSelection, Size> for QuadrantBbox { fn with<V, F: FnOnce(&Size) -> V>(&self, data: &CoordinateSelection, f: F) -> V { f(&data.frame.size()) } fn with_mut<V, F: FnOnce(&mut Size) -> V>( &self, data: &mut CoordinateSelection, f: F, ) -> V { let size = data.frame.size(); let mut size2 = size; let r = f(&mut size2); if size != size2 { data.frame = data.frame.with_size(size2); } r } } }
use serde::{ Deserialize, Serialize, }; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct QaStatus { has_issue: bool, possible_contamination: bool, incomplete_sequence: bool, missing_rfam_match: bool, }
/// Compute a + b + carry, returning the result and the new carry over. #[inline(always)] pub const fn adc(a: u64, b: u64, carry: u64) -> (u64, u64) { let ret = (a as u128) + (b as u128) + (carry as u128); (ret as u64, (ret >> 64) as u64) } /// Compute a - (b + borrow), returning the result and the new borrow. #[inline(always)] pub const fn sbb(a: u64, b: u64, borrow: u64) -> (u64, u64) { let ret = (a as u128).wrapping_sub((b as u128) + ((borrow >> 63) as u128)); (ret as u64, (ret >> 64) as u64) } /// Compute a + (b * c) + carry, returning the result and the new carry over. #[inline(always)] pub const fn mac(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) { let ret = (a as u128) + ((b as u128) * (c as u128)) + (carry as u128); (ret as u64, (ret >> 64) as u64) } macro_rules! impl_add_binop_specify_output { ($lhs:ident, $rhs:ident, $output:ident) => { impl<'b> Add<&'b $rhs> for $lhs { type Output = $output; #[inline] fn add(self, rhs: &'b $rhs) -> $output { &self + rhs } } impl<'a> Add<$rhs> for &'a $lhs { type Output = $output; #[inline] fn add(self, rhs: $rhs) -> $output { self + &rhs } } impl Add<$rhs> for $lhs { type Output = $output; #[inline] fn add(self, rhs: $rhs) -> $output { &self + &rhs } } }; } macro_rules! impl_sub_binop_specify_output { ($lhs:ident, $rhs:ident, $output:ident) => { impl<'b> Sub<&'b $rhs> for $lhs { type Output = $output; #[inline] fn sub(self, rhs: &'b $rhs) -> $output { &self - rhs } } impl<'a> Sub<$rhs> for &'a $lhs { type Output = $output; #[inline] fn sub(self, rhs: $rhs) -> $output { self - &rhs } } impl Sub<$rhs> for $lhs { type Output = $output; #[inline] fn sub(self, rhs: $rhs) -> $output { &self - &rhs } } }; } macro_rules! impl_binops_additive_specify_output { ($lhs:ident, $rhs:ident, $output:ident) => { impl_add_binop_specify_output!($lhs, $rhs, $output); impl_sub_binop_specify_output!($lhs, $rhs, $output); }; } macro_rules! impl_binops_multiplicative_mixed { ($lhs:ident, $rhs:ident, $output:ident) => { impl<'b> Mul<&'b $rhs> for $lhs { type Output = $output; #[inline] fn mul(self, rhs: &'b $rhs) -> $output { &self * rhs } } impl<'a> Mul<$rhs> for &'a $lhs { type Output = $output; #[inline] fn mul(self, rhs: $rhs) -> $output { self * &rhs } } impl Mul<$rhs> for $lhs { type Output = $output; #[inline] fn mul(self, rhs: $rhs) -> $output { &self * &rhs } } }; } macro_rules! impl_binops_additive { ($lhs:ident, $rhs:ident) => { impl_binops_additive_specify_output!($lhs, $rhs, $lhs); impl SubAssign<$rhs> for $lhs { #[inline] fn sub_assign(&mut self, rhs: $rhs) { *self = &*self - &rhs; } } impl AddAssign<$rhs> for $lhs { #[inline] fn add_assign(&mut self, rhs: $rhs) { *self = &*self + &rhs; } } impl<'b> SubAssign<&'b $rhs> for $lhs { #[inline] fn sub_assign(&mut self, rhs: &'b $rhs) { *self = &*self - rhs; } } impl<'b> AddAssign<&'b $rhs> for $lhs { #[inline] fn add_assign(&mut self, rhs: &'b $rhs) { *self = &*self + rhs; } } }; } macro_rules! impl_binops_multiplicative { ($lhs:ident, $rhs:ident) => { impl_binops_multiplicative_mixed!($lhs, $rhs, $lhs); impl MulAssign<$rhs> for $lhs { #[inline] fn mul_assign(&mut self, rhs: $rhs) { *self = &*self * &rhs; } } impl<'b> MulAssign<&'b $rhs> for $lhs { #[inline] fn mul_assign(&mut self, rhs: &'b $rhs) { *self = &*self * rhs; } } }; } macro_rules! impl_pippenger_sum_of_products { () => { /// Use pippenger multi-exponentiation method to compute /// the sum of multiple points raise to scalars. /// This uses a fixed window of 4 to be constant time #[cfg(feature = "alloc")] pub fn sum_of_products(points: &[Self], scalars: &[Scalar]) -> Self { use alloc::vec::Vec; let ss: Vec<Scalar> = scalars .iter() .map(|s| Scalar::montgomery_reduce(s.0[0], s.0[1], s.0[2], s.0[3], 0, 0, 0, 0)) .collect(); Self::sum_of_products_pippenger(points, ss.as_slice()) } /// Use pippenger multi-exponentiation method to compute /// the sum of multiple points raise to scalars. /// This uses a fixed window of 4 to be constant time /// The scalars are used as place holders for temporary computations pub fn sum_of_products_in_place(points: &[Self], scalars: &mut [Scalar]) -> Self { // Scalars are in montgomery form, hack them in place to be temporarily // in canonical form, do the computation, then switch them back for i in 0..scalars.len() { // Turn into canonical form by computing (a.R) / R = a scalars[i] = Scalar::montgomery_reduce( scalars[i].0[0], scalars[i].0[1], scalars[i].0[2], scalars[i].0[3], 0, 0, 0, 0, ); } let res = Self::sum_of_products_pippenger(points, scalars); for i in 0..scalars.len() { scalars[i] = Scalar::from_raw(scalars[i].0); } res } /// Compute pippenger multi-exponentiation. /// Pippenger relies on scalars in canonical form /// This uses a fixed window of 4 to be constant time fn sum_of_products_pippenger(points: &[Self], scalars: &[Scalar]) -> Self { const WINDOW: usize = 4; const NUM_BUCKETS: usize = 1 << WINDOW; const EDGE: usize = WINDOW - 1; const MASK: u64 = (NUM_BUCKETS - 1) as u64; let num_components = core::cmp::min(points.len(), scalars.len()); let mut buckets = [Self::identity(); NUM_BUCKETS]; let mut res = Self::identity(); let mut num_doubles = 0; let mut bit_sequence_index = 255usize; // point to top bit we need to process loop { for _ in 0..num_doubles { res = res.double(); } let mut max_bucket = 0; let word_index = bit_sequence_index >> 6; // divide by 64 to find word_index let bit_index = bit_sequence_index & 63; // mod by 64 to find bit_index if bit_index < EDGE { // we are on the edge of a word; have to look at the previous word, if it exists if word_index == 0 { // there is no word before let smaller_mask = ((1 << (bit_index + 1)) - 1) as u64; for i in 0..num_components { let bucket_index: usize = (scalars[i].0[word_index] & smaller_mask) as usize; if bucket_index > 0 { buckets[bucket_index] += points[i]; if bucket_index > max_bucket { max_bucket = bucket_index; } } } } else { // there is a word before let high_order_mask = ((1 << (bit_index + 1)) - 1) as u64; let high_order_shift = EDGE - bit_index; let low_order_mask = ((1 << high_order_shift) - 1) as u64; let low_order_shift = 64 - high_order_shift; let prev_word_index = word_index - 1; for i in 0..num_components { let mut bucket_index = ((scalars[i].0[word_index] & high_order_mask) << high_order_shift) as usize; bucket_index |= ((scalars[i].0[prev_word_index] >> low_order_shift) & low_order_mask) as usize; if bucket_index > 0 { buckets[bucket_index] += points[i]; if bucket_index > max_bucket { max_bucket = bucket_index; } } } } } else { let shift = bit_index - EDGE; for i in 0..num_components { let bucket_index: usize = ((scalars[i].0[word_index] >> shift) & MASK) as usize; assert!(bit_sequence_index != 255 || scalars[i].0[3] >> 63 == 0); if bucket_index > 0 { buckets[bucket_index] += points[i]; if bucket_index > max_bucket { max_bucket = bucket_index; } } } } res += &buckets[max_bucket]; for i in (1..max_bucket).rev() { buckets[i] += buckets[i + 1]; res += buckets[i]; buckets[i + 1] = Self::identity(); } buckets[1] = Self::identity(); if bit_sequence_index < WINDOW { break; } bit_sequence_index -= WINDOW; num_doubles = { if bit_sequence_index < EDGE { bit_sequence_index + 1 } else { WINDOW } }; } res } }; } macro_rules! impl_serde { ($name:ident, $serfunc:expr, $deserfunc:expr, $len:expr) => { impl serde::Serialize for $name { fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { $serfunc(self).serialize(s) } } impl<'de> serde::Deserialize<'de> for $name { fn deserialize<D>(deserializer: D) -> Result<$name, D::Error> where D: serde::Deserializer<'de>, { struct ByteArrayVisitor; impl<'de> serde::de::Visitor<'de> for ByteArrayVisitor { type Value = $name; fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "an array of {} bytes", $len) } fn visit_seq<A>(self, mut seq: A) -> Result<$name, A::Error> where A: serde::de::SeqAccess<'de>, { let mut arr = [0u8; $len]; for i in 0..arr.len() { arr[i] = seq .next_element()? .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?; } let p = $deserfunc(&arr); if p.is_some().unwrap_u8() == 1 { Ok(p.unwrap()) } else { Err(serde::de::Error::invalid_value( serde::de::Unexpected::Bytes(&arr), &self, )) } } } if $len <= 32 && $len > 0 { // for arrays of size from 1 to 32 serde implements serialization using tuple deserializer.deserialize_tuple($len, ByteArrayVisitor) } else { // for other sizes serialization is implemented using sequence deserializer.deserialize_seq(ByteArrayVisitor) } } } }; }
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::runtime::integer_to_string::base_integer_to_string; #[native_implemented::function(erlang:integer_to_list/2)] pub fn result(process: &Process, integer: Term, base: Term) -> exception::Result<Term> { let string = base_integer_to_string(base, integer)?; let charlist = process.charlist_from_str(&string); Ok(charlist) }
use libc::c_int; use wasmer_runtime_core::Instance; // NOTE: Not implemented by Emscripten pub extern "C" fn ___lock(which: c_int, varargs: c_int, _instance: &mut Instance) { debug!("emscripten::___lock {}, {}", which, varargs); } // NOTE: Not implemented by Emscripten pub extern "C" fn ___unlock(which: c_int, varargs: c_int, _instance: &mut Instance) { debug!("emscripten::___unlock {}, {}", which, varargs); } // NOTE: Not implemented by Emscripten pub extern "C" fn ___wait(_which: c_int, _varargs: c_int, _instance: &mut Instance) { debug!("emscripten::___wait"); }
#[doc = "Reader of register CIR"] pub type R = crate::R<u32, super::CIR>; #[doc = "Writer for register CIR"] pub type W = crate::W<u32, super::CIR>; #[doc = "Register CIR `reset()`'s with value 0"] impl crate::ResetValue for super::CIR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Clock security system interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CSSC_AW { #[doc = "1: Clear interrupt"] CLEAR = 1, } impl From<CSSC_AW> for bool { #[inline(always)] fn from(variant: CSSC_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `CSSC`"] pub struct CSSC_W<'a> { w: &'a mut W, } impl<'a> CSSC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSSC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(CSSC_AW::CLEAR) } #[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 = "MSI ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSIRDYC_AW { #[doc = "1: Clear interrupt"] CLEAR = 1, } impl From<MSIRDYC_AW> for bool { #[inline(always)] fn from(variant: MSIRDYC_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `MSIRDYC`"] pub struct MSIRDYC_W<'a> { w: &'a mut W, } impl<'a> MSIRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSIRDYC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MSIRDYC_AW::CLEAR) } #[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 = "PLL ready interrupt clear"] pub type PLLRDYC_AW = MSIRDYC_AW; #[doc = "Write proxy for field `PLLRDYC`"] pub struct PLLRDYC_W<'a> { w: &'a mut W, } impl<'a> PLLRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLLRDYC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MSIRDYC_AW::CLEAR) } #[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 = "HSE ready interrupt clear"] pub type HSERDYC_AW = MSIRDYC_AW; #[doc = "Write proxy for field `HSERDYC`"] pub struct HSERDYC_W<'a> { w: &'a mut W, } impl<'a> HSERDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSERDYC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MSIRDYC_AW::CLEAR) } #[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 = "HSI ready interrupt clear"] pub type HSIRDYC_AW = MSIRDYC_AW; #[doc = "Write proxy for field `HSIRDYC`"] pub struct HSIRDYC_W<'a> { w: &'a mut W, } impl<'a> HSIRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIRDYC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MSIRDYC_AW::CLEAR) } #[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 = "LSE ready interrupt clear"] pub type LSERDYC_AW = MSIRDYC_AW; #[doc = "Write proxy for field `LSERDYC`"] pub struct LSERDYC_W<'a> { w: &'a mut W, } impl<'a> LSERDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSERDYC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MSIRDYC_AW::CLEAR) } #[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 = "LSI ready interrupt clear"] pub type LSIRDYC_AW = MSIRDYC_AW; #[doc = "Write proxy for field `LSIRDYC`"] pub struct LSIRDYC_W<'a> { w: &'a mut W, } impl<'a> LSIRDYC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSIRDYC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MSIRDYC_AW::CLEAR) } #[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 = "MSI ready interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSIRDYIE_A { #[doc = "0: Interrupt disabled"] DISABLED = 0, #[doc = "1: Interrupt enabled"] ENABLED = 1, } impl From<MSIRDYIE_A> for bool { #[inline(always)] fn from(variant: MSIRDYIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MSIRDYIE`"] pub type MSIRDYIE_R = crate::R<bool, MSIRDYIE_A>; impl MSIRDYIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSIRDYIE_A { match self.bits { false => MSIRDYIE_A::DISABLED, true => MSIRDYIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == MSIRDYIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == MSIRDYIE_A::ENABLED } } #[doc = "Write proxy for field `MSIRDYIE`"] pub struct MSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> MSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSIRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MSIRDYIE_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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "PLL ready interrupt enable"] pub type PLLRDYIE_A = MSIRDYIE_A; #[doc = "Reader of field `PLLRDYIE`"] pub type PLLRDYIE_R = crate::R<bool, MSIRDYIE_A>; #[doc = "Write proxy for field `PLLRDYIE`"] pub struct PLLRDYIE_W<'a> { w: &'a mut W, } impl<'a> PLLRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLLRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MSIRDYIE_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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "HSE ready interrupt enable"] pub type HSERDYIE_A = MSIRDYIE_A; #[doc = "Reader of field `HSERDYIE`"] pub type HSERDYIE_R = crate::R<bool, MSIRDYIE_A>; #[doc = "Write proxy for field `HSERDYIE`"] pub struct HSERDYIE_W<'a> { w: &'a mut W, } impl<'a> HSERDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSERDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MSIRDYIE_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "HSI ready interrupt enable"] pub type HSIRDYIE_A = MSIRDYIE_A; #[doc = "Reader of field `HSIRDYIE`"] pub type HSIRDYIE_R = crate::R<bool, MSIRDYIE_A>; #[doc = "Write proxy for field `HSIRDYIE`"] pub struct HSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> HSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MSIRDYIE_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "LSE ready interrupt enable"] pub type LSERDYIE_A = MSIRDYIE_A; #[doc = "Reader of field `LSERDYIE`"] pub type LSERDYIE_R = crate::R<bool, MSIRDYIE_A>; #[doc = "Write proxy for field `LSERDYIE`"] pub struct LSERDYIE_W<'a> { w: &'a mut W, } impl<'a> LSERDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSERDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MSIRDYIE_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "LSI ready interrupt enable"] pub type LSIRDYIE_A = MSIRDYIE_A; #[doc = "Reader of field `LSIRDYIE`"] pub type LSIRDYIE_R = crate::R<bool, MSIRDYIE_A>; #[doc = "Write proxy for field `LSIRDYIE`"] pub struct LSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> LSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSIRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MSIRDYIE_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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Clock security system interrupt flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CSSF_A { #[doc = "0: No clock security interrupt caused by HSE clock failure"] NOTINTERUPTED = 0, #[doc = "1: Clock security interrupt caused by HSE clock failure"] INTERUPTED = 1, } impl From<CSSF_A> for bool { #[inline(always)] fn from(variant: CSSF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CSSF`"] pub type CSSF_R = crate::R<bool, CSSF_A>; impl CSSF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CSSF_A { match self.bits { false => CSSF_A::NOTINTERUPTED, true => CSSF_A::INTERUPTED, } } #[doc = "Checks if the value of the field is `NOTINTERUPTED`"] #[inline(always)] pub fn is_not_interupted(&self) -> bool { *self == CSSF_A::NOTINTERUPTED } #[doc = "Checks if the value of the field is `INTERUPTED`"] #[inline(always)] pub fn is_interupted(&self) -> bool { *self == CSSF_A::INTERUPTED } } #[doc = "MSI ready interrupt flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSIRDYF_A { #[doc = "0: Clock is not stable"] NOTSTABLE = 0, #[doc = "1: Clock is stable"] STABLE = 1, } impl From<MSIRDYF_A> for bool { #[inline(always)] fn from(variant: MSIRDYF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MSIRDYF`"] pub type MSIRDYF_R = crate::R<bool, MSIRDYF_A>; impl MSIRDYF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSIRDYF_A { match self.bits { false => MSIRDYF_A::NOTSTABLE, true => MSIRDYF_A::STABLE, } } #[doc = "Checks if the value of the field is `NOTSTABLE`"] #[inline(always)] pub fn is_not_stable(&self) -> bool { *self == MSIRDYF_A::NOTSTABLE } #[doc = "Checks if the value of the field is `STABLE`"] #[inline(always)] pub fn is_stable(&self) -> bool { *self == MSIRDYF_A::STABLE } } #[doc = "PLL ready interrupt flag"] pub type PLLRDYF_A = MSIRDYF_A; #[doc = "Reader of field `PLLRDYF`"] pub type PLLRDYF_R = crate::R<bool, MSIRDYF_A>; #[doc = "HSE ready interrupt flag"] pub type HSERDYF_A = MSIRDYF_A; #[doc = "Reader of field `HSERDYF`"] pub type HSERDYF_R = crate::R<bool, MSIRDYF_A>; #[doc = "HSI ready interrupt flag"] pub type HSIRDYF_A = MSIRDYF_A; #[doc = "Reader of field `HSIRDYF`"] pub type HSIRDYF_R = crate::R<bool, MSIRDYF_A>; #[doc = "LSE ready interrupt flag"] pub type LSERDYF_A = MSIRDYF_A; #[doc = "Reader of field `LSERDYF`"] pub type LSERDYF_R = crate::R<bool, MSIRDYF_A>; #[doc = "LSI ready interrupt flag"] pub type LSIRDYF_A = MSIRDYF_A; #[doc = "Reader of field `LSIRDYF`"] pub type LSIRDYF_R = crate::R<bool, MSIRDYF_A>; #[doc = "LSE Clock security system interrupt clear"] pub type LSECSSC_AW = CSSC_AW; #[doc = "Write proxy for field `LSECSSC`"] pub struct LSECSSC_W<'a> { w: &'a mut W, } impl<'a> LSECSSC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSECSSC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear interrupt"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(CSSC_AW::CLEAR) } #[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 = "LSE Clock security system interrupt flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LSECSSF_A { #[doc = "0: No failure detected on the external 32 KHz oscillator"] NOFAILURE = 0, #[doc = "1: A failure is detected on the external 32 kHz oscillator"] FAILURE = 1, } impl From<LSECSSF_A> for bool { #[inline(always)] fn from(variant: LSECSSF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LSECSSF`"] pub type LSECSSF_R = crate::R<bool, LSECSSF_A>; impl LSECSSF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LSECSSF_A { match self.bits { false => LSECSSF_A::NOFAILURE, true => LSECSSF_A::FAILURE, } } #[doc = "Checks if the value of the field is `NOFAILURE`"] #[inline(always)] pub fn is_no_failure(&self) -> bool { *self == LSECSSF_A::NOFAILURE } #[doc = "Checks if the value of the field is `FAILURE`"] #[inline(always)] pub fn is_failure(&self) -> bool { *self == LSECSSF_A::FAILURE } } #[doc = "Write proxy for field `LSECSSF`"] pub struct LSECSSF_W<'a> { w: &'a mut W, } impl<'a> LSECSSF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSECSSF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No failure detected on the external 32 KHz oscillator"] #[inline(always)] pub fn no_failure(self) -> &'a mut W { self.variant(LSECSSF_A::NOFAILURE) } #[doc = "A failure is detected on the external 32 kHz oscillator"] #[inline(always)] pub fn failure(self) -> &'a mut W { self.variant(LSECSSF_A::FAILURE) } #[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 = "LSE clock security system interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LSECSSIE_A { #[doc = "0: LSE CSS interrupt disabled"] DISABLED = 0, #[doc = "1: LSE CSS interrupt enabled"] ENABLED = 1, } impl From<LSECSSIE_A> for bool { #[inline(always)] fn from(variant: LSECSSIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LSECSSIE`"] pub type LSECSSIE_R = crate::R<bool, LSECSSIE_A>; impl LSECSSIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LSECSSIE_A { match self.bits { false => LSECSSIE_A::DISABLED, true => LSECSSIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == LSECSSIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == LSECSSIE_A::ENABLED } } #[doc = "Write proxy for field `LSECSSIE`"] pub struct LSECSSIE_W<'a> { w: &'a mut W, } impl<'a> LSECSSIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSECSSIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "LSE CSS interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSECSSIE_A::DISABLED) } #[doc = "LSE CSS interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSECSSIE_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } impl R { #[doc = "Bit 13 - MSI ready interrupt enable"] #[inline(always)] pub fn msirdyie(&self) -> MSIRDYIE_R { MSIRDYIE_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - PLL ready interrupt enable"] #[inline(always)] pub fn pllrdyie(&self) -> PLLRDYIE_R { PLLRDYIE_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 11 - HSE ready interrupt enable"] #[inline(always)] pub fn hserdyie(&self) -> HSERDYIE_R { HSERDYIE_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - HSI ready interrupt enable"] #[inline(always)] pub fn hsirdyie(&self) -> HSIRDYIE_R { HSIRDYIE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - LSE ready interrupt enable"] #[inline(always)] pub fn lserdyie(&self) -> LSERDYIE_R { LSERDYIE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - LSI ready interrupt enable"] #[inline(always)] pub fn lsirdyie(&self) -> LSIRDYIE_R { LSIRDYIE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - Clock security system interrupt flag"] #[inline(always)] pub fn cssf(&self) -> CSSF_R { CSSF_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 5 - MSI ready interrupt flag"] #[inline(always)] pub fn msirdyf(&self) -> MSIRDYF_R { MSIRDYF_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - PLL ready interrupt flag"] #[inline(always)] pub fn pllrdyf(&self) -> PLLRDYF_R { PLLRDYF_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - HSE ready interrupt flag"] #[inline(always)] pub fn hserdyf(&self) -> HSERDYF_R { HSERDYF_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - HSI ready interrupt flag"] #[inline(always)] pub fn hsirdyf(&self) -> HSIRDYF_R { HSIRDYF_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - LSE ready interrupt flag"] #[inline(always)] pub fn lserdyf(&self) -> LSERDYF_R { LSERDYF_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - LSI ready interrupt flag"] #[inline(always)] pub fn lsirdyf(&self) -> LSIRDYF_R { LSIRDYF_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 6 - LSE Clock security system interrupt flag"] #[inline(always)] pub fn lsecssf(&self) -> LSECSSF_R { LSECSSF_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 14 - LSE clock security system interrupt enable"] #[inline(always)] pub fn lsecssie(&self) -> LSECSSIE_R { LSECSSIE_R::new(((self.bits >> 14) & 0x01) != 0) } } impl W { #[doc = "Bit 23 - Clock security system interrupt clear"] #[inline(always)] pub fn cssc(&mut self) -> CSSC_W { CSSC_W { w: self } } #[doc = "Bit 21 - MSI ready interrupt clear"] #[inline(always)] pub fn msirdyc(&mut self) -> MSIRDYC_W { MSIRDYC_W { w: self } } #[doc = "Bit 20 - PLL ready interrupt clear"] #[inline(always)] pub fn pllrdyc(&mut self) -> PLLRDYC_W { PLLRDYC_W { w: self } } #[doc = "Bit 19 - HSE ready interrupt clear"] #[inline(always)] pub fn hserdyc(&mut self) -> HSERDYC_W { HSERDYC_W { w: self } } #[doc = "Bit 18 - HSI ready interrupt clear"] #[inline(always)] pub fn hsirdyc(&mut self) -> HSIRDYC_W { HSIRDYC_W { w: self } } #[doc = "Bit 17 - LSE ready interrupt clear"] #[inline(always)] pub fn lserdyc(&mut self) -> LSERDYC_W { LSERDYC_W { w: self } } #[doc = "Bit 16 - LSI ready interrupt clear"] #[inline(always)] pub fn lsirdyc(&mut self) -> LSIRDYC_W { LSIRDYC_W { w: self } } #[doc = "Bit 13 - MSI ready interrupt enable"] #[inline(always)] pub fn msirdyie(&mut self) -> MSIRDYIE_W { MSIRDYIE_W { w: self } } #[doc = "Bit 12 - PLL ready interrupt enable"] #[inline(always)] pub fn pllrdyie(&mut self) -> PLLRDYIE_W { PLLRDYIE_W { w: self } } #[doc = "Bit 11 - HSE ready interrupt enable"] #[inline(always)] pub fn hserdyie(&mut self) -> HSERDYIE_W { HSERDYIE_W { w: self } } #[doc = "Bit 10 - HSI ready interrupt enable"] #[inline(always)] pub fn hsirdyie(&mut self) -> HSIRDYIE_W { HSIRDYIE_W { w: self } } #[doc = "Bit 9 - LSE ready interrupt enable"] #[inline(always)] pub fn lserdyie(&mut self) -> LSERDYIE_W { LSERDYIE_W { w: self } } #[doc = "Bit 8 - LSI ready interrupt enable"] #[inline(always)] pub fn lsirdyie(&mut self) -> LSIRDYIE_W { LSIRDYIE_W { w: self } } #[doc = "Bit 22 - LSE Clock security system interrupt clear"] #[inline(always)] pub fn lsecssc(&mut self) -> LSECSSC_W { LSECSSC_W { w: self } } #[doc = "Bit 6 - LSE Clock security system interrupt flag"] #[inline(always)] pub fn lsecssf(&mut self) -> LSECSSF_W { LSECSSF_W { w: self } } #[doc = "Bit 14 - LSE clock security system interrupt enable"] #[inline(always)] pub fn lsecssie(&mut self) -> LSECSSIE_W { LSECSSIE_W { w: self } } }
use std::collections::HashMap; use parser::types::{ExpressionType, MutPass, ProgramError, Statement, StatementType, Expression}; pub struct Changes<'a> { changes: HashMap<usize, ExpressionType<'a>>, statement_changes: HashMap<usize, StatementType<'a>>, } impl<'a> Changes<'a> { pub(crate) fn new(changes: HashMap<usize, ExpressionType<'a>>, statement_changes: HashMap<usize, StatementType<'a>>) -> Changes<'a> { Changes { changes, statement_changes, } } } // FIXME: Convert this into an immutable datastructure impl<'a> MutPass<'a, ()> for Changes<'a> { fn run(&mut self, ss: &'a mut [Statement<'a>]) -> Result<(), Vec<ProgramError<'a>>> { for s in ss.iter_mut() { self.pass(s)?; } Ok(()) } fn pass(&mut self, statement: &'a mut Statement<'a>) -> Result<(), Vec<ProgramError<'a>>> { if let Some(new_statement_type) = self.statement_changes.remove(&statement.id()) { statement.statement_type = new_statement_type; } match &mut statement.statement_type { StatementType::Module { name, statements } => self.pass_module(name, statements)?, StatementType::Import { name } => self.pass_import(name)?, StatementType::Block { body } => self.pass_block(body)?, StatementType::VariableDeclaration { expression, name } => self.pass_variable_declaration(name, expression)?, StatementType::ClassDeclaration { name, properties, methods, static_methods, setters, getters, superclass, } => self.pass_class_declaration(name, properties, methods, static_methods, setters, getters, superclass)?, StatementType::TraitDeclaration { name, .. } => self.pass_trait_declaration(name)?, StatementType::TraitImplementation { class_name, trait_name, methods, static_methods, setters, getters, .. } => self.pass_trait_implementation(class_name, trait_name, methods, static_methods, setters, getters)?, StatementType::FunctionDeclaration { name, arguments, body, .. } => self.pass_function_declaration(name, arguments, body)?, StatementType::Expression { expression } => self.pass_expression_statement(expression)?, StatementType::If { condition, then, otherwise, } => self.pass_if(condition, then, otherwise)?, StatementType::PrintStatement { expression } => self.pass_print(expression)?, StatementType::Return { value } => self.pass_return(value)?, StatementType::While { condition, action } => self.pass_while(condition, action)?, StatementType::Break => {} StatementType::EOF => {} }; Ok(()) } fn pass_expression(&mut self, expression: &'a mut Expression<'a>) -> Result<(), Vec<ProgramError<'a>>> { let expression_id = expression.id(); if let Some(new_expression_type) = self.changes.remove(&expression_id) { expression.expression_type = new_expression_type; } match &mut expression.expression_type { ExpressionType::UpliftClassVariables(name) => self.pass_uplift_class_variables(name)?, ExpressionType::UpliftFunctionVariables(name) => self.pass_uplift_function_variables(name)?, ExpressionType::IsType { value, checked_type } => self.pass_checked_type(value, checked_type)?, ExpressionType::ModuleLiteral { module, field, } => self.pass_module_literal(module, field)?, ExpressionType::Get { callee, .. } => self.pass_get(callee)?, ExpressionType::Set { callee, value, .. } => self.pass_set(callee, value)?, ExpressionType::VariableLiteral { identifier } => self.pass_variable_literal(identifier, expression_id)?, ExpressionType::VariableAssignment { identifier, expression: expression_value, } => self.pass_variable_assignment(identifier, expression_value, expression_id)?, ExpressionType::Binary { left, right, operator } => self.pass_binary(left, right, operator)?, ExpressionType::Call { callee, arguments } => self.pass_call(callee, arguments, expression_id)?, ExpressionType::Grouping { expression } => self.pass_grouping(expression)?, ExpressionType::Conditional { condition, then_branch, else_branch, } => self.pass_conditional(condition, then_branch, else_branch)?, ExpressionType::Unary { operand, operator } => self.pass_unary(operand, operator)?, ExpressionType::ExpressionLiteral { value } => self.pass_expression_literal(value)?, ExpressionType::AnonymousFunction { arguments, body } => self.pass_anonymous_function(arguments, body, expression_id)?, ExpressionType::RepeatedElementArray { element, length } => self.pass_repeated_element_array(element, length)?, ExpressionType::Array { elements } => self.pass_array(elements)?, ExpressionType::ArrayElement { array, index } => self.pass_array_element(array, index)?, ExpressionType::ArrayElementSet { array, index, value, } => self.pass_array_element_set(array, index, value)?, }; Ok(()) } }
use crate::NumOfPages; use core::fmt; use core::ops::Add; use core::ops::AddAssign; use core::ops::Div; use core::ops::DivAssign; use core::ops::Mul; use core::ops::MulAssign; use core::ops::Sub; use core::ops::SubAssign; use x86_64::structures::paging::PageSize; use x86_64::PhysAddr; use x86_64::VirtAddr; #[repr(transparent)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] /// A struct representing byte size. pub struct Bytes(usize); impl Bytes { /// Creates a new instance with given value. #[must_use] pub const fn new(bytes: usize) -> Self { Self(bytes) } /// Equivalent to `Bytes::new(0)`. #[must_use] pub const fn zero() -> Self { Self::new(0) } /// Returns the value. #[must_use] pub const fn as_usize(self) -> usize { self.0 } /// Converts bytes to the number of physical pages. Note that the number of physical pages will /// be calculated so that the specified bytes will be fit in pages. #[must_use] pub fn as_num_of_pages<T: PageSize>(self) -> NumOfPages<T> { #[allow(clippy::cast_possible_truncation)] NumOfPages::new((self.0 + T::SIZE as usize - 1) / T::SIZE as usize) } } impl Add for Bytes { type Output = Bytes; fn add(self, rhs: Bytes) -> Self { Self::new(self.0 + rhs.0) } } impl Add<usize> for Bytes { type Output = Bytes; fn add(self, rhs: usize) -> Self::Output { Self::new(self.0 + rhs) } } impl Add<Bytes> for VirtAddr { type Output = VirtAddr; fn add(self, rhs: Bytes) -> Self::Output { self + rhs.as_usize() } } impl Add<Bytes> for PhysAddr { type Output = PhysAddr; fn add(self, rhs: Bytes) -> Self::Output { self + rhs.as_usize() } } impl AddAssign for Bytes { fn add_assign(&mut self, rhs: Bytes) { self.0 += rhs.0; } } impl AddAssign<usize> for Bytes { fn add_assign(&mut self, rhs: usize) { self.0 += rhs; } } impl AddAssign<Bytes> for VirtAddr { fn add_assign(&mut self, rhs: Bytes) { *self += rhs.as_usize(); } } impl AddAssign<Bytes> for PhysAddr { fn add_assign(&mut self, rhs: Bytes) { *self += rhs.as_usize(); } } impl Sub for Bytes { type Output = Bytes; fn sub(self, rhs: Bytes) -> Self { Self::new(self.0 - rhs.0) } } impl Sub<usize> for Bytes { type Output = Bytes; fn sub(self, rhs: usize) -> Self::Output { Self::new(self.0 - rhs) } } impl Sub<Bytes> for VirtAddr { type Output = VirtAddr; fn sub(self, rhs: Bytes) -> Self::Output { self - rhs.as_usize() } } impl Sub<Bytes> for PhysAddr { type Output = PhysAddr; fn sub(self, rhs: Bytes) -> Self::Output { self - rhs.as_usize() } } impl SubAssign for Bytes { fn sub_assign(&mut self, rhs: Bytes) { self.0 -= rhs.0; } } impl SubAssign<usize> for Bytes { fn sub_assign(&mut self, rhs: usize) { *self -= Bytes::new(rhs); } } impl SubAssign<Bytes> for VirtAddr { fn sub_assign(&mut self, rhs: Bytes) { *self -= rhs.as_usize(); } } impl SubAssign<Bytes> for PhysAddr { fn sub_assign(&mut self, rhs: Bytes) { *self -= rhs.as_usize() } } impl Mul<usize> for Bytes { type Output = Bytes; fn mul(self, rhs: usize) -> Self::Output { Self(self.0 * rhs) } } impl MulAssign<usize> for Bytes { fn mul_assign(&mut self, rhs: usize) { *self = *self * rhs; } } impl Div<usize> for Bytes { type Output = Bytes; fn div(self, rhs: usize) -> Self::Output { Self(self.0 / rhs) } } impl DivAssign<usize> for Bytes { fn div_assign(&mut self, rhs: usize) { *self = *self / rhs; } } impl From<usize> for Bytes { fn from(b: usize) -> Self { Self::new(b) } } impl fmt::Display for Bytes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let unit = if self.0 == 1 { "byte" } else { "bytes" }; write!(f, "{} {}", self.0, unit) } } #[cfg(test)] mod tests { use super::*; use x86_64::structures::paging::{Size1GiB, Size2MiB, Size4KiB}; use x86_64::{PhysAddr, VirtAddr}; #[test] fn get_value_from_bytes() { let bytes = Bytes::new(334); assert_eq!(bytes.as_usize(), 334); } #[test] fn bytes_to_pages() { let bytes = Bytes::new(0x40000000); assert_eq!(bytes.as_num_of_pages::<Size4KiB>().as_usize(), 0x40000); assert_eq!(bytes.as_num_of_pages::<Size2MiB>().as_usize(), 512); assert_eq!(bytes.as_num_of_pages::<Size1GiB>().as_usize(), 1); } #[test] fn addition_bytes_to_bytes() { let b1 = Bytes::new(3); let b2 = Bytes::new(1); let sum = b1 + b2; assert_eq!(sum.as_usize(), 4); } #[test] fn add_usize_to_bytes() { let b = Bytes::new(3); assert_eq!(b + 7, Bytes::new(10)); } #[test] fn subtraction_bytes_from_bytes() { let b1 = Bytes::new(3); let b2 = Bytes::new(1); let diff = b1 - b2; assert_eq!(diff.as_usize(), 2); } #[test] fn subtract_usize_from_bytes() { let b = Bytes::new(5); assert_eq!(b - 3, Bytes::new(2)); } #[test] fn add_assign_bytes_to_bytes() { let mut b1 = Bytes::new(3); b1 += Bytes::new(1); assert_eq!(b1.as_usize(), 4); } #[test] fn add_assign_usize_to_bytes() { let mut b1 = Bytes::new(3); b1 += 1; assert_eq!(b1.as_usize(), 4); } #[test] fn sub_assign_bytes_to_bytes() { let mut b1 = Bytes::new(3); b1 -= Bytes::new(1); assert_eq!(b1.as_usize(), 2); } #[test] fn sub_assign_usize_to_bytes() { let mut b1 = Bytes::new(10); b1 -= 3; assert_eq!(b1, Bytes::new(7)); } #[test] fn mul_bytes_by_usize() { let b = Bytes::new(3); let mul = b * 4; assert_eq!(mul.as_usize(), 12); } #[test] fn mul_assign_bytes_by_usize() { let mut b = Bytes::new(3); b *= 4; assert_eq!(b.as_usize(), 12); } #[test] fn div_bytes_by_usize() { let b1 = Bytes::new(3); let div = b1 / 2; assert_eq!(div.as_usize(), 1); } #[test] fn divassign_bytes_by_usize() { let mut b = Bytes::new(3); b /= 2; assert_eq!(b.as_usize(), 1); } #[test] fn bytes_zero() { let b = Bytes::zero(); assert_eq!(b.as_usize(), 0); } #[test] fn from() { let b = Bytes::from(3); assert_eq!(b, Bytes::new(3)); } #[test] fn debug() { let b = Bytes::new(3); let f = format!("{:?}", b); assert_eq!(f, format!("Bytes(3)")); } #[test] fn display_0() { let b = Bytes::zero(); let f = format!("{}", b); assert_eq!(f, format!("0 bytes")); } #[test] fn display_1() { let b = Bytes::new(1); let f = format!("{}", b); assert_eq!(f, format!("1 byte")); } #[test] fn display_2() { let b = Bytes::new(2); let f = format!("{}", b); assert_eq!(f, format!("2 bytes")); } #[test] fn add_bytes_to_virt_addr() { let a = VirtAddr::new(0x1000); let bytes = Bytes::new(4); assert_eq!(a + bytes, VirtAddr::new(0x1004)); } #[test] fn add_bytes_to_phys_addr() { let a = PhysAddr::new(0x1000); let bytes = Bytes::new(4); assert_eq!(a + bytes, PhysAddr::new(0x1004)); } #[test] fn add_assign_bytes_to_virt_addr() { let mut a = VirtAddr::new(0x1000); a += Bytes::new(4); assert_eq!(a, VirtAddr::new(0x1004)); } #[test] fn add_assign_bytes_to_phys_addr() { let mut a = PhysAddr::new(0x1000); a += Bytes::new(4); assert_eq!(a, PhysAddr::new(0x1004)); } #[test] fn sub_bytes_from_virt_addr() { let a = VirtAddr::new(0x1000); let bytes = Bytes::new(4); assert_eq!(a - bytes, VirtAddr::new(0xffc)); } #[test] fn sub_bytes_from_phys_addr() { let a = PhysAddr::new(0x1000); let bytes = Bytes::new(4); assert_eq!(a - bytes, PhysAddr::new(0xffc)); } #[test] fn sub_assign_bytes_from_virt_addr() { let mut a = VirtAddr::new(0x1000); a -= Bytes::new(4); assert_eq!(a, VirtAddr::new(0xffc)); } #[test] fn sub_assign_bytes_from_phys_addr() { let mut a = PhysAddr::new(0x1000); a -= Bytes::new(4); assert_eq!(a, PhysAddr::new(0xffc)); } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qmatrix4x4.h // dst-file: /src/gui/qmatrix4x4.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 super::qtransform::*; // 773 use super::qvector3d::*; // 773 use super::qmatrix::*; // 773 use super::super::core::qrect::*; // 771 use super::qvector4d::*; // 773 // use super::qgenericmatrix::*; // 775 use super::qquaternion::*; // 773 use super::super::core::qpoint::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QMatrix4x4_Class_Size() -> c_int; // proto: QTransform QMatrix4x4::toTransform(); fn C_ZNK10QMatrix4x411toTransformEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QMatrix4x4::scale(const QVector3D & vector); fn C_ZN10QMatrix4x45scaleERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QMatrix4x4::translate(float x, float y, float z); fn C_ZN10QMatrix4x49translateEfff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float); // proto: const float * QMatrix4x4::constData(); fn C_ZNK10QMatrix4x49constDataEv(qthis: u64 /* *mut c_void*/) -> *mut c_float; // proto: float * QMatrix4x4::data(); fn C_ZN10QMatrix4x44dataEv(qthis: u64 /* *mut c_void*/) -> *mut c_float; // proto: QMatrix4x4 QMatrix4x4::inverted(bool * invertible); fn C_ZNK10QMatrix4x48invertedEPb(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> *mut c_void; // proto: QVector3D QMatrix4x4::mapVector(const QVector3D & vector); fn C_ZNK10QMatrix4x49mapVectorERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix4x4::ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane); fn C_ZN10QMatrix4x45orthoEffffff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float, arg4: c_float, arg5: c_float); // proto: void QMatrix4x4::QMatrix4x4(); fn C_ZN10QMatrix4x4C2Ev() -> u64; // proto: QMatrix QMatrix4x4::toAffine(); fn C_ZNK10QMatrix4x48toAffineEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QRectF QMatrix4x4::mapRect(const QRectF & rect); fn C_ZNK10QMatrix4x47mapRectERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix4x4::setColumn(int index, const QVector4D & value); fn C_ZN10QMatrix4x49setColumnEiRK9QVector4D(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void); // proto: bool QMatrix4x4::isIdentity(); fn C_ZNK10QMatrix4x410isIdentityEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QVector4D QMatrix4x4::column(int index); fn C_ZNK10QMatrix4x46columnEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void; // proto: void QMatrix4x4::setRow(int index, const QVector4D & value); fn C_ZN10QMatrix4x46setRowEiRK9QVector4D(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void); // proto: void QMatrix4x4::flipCoordinates(); fn C_ZN10QMatrix4x415flipCoordinatesEv(qthis: u64 /* *mut c_void*/); // proto: QMatrix3x3 QMatrix4x4::normalMatrix(); fn C_ZNK10QMatrix4x412normalMatrixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QMatrix4x4::viewport(float left, float bottom, float width, float height, float nearPlane, float farPlane); fn C_ZN10QMatrix4x48viewportEffffff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float, arg4: c_float, arg5: c_float); // proto: void QMatrix4x4::copyDataTo(float * values); fn C_ZNK10QMatrix4x410copyDataToEPf(qthis: u64 /* *mut c_void*/, arg0: *mut c_float); // proto: void QMatrix4x4::QMatrix4x4(const QTransform & transform); fn C_ZN10QMatrix4x4C2ERK10QTransform(arg0: *mut c_void) -> u64; // proto: bool QMatrix4x4::isAffine(); fn C_ZNK10QMatrix4x48isAffineEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QMatrix4x4::ortho(const QRect & rect); fn C_ZN10QMatrix4x45orthoERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QMatrix4x4::rotate(const QQuaternion & quaternion); fn C_ZN10QMatrix4x46rotateERK11QQuaternion(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QMatrix4x4::QMatrix4x4(const QMatrix & matrix); fn C_ZN10QMatrix4x4C2ERK7QMatrix(arg0: *mut c_void) -> u64; // proto: void QMatrix4x4::perspective(float verticalAngle, float aspectRatio, float nearPlane, float farPlane); fn C_ZN10QMatrix4x411perspectiveEffff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float); // proto: void QMatrix4x4::translate(const QVector3D & vector); fn C_ZN10QMatrix4x49translateERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: double QMatrix4x4::determinant(); fn C_ZNK10QMatrix4x411determinantEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: void QMatrix4x4::scale(float x, float y, float z); fn C_ZN10QMatrix4x45scaleEfff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float); // proto: void QMatrix4x4::frustum(float left, float right, float bottom, float top, float nearPlane, float farPlane); fn C_ZN10QMatrix4x47frustumEffffff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float, arg4: c_float, arg5: c_float); // proto: QPoint QMatrix4x4::map(const QPoint & point); fn C_ZNK10QMatrix4x43mapERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix4x4::optimize(); fn C_ZN10QMatrix4x48optimizeEv(qthis: u64 /* *mut c_void*/); // proto: void QMatrix4x4::QMatrix4x4(const float * values); fn C_ZN10QMatrix4x4C2EPKf(arg0: *mut c_float) -> u64; // proto: void QMatrix4x4::translate(float x, float y); fn C_ZN10QMatrix4x49translateEff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float); // proto: void QMatrix4x4::setToIdentity(); fn C_ZN10QMatrix4x413setToIdentityEv(qthis: u64 /* *mut c_void*/); // proto: QRect QMatrix4x4::mapRect(const QRect & rect); fn C_ZNK10QMatrix4x47mapRectERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix4x4::scale(float x, float y); fn C_ZN10QMatrix4x45scaleEff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float); // proto: void QMatrix4x4::QMatrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44); fn C_ZN10QMatrix4x4C2Effffffffffffffff(arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float, arg4: c_float, arg5: c_float, arg6: c_float, arg7: c_float, arg8: c_float, arg9: c_float, arg10: c_float, arg11: c_float, arg12: c_float, arg13: c_float, arg14: c_float, arg15: c_float) -> u64; // proto: QVector3D QMatrix4x4::map(const QVector3D & point); fn C_ZNK10QMatrix4x43mapERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix4x4::lookAt(const QVector3D & eye, const QVector3D & center, const QVector3D & up); fn C_ZN10QMatrix4x46lookAtERK9QVector3DS2_S2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QMatrix4x4::ortho(const QRectF & rect); fn C_ZN10QMatrix4x45orthoERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QMatrix4x4::viewport(const QRectF & rect); fn C_ZN10QMatrix4x48viewportERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QMatrix4x4::rotate(float angle, float x, float y, float z); fn C_ZN10QMatrix4x46rotateEffff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float); // proto: void QMatrix4x4::fill(float value); fn C_ZN10QMatrix4x44fillEf(qthis: u64 /* *mut c_void*/, arg0: c_float); // proto: void QMatrix4x4::QMatrix4x4(const float * values, int cols, int rows); fn C_ZN10QMatrix4x4C2EPKfii(arg0: *mut c_float, arg1: c_int, arg2: c_int) -> u64; // proto: QTransform QMatrix4x4::toTransform(float distanceToPlane); fn C_ZNK10QMatrix4x411toTransformEf(qthis: u64 /* *mut c_void*/, arg0: c_float) -> *mut c_void; // proto: QMatrix4x4 QMatrix4x4::transposed(); fn C_ZNK10QMatrix4x410transposedEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QPointF QMatrix4x4::map(const QPointF & point); fn C_ZNK10QMatrix4x43mapERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QMatrix4x4::scale(float factor); fn C_ZN10QMatrix4x45scaleEf(qthis: u64 /* *mut c_void*/, arg0: c_float); // proto: QVector4D QMatrix4x4::row(int index); fn C_ZNK10QMatrix4x43rowEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void; // proto: void QMatrix4x4::rotate(float angle, const QVector3D & vector); fn C_ZN10QMatrix4x46rotateEfRK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: *mut c_void); // proto: QVector4D QMatrix4x4::map(const QVector4D & point); fn C_ZNK10QMatrix4x43mapERK9QVector4D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QMatrix4x4)=68 #[derive(Default)] pub struct QMatrix4x4 { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QMatrix4x4 { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMatrix4x4 { return QMatrix4x4{qclsinst: qthis, ..Default::default()}; } } // proto: QTransform QMatrix4x4::toTransform(); impl /*struct*/ QMatrix4x4 { pub fn toTransform<RetType, T: QMatrix4x4_toTransform<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toTransform(self); // return 1; } } pub trait QMatrix4x4_toTransform<RetType> { fn toTransform(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QTransform QMatrix4x4::toTransform(); impl<'a> /*trait*/ QMatrix4x4_toTransform<QTransform> for () { fn toTransform(self , rsthis: & QMatrix4x4) -> QTransform { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x411toTransformEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x411toTransformEv(rsthis.qclsinst)}; let mut ret1 = QTransform::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::scale(const QVector3D & vector); impl /*struct*/ QMatrix4x4 { pub fn scale<RetType, T: QMatrix4x4_scale<RetType>>(& self, overload_args: T) -> RetType { return overload_args.scale(self); // return 1; } } pub trait QMatrix4x4_scale<RetType> { fn scale(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::scale(const QVector3D & vector); impl<'a> /*trait*/ QMatrix4x4_scale<()> for (&'a QVector3D) { fn scale(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45scaleERK9QVector3D()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x45scaleERK9QVector3D(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::translate(float x, float y, float z); impl /*struct*/ QMatrix4x4 { pub fn translate<RetType, T: QMatrix4x4_translate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.translate(self); // return 1; } } pub trait QMatrix4x4_translate<RetType> { fn translate(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::translate(float x, float y, float z); impl<'a> /*trait*/ QMatrix4x4_translate<()> for (f32, f32, f32) { fn translate(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x49translateEfff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; unsafe {C_ZN10QMatrix4x49translateEfff(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: const float * QMatrix4x4::constData(); impl /*struct*/ QMatrix4x4 { pub fn constData<RetType, T: QMatrix4x4_constData<RetType>>(& self, overload_args: T) -> RetType { return overload_args.constData(self); // return 1; } } pub trait QMatrix4x4_constData<RetType> { fn constData(self , rsthis: & QMatrix4x4) -> RetType; } // proto: const float * QMatrix4x4::constData(); impl<'a> /*trait*/ QMatrix4x4_constData<*mut f32> for () { fn constData(self , rsthis: & QMatrix4x4) -> *mut f32 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x49constDataEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x49constDataEv(rsthis.qclsinst)}; return ret as *mut f32; // 1 // return 1; } } // proto: float * QMatrix4x4::data(); impl /*struct*/ QMatrix4x4 { pub fn data<RetType, T: QMatrix4x4_data<RetType>>(& self, overload_args: T) -> RetType { return overload_args.data(self); // return 1; } } pub trait QMatrix4x4_data<RetType> { fn data(self , rsthis: & QMatrix4x4) -> RetType; } // proto: float * QMatrix4x4::data(); impl<'a> /*trait*/ QMatrix4x4_data<*mut f32> for () { fn data(self , rsthis: & QMatrix4x4) -> *mut f32 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x44dataEv()}; let mut ret = unsafe {C_ZN10QMatrix4x44dataEv(rsthis.qclsinst)}; return ret as *mut f32; // 1 // return 1; } } // proto: QMatrix4x4 QMatrix4x4::inverted(bool * invertible); impl /*struct*/ QMatrix4x4 { pub fn inverted<RetType, T: QMatrix4x4_inverted<RetType>>(& self, overload_args: T) -> RetType { return overload_args.inverted(self); // return 1; } } pub trait QMatrix4x4_inverted<RetType> { fn inverted(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QMatrix4x4 QMatrix4x4::inverted(bool * invertible); impl<'a> /*trait*/ QMatrix4x4_inverted<QMatrix4x4> for (Option<&'a mut Vec<i8>>) { fn inverted(self , rsthis: & QMatrix4x4) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x48invertedEPb()}; let arg0 = (if self.is_none() {0 as *const i8} else {self.unwrap().as_ptr()}) as *mut c_char; let mut ret = unsafe {C_ZNK10QMatrix4x48invertedEPb(rsthis.qclsinst, arg0)}; let mut ret1 = QMatrix4x4::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QVector3D QMatrix4x4::mapVector(const QVector3D & vector); impl /*struct*/ QMatrix4x4 { pub fn mapVector<RetType, T: QMatrix4x4_mapVector<RetType>>(& self, overload_args: T) -> RetType { return overload_args.mapVector(self); // return 1; } } pub trait QMatrix4x4_mapVector<RetType> { fn mapVector(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QVector3D QMatrix4x4::mapVector(const QVector3D & vector); impl<'a> /*trait*/ QMatrix4x4_mapVector<QVector3D> for (&'a QVector3D) { fn mapVector(self , rsthis: & QMatrix4x4) -> QVector3D { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x49mapVectorERK9QVector3D()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x49mapVectorERK9QVector3D(rsthis.qclsinst, arg0)}; let mut ret1 = QVector3D::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane); impl /*struct*/ QMatrix4x4 { pub fn ortho<RetType, T: QMatrix4x4_ortho<RetType>>(& self, overload_args: T) -> RetType { return overload_args.ortho(self); // return 1; } } pub trait QMatrix4x4_ortho<RetType> { fn ortho(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane); impl<'a> /*trait*/ QMatrix4x4_ortho<()> for (f32, f32, f32, f32, f32, f32) { fn ortho(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45orthoEffffff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; let arg3 = self.3 as c_float; let arg4 = self.4 as c_float; let arg5 = self.5 as c_float; unsafe {C_ZN10QMatrix4x45orthoEffffff(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: void QMatrix4x4::QMatrix4x4(); impl /*struct*/ QMatrix4x4 { pub fn new<T: QMatrix4x4_new>(value: T) -> QMatrix4x4 { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QMatrix4x4_new { fn new(self) -> QMatrix4x4; } // proto: void QMatrix4x4::QMatrix4x4(); impl<'a> /*trait*/ QMatrix4x4_new for () { fn new(self) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x4C2Ev()}; let ctysz: c_int = unsafe{QMatrix4x4_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN10QMatrix4x4C2Ev()}; let rsthis = QMatrix4x4{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QMatrix QMatrix4x4::toAffine(); impl /*struct*/ QMatrix4x4 { pub fn toAffine<RetType, T: QMatrix4x4_toAffine<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toAffine(self); // return 1; } } pub trait QMatrix4x4_toAffine<RetType> { fn toAffine(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QMatrix QMatrix4x4::toAffine(); impl<'a> /*trait*/ QMatrix4x4_toAffine<QMatrix> for () { fn toAffine(self , rsthis: & QMatrix4x4) -> QMatrix { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x48toAffineEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x48toAffineEv(rsthis.qclsinst)}; let mut ret1 = QMatrix::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QRectF QMatrix4x4::mapRect(const QRectF & rect); impl /*struct*/ QMatrix4x4 { pub fn mapRect<RetType, T: QMatrix4x4_mapRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.mapRect(self); // return 1; } } pub trait QMatrix4x4_mapRect<RetType> { fn mapRect(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QRectF QMatrix4x4::mapRect(const QRectF & rect); impl<'a> /*trait*/ QMatrix4x4_mapRect<QRectF> for (&'a QRectF) { fn mapRect(self , rsthis: & QMatrix4x4) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x47mapRectERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x47mapRectERK6QRectF(rsthis.qclsinst, arg0)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::setColumn(int index, const QVector4D & value); impl /*struct*/ QMatrix4x4 { pub fn setColumn<RetType, T: QMatrix4x4_setColumn<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setColumn(self); // return 1; } } pub trait QMatrix4x4_setColumn<RetType> { fn setColumn(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::setColumn(int index, const QVector4D & value); impl<'a> /*trait*/ QMatrix4x4_setColumn<()> for (i32, &'a QVector4D) { fn setColumn(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x49setColumnEiRK9QVector4D()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x49setColumnEiRK9QVector4D(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: bool QMatrix4x4::isIdentity(); impl /*struct*/ QMatrix4x4 { pub fn isIdentity<RetType, T: QMatrix4x4_isIdentity<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isIdentity(self); // return 1; } } pub trait QMatrix4x4_isIdentity<RetType> { fn isIdentity(self , rsthis: & QMatrix4x4) -> RetType; } // proto: bool QMatrix4x4::isIdentity(); impl<'a> /*trait*/ QMatrix4x4_isIdentity<i8> for () { fn isIdentity(self , rsthis: & QMatrix4x4) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x410isIdentityEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x410isIdentityEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QVector4D QMatrix4x4::column(int index); impl /*struct*/ QMatrix4x4 { pub fn column<RetType, T: QMatrix4x4_column<RetType>>(& self, overload_args: T) -> RetType { return overload_args.column(self); // return 1; } } pub trait QMatrix4x4_column<RetType> { fn column(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QVector4D QMatrix4x4::column(int index); impl<'a> /*trait*/ QMatrix4x4_column<QVector4D> for (i32) { fn column(self , rsthis: & QMatrix4x4) -> QVector4D { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x46columnEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK10QMatrix4x46columnEi(rsthis.qclsinst, arg0)}; let mut ret1 = QVector4D::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::setRow(int index, const QVector4D & value); impl /*struct*/ QMatrix4x4 { pub fn setRow<RetType, T: QMatrix4x4_setRow<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setRow(self); // return 1; } } pub trait QMatrix4x4_setRow<RetType> { fn setRow(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::setRow(int index, const QVector4D & value); impl<'a> /*trait*/ QMatrix4x4_setRow<()> for (i32, &'a QVector4D) { fn setRow(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x46setRowEiRK9QVector4D()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x46setRowEiRK9QVector4D(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QMatrix4x4::flipCoordinates(); impl /*struct*/ QMatrix4x4 { pub fn flipCoordinates<RetType, T: QMatrix4x4_flipCoordinates<RetType>>(& self, overload_args: T) -> RetType { return overload_args.flipCoordinates(self); // return 1; } } pub trait QMatrix4x4_flipCoordinates<RetType> { fn flipCoordinates(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::flipCoordinates(); impl<'a> /*trait*/ QMatrix4x4_flipCoordinates<()> for () { fn flipCoordinates(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x415flipCoordinatesEv()}; unsafe {C_ZN10QMatrix4x415flipCoordinatesEv(rsthis.qclsinst)}; // return 1; } } // proto: QMatrix3x3 QMatrix4x4::normalMatrix(); impl /*struct*/ QMatrix4x4 { pub fn normalMatrix<RetType, T: QMatrix4x4_normalMatrix<RetType>>(& self, overload_args: T) -> RetType { return overload_args.normalMatrix(self); // return 1; } } pub trait QMatrix4x4_normalMatrix<RetType> { fn normalMatrix(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QMatrix3x3 QMatrix4x4::normalMatrix(); impl<'a> /*trait*/ QMatrix4x4_normalMatrix<u64> for () { fn normalMatrix(self , rsthis: & QMatrix4x4) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x412normalMatrixEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x412normalMatrixEv(rsthis.qclsinst)}; return ret as u64; // 5 // return 1; } } // proto: void QMatrix4x4::viewport(float left, float bottom, float width, float height, float nearPlane, float farPlane); impl /*struct*/ QMatrix4x4 { pub fn viewport<RetType, T: QMatrix4x4_viewport<RetType>>(& self, overload_args: T) -> RetType { return overload_args.viewport(self); // return 1; } } pub trait QMatrix4x4_viewport<RetType> { fn viewport(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::viewport(float left, float bottom, float width, float height, float nearPlane, float farPlane); impl<'a> /*trait*/ QMatrix4x4_viewport<()> for (f32, f32, f32, f32, Option<f32>, Option<f32>) { fn viewport(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x48viewportEffffff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; let arg3 = self.3 as c_float; let arg4 = (if self.4.is_none() {0.0} else {self.4.unwrap()}) as c_float; let arg5 = (if self.5.is_none() {1.0} else {self.5.unwrap()}) as c_float; unsafe {C_ZN10QMatrix4x48viewportEffffff(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: void QMatrix4x4::copyDataTo(float * values); impl /*struct*/ QMatrix4x4 { pub fn copyDataTo<RetType, T: QMatrix4x4_copyDataTo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.copyDataTo(self); // return 1; } } pub trait QMatrix4x4_copyDataTo<RetType> { fn copyDataTo(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::copyDataTo(float * values); impl<'a> /*trait*/ QMatrix4x4_copyDataTo<()> for (&'a mut Vec<f32>) { fn copyDataTo(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x410copyDataToEPf()}; let arg0 = self.as_ptr() as *mut c_float; unsafe {C_ZNK10QMatrix4x410copyDataToEPf(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::QMatrix4x4(const QTransform & transform); impl<'a> /*trait*/ QMatrix4x4_new for (&'a QTransform) { fn new(self) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x4C2ERK10QTransform()}; let ctysz: c_int = unsafe{QMatrix4x4_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN10QMatrix4x4C2ERK10QTransform(arg0)}; let rsthis = QMatrix4x4{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QMatrix4x4::isAffine(); impl /*struct*/ QMatrix4x4 { pub fn isAffine<RetType, T: QMatrix4x4_isAffine<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isAffine(self); // return 1; } } pub trait QMatrix4x4_isAffine<RetType> { fn isAffine(self , rsthis: & QMatrix4x4) -> RetType; } // proto: bool QMatrix4x4::isAffine(); impl<'a> /*trait*/ QMatrix4x4_isAffine<i8> for () { fn isAffine(self , rsthis: & QMatrix4x4) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x48isAffineEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x48isAffineEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QMatrix4x4::ortho(const QRect & rect); impl<'a> /*trait*/ QMatrix4x4_ortho<()> for (&'a QRect) { fn ortho(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45orthoERK5QRect()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x45orthoERK5QRect(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::rotate(const QQuaternion & quaternion); impl /*struct*/ QMatrix4x4 { pub fn rotate<RetType, T: QMatrix4x4_rotate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rotate(self); // return 1; } } pub trait QMatrix4x4_rotate<RetType> { fn rotate(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::rotate(const QQuaternion & quaternion); impl<'a> /*trait*/ QMatrix4x4_rotate<()> for (&'a QQuaternion) { fn rotate(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x46rotateERK11QQuaternion()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x46rotateERK11QQuaternion(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::QMatrix4x4(const QMatrix & matrix); impl<'a> /*trait*/ QMatrix4x4_new for (&'a QMatrix) { fn new(self) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x4C2ERK7QMatrix()}; let ctysz: c_int = unsafe{QMatrix4x4_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN10QMatrix4x4C2ERK7QMatrix(arg0)}; let rsthis = QMatrix4x4{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QMatrix4x4::perspective(float verticalAngle, float aspectRatio, float nearPlane, float farPlane); impl /*struct*/ QMatrix4x4 { pub fn perspective<RetType, T: QMatrix4x4_perspective<RetType>>(& self, overload_args: T) -> RetType { return overload_args.perspective(self); // return 1; } } pub trait QMatrix4x4_perspective<RetType> { fn perspective(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::perspective(float verticalAngle, float aspectRatio, float nearPlane, float farPlane); impl<'a> /*trait*/ QMatrix4x4_perspective<()> for (f32, f32, f32, f32) { fn perspective(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x411perspectiveEffff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; let arg3 = self.3 as c_float; unsafe {C_ZN10QMatrix4x411perspectiveEffff(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: void QMatrix4x4::translate(const QVector3D & vector); impl<'a> /*trait*/ QMatrix4x4_translate<()> for (&'a QVector3D) { fn translate(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x49translateERK9QVector3D()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x49translateERK9QVector3D(rsthis.qclsinst, arg0)}; // return 1; } } // proto: double QMatrix4x4::determinant(); impl /*struct*/ QMatrix4x4 { pub fn determinant<RetType, T: QMatrix4x4_determinant<RetType>>(& self, overload_args: T) -> RetType { return overload_args.determinant(self); // return 1; } } pub trait QMatrix4x4_determinant<RetType> { fn determinant(self , rsthis: & QMatrix4x4) -> RetType; } // proto: double QMatrix4x4::determinant(); impl<'a> /*trait*/ QMatrix4x4_determinant<f64> for () { fn determinant(self , rsthis: & QMatrix4x4) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x411determinantEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x411determinantEv(rsthis.qclsinst)}; return ret as f64; // 1 // return 1; } } // proto: void QMatrix4x4::scale(float x, float y, float z); impl<'a> /*trait*/ QMatrix4x4_scale<()> for (f32, f32, f32) { fn scale(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45scaleEfff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; unsafe {C_ZN10QMatrix4x45scaleEfff(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QMatrix4x4::frustum(float left, float right, float bottom, float top, float nearPlane, float farPlane); impl /*struct*/ QMatrix4x4 { pub fn frustum<RetType, T: QMatrix4x4_frustum<RetType>>(& self, overload_args: T) -> RetType { return overload_args.frustum(self); // return 1; } } pub trait QMatrix4x4_frustum<RetType> { fn frustum(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::frustum(float left, float right, float bottom, float top, float nearPlane, float farPlane); impl<'a> /*trait*/ QMatrix4x4_frustum<()> for (f32, f32, f32, f32, f32, f32) { fn frustum(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x47frustumEffffff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; let arg3 = self.3 as c_float; let arg4 = self.4 as c_float; let arg5 = self.5 as c_float; unsafe {C_ZN10QMatrix4x47frustumEffffff(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)}; // return 1; } } // proto: QPoint QMatrix4x4::map(const QPoint & point); impl /*struct*/ QMatrix4x4 { pub fn map<RetType, T: QMatrix4x4_map<RetType>>(& self, overload_args: T) -> RetType { return overload_args.map(self); // return 1; } } pub trait QMatrix4x4_map<RetType> { fn map(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QPoint QMatrix4x4::map(const QPoint & point); impl<'a> /*trait*/ QMatrix4x4_map<QPoint> for (&'a QPoint) { fn map(self , rsthis: & QMatrix4x4) -> QPoint { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x43mapERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x43mapERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QPoint::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::optimize(); impl /*struct*/ QMatrix4x4 { pub fn optimize<RetType, T: QMatrix4x4_optimize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.optimize(self); // return 1; } } pub trait QMatrix4x4_optimize<RetType> { fn optimize(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::optimize(); impl<'a> /*trait*/ QMatrix4x4_optimize<()> for () { fn optimize(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x48optimizeEv()}; unsafe {C_ZN10QMatrix4x48optimizeEv(rsthis.qclsinst)}; // return 1; } } // proto: void QMatrix4x4::QMatrix4x4(const float * values); impl<'a> /*trait*/ QMatrix4x4_new for (&'a Vec<f32>) { fn new(self) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x4C2EPKf()}; let ctysz: c_int = unsafe{QMatrix4x4_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.as_ptr() as *mut c_float; let qthis: u64 = unsafe {C_ZN10QMatrix4x4C2EPKf(arg0)}; let rsthis = QMatrix4x4{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QMatrix4x4::translate(float x, float y); impl<'a> /*trait*/ QMatrix4x4_translate<()> for (f32, f32) { fn translate(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x49translateEff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; unsafe {C_ZN10QMatrix4x49translateEff(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QMatrix4x4::setToIdentity(); impl /*struct*/ QMatrix4x4 { pub fn setToIdentity<RetType, T: QMatrix4x4_setToIdentity<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setToIdentity(self); // return 1; } } pub trait QMatrix4x4_setToIdentity<RetType> { fn setToIdentity(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::setToIdentity(); impl<'a> /*trait*/ QMatrix4x4_setToIdentity<()> for () { fn setToIdentity(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x413setToIdentityEv()}; unsafe {C_ZN10QMatrix4x413setToIdentityEv(rsthis.qclsinst)}; // return 1; } } // proto: QRect QMatrix4x4::mapRect(const QRect & rect); impl<'a> /*trait*/ QMatrix4x4_mapRect<QRect> for (&'a QRect) { fn mapRect(self , rsthis: & QMatrix4x4) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x47mapRectERK5QRect()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x47mapRectERK5QRect(rsthis.qclsinst, arg0)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::scale(float x, float y); impl<'a> /*trait*/ QMatrix4x4_scale<()> for (f32, f32) { fn scale(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45scaleEff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; unsafe {C_ZN10QMatrix4x45scaleEff(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QMatrix4x4::QMatrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44); impl<'a> /*trait*/ QMatrix4x4_new for (f32, f32, f32, f32, f32, f32, f32, f32, f32, f32, f32, f32, f32, f32, f32, f32) { fn new(self) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x4C2Effffffffffffffff()}; let ctysz: c_int = unsafe{QMatrix4x4_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; let arg3 = self.3 as c_float; let arg4 = self.4 as c_float; let arg5 = self.5 as c_float; let arg6 = self.6 as c_float; let arg7 = self.7 as c_float; let arg8 = self.8 as c_float; let arg9 = self.9 as c_float; let arg10 = self.10 as c_float; let arg11 = self.11 as c_float; let arg12 = self.12 as c_float; let arg13 = self.13 as c_float; let arg14 = self.14 as c_float; let arg15 = self.15 as c_float; let qthis: u64 = unsafe {C_ZN10QMatrix4x4C2Effffffffffffffff(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15)}; let rsthis = QMatrix4x4{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QVector3D QMatrix4x4::map(const QVector3D & point); impl<'a> /*trait*/ QMatrix4x4_map<QVector3D> for (&'a QVector3D) { fn map(self , rsthis: & QMatrix4x4) -> QVector3D { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x43mapERK9QVector3D()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x43mapERK9QVector3D(rsthis.qclsinst, arg0)}; let mut ret1 = QVector3D::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::lookAt(const QVector3D & eye, const QVector3D & center, const QVector3D & up); impl /*struct*/ QMatrix4x4 { pub fn lookAt<RetType, T: QMatrix4x4_lookAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.lookAt(self); // return 1; } } pub trait QMatrix4x4_lookAt<RetType> { fn lookAt(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::lookAt(const QVector3D & eye, const QVector3D & center, const QVector3D & up); impl<'a> /*trait*/ QMatrix4x4_lookAt<()> for (&'a QVector3D, &'a QVector3D, &'a QVector3D) { fn lookAt(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x46lookAtERK9QVector3DS2_S2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x46lookAtERK9QVector3DS2_S2_(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QMatrix4x4::ortho(const QRectF & rect); impl<'a> /*trait*/ QMatrix4x4_ortho<()> for (&'a QRectF) { fn ortho(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45orthoERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x45orthoERK6QRectF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::viewport(const QRectF & rect); impl<'a> /*trait*/ QMatrix4x4_viewport<()> for (&'a QRectF) { fn viewport(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x48viewportERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x48viewportERK6QRectF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::rotate(float angle, float x, float y, float z); impl<'a> /*trait*/ QMatrix4x4_rotate<()> for (f32, f32, f32, Option<f32>) { fn rotate(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x46rotateEffff()}; let arg0 = self.0 as c_float; let arg1 = self.1 as c_float; let arg2 = self.2 as c_float; let arg3 = (if self.3.is_none() {0.0} else {self.3.unwrap()}) as c_float; unsafe {C_ZN10QMatrix4x46rotateEffff(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: void QMatrix4x4::fill(float value); impl /*struct*/ QMatrix4x4 { pub fn fill<RetType, T: QMatrix4x4_fill<RetType>>(& self, overload_args: T) -> RetType { return overload_args.fill(self); // return 1; } } pub trait QMatrix4x4_fill<RetType> { fn fill(self , rsthis: & QMatrix4x4) -> RetType; } // proto: void QMatrix4x4::fill(float value); impl<'a> /*trait*/ QMatrix4x4_fill<()> for (f32) { fn fill(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x44fillEf()}; let arg0 = self as c_float; unsafe {C_ZN10QMatrix4x44fillEf(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QMatrix4x4::QMatrix4x4(const float * values, int cols, int rows); impl<'a> /*trait*/ QMatrix4x4_new for (&'a Vec<f32>, i32, i32) { fn new(self) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x4C2EPKfii()}; let ctysz: c_int = unsafe{QMatrix4x4_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.as_ptr() as *mut c_float; let arg1 = self.1 as c_int; let arg2 = self.2 as c_int; let qthis: u64 = unsafe {C_ZN10QMatrix4x4C2EPKfii(arg0, arg1, arg2)}; let rsthis = QMatrix4x4{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QTransform QMatrix4x4::toTransform(float distanceToPlane); impl<'a> /*trait*/ QMatrix4x4_toTransform<QTransform> for (f32) { fn toTransform(self , rsthis: & QMatrix4x4) -> QTransform { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x411toTransformEf()}; let arg0 = self as c_float; let mut ret = unsafe {C_ZNK10QMatrix4x411toTransformEf(rsthis.qclsinst, arg0)}; let mut ret1 = QTransform::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMatrix4x4 QMatrix4x4::transposed(); impl /*struct*/ QMatrix4x4 { pub fn transposed<RetType, T: QMatrix4x4_transposed<RetType>>(& self, overload_args: T) -> RetType { return overload_args.transposed(self); // return 1; } } pub trait QMatrix4x4_transposed<RetType> { fn transposed(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QMatrix4x4 QMatrix4x4::transposed(); impl<'a> /*trait*/ QMatrix4x4_transposed<QMatrix4x4> for () { fn transposed(self , rsthis: & QMatrix4x4) -> QMatrix4x4 { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x410transposedEv()}; let mut ret = unsafe {C_ZNK10QMatrix4x410transposedEv(rsthis.qclsinst)}; let mut ret1 = QMatrix4x4::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QPointF QMatrix4x4::map(const QPointF & point); impl<'a> /*trait*/ QMatrix4x4_map<QPointF> for (&'a QPointF) { fn map(self , rsthis: & QMatrix4x4) -> QPointF { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x43mapERK7QPointF()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x43mapERK7QPointF(rsthis.qclsinst, arg0)}; let mut ret1 = QPointF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::scale(float factor); impl<'a> /*trait*/ QMatrix4x4_scale<()> for (f32) { fn scale(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x45scaleEf()}; let arg0 = self as c_float; unsafe {C_ZN10QMatrix4x45scaleEf(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QVector4D QMatrix4x4::row(int index); impl /*struct*/ QMatrix4x4 { pub fn row<RetType, T: QMatrix4x4_row<RetType>>(& self, overload_args: T) -> RetType { return overload_args.row(self); // return 1; } } pub trait QMatrix4x4_row<RetType> { fn row(self , rsthis: & QMatrix4x4) -> RetType; } // proto: QVector4D QMatrix4x4::row(int index); impl<'a> /*trait*/ QMatrix4x4_row<QVector4D> for (i32) { fn row(self , rsthis: & QMatrix4x4) -> QVector4D { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x43rowEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK10QMatrix4x43rowEi(rsthis.qclsinst, arg0)}; let mut ret1 = QVector4D::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMatrix4x4::rotate(float angle, const QVector3D & vector); impl<'a> /*trait*/ QMatrix4x4_rotate<()> for (f32, &'a QVector3D) { fn rotate(self , rsthis: & QMatrix4x4) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZN10QMatrix4x46rotateEfRK9QVector3D()}; let arg0 = self.0 as c_float; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN10QMatrix4x46rotateEfRK9QVector3D(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QVector4D QMatrix4x4::map(const QVector4D & point); impl<'a> /*trait*/ QMatrix4x4_map<QVector4D> for (&'a QVector4D) { fn map(self , rsthis: & QMatrix4x4) -> QVector4D { // let qthis: *mut c_void = unsafe{calloc(1, 68)}; // unsafe{_ZNK10QMatrix4x43mapERK9QVector4D()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK10QMatrix4x43mapERK9QVector4D(rsthis.qclsinst, arg0)}; let mut ret1 = QVector4D::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
use biofile::bed::paired_end_collator::PairedEndCollator; use clap::{clap_app, Arg}; use program_flow::{ argparse::{ extract_boolean_flag, extract_numeric_arg, extract_optional_numeric_arg, extract_str_arg, }, debug_eprint_named_vars, eprint_named_vars, OrExit, }; fn main() { let mut app = clap_app!(collate_paired_end => (about: "Extracts paired-end reads and generate a single interval from \ each pair of reads.") ); app = app .arg( Arg::with_name("bed_path") .long("bed") .short("b") .takes_value(true) .required(true) .help("path to the bed file containing the paired-end reads"), ) .arg( Arg::with_name("out_path") .long("out-path") .short("o") .takes_value(true) .required(true) .help("output file path."), ) .arg( Arg::with_name("left_offset") .long("left") .short("l") .takes_value(true) .required(true) .long_help( "Ater finding the mid-point M of each paired-end reads, \ the start coordinate for the single interval generated in \ the output will be M - right_offset. Note that in the BED \ format the start coordinate 0-based inclusive.", ), ) .arg( Arg::with_name("right_offset") .long("right") .short("r") .takes_value(true) .required(true) .long_help( "Ater finding the mid-point M of each paired-end reads, \ the end coordinate for the single interval generated in the \ output will be M + right_offset. Note that in the BED \ format the end coordinate is 0-based exclusive.", ), ) .arg( Arg::with_name("min_separation") .long("min-separation") .short("x") .takes_value(true) .long_help( "If provided, will ignore pairs where the distance between \ the smallest and the largest coordinate is less than \ min_separation" ) ) .arg( Arg::with_name("max_separation") .long("max-separation") .short("y") .takes_value(true) .long_help( "If provided, will ignore pairs where the distance between \ the smallest and the largest coordinate is larger than \ max_separation" ) ) .arg( Arg::with_name("debug") .long("debug") .help("outputs PCR duplicate reads into stderr") ); let matches = app.get_matches(); let bed_path = extract_str_arg(&matches, "bed_path"); let out_path = extract_str_arg(&matches, "out_path"); let left_offset = extract_numeric_arg(&matches, "left_offset") .unwrap_or_exit(Some("failed to extract the left offset argument")); let right_offset = extract_numeric_arg(&matches, "right_offset") .unwrap_or_exit(Some("failed to extract the right offset argument")); let min_separation = extract_optional_numeric_arg::<i64>(&matches, "min_separation") .unwrap_or_exit(Some( "failed to extract the min_separation argument", )); let max_separation = extract_optional_numeric_arg::<i64>(&matches, "max_separation") .unwrap_or_exit(Some( "failed to extract the max_separation argument", )); let debug = extract_boolean_flag(&matches, "debug"); eprint_named_vars!(bed_path, out_path, left_offset, right_offset, debug); debug_eprint_named_vars!(min_separation, max_separation); let collator = PairedEndCollator::new(&bed_path); let result = collator .write( &out_path, left_offset, right_offset, min_separation, max_separation, debug, ) .unwrap_or_exit(Some( "failed to collate the paired-end reads bed file", )); println!( "Paired-end reads basepair distance histogram:\n{}", result.distance_histogram ); println!( "{}", format!( "number of conflicting reads: {}", result.num_conflicting_reads ) ); println!( "{}", format!( "number of num_overlapping pairs: {}", result.num_overlapping_pairs ) ); println!( "{}", format!("number of PCR duplicates: {}", result.num_pcr_duplicates) ); }
use std::{cmp::Reverse, collections::BTreeSet}; use proconio::input; use segment_tree::SegmentTree; fn main() { input! { n: usize, a: [i64; n], }; const INF: i64 = std::i64::MAX / 2; // dp[i] := max(dp[i - 1], max(dp[j - 1] + a[i] - a[j]), max(dp[j - 1] + a[j] - a[i])) let mut dp = vec![-INF; n]; dp[0] = 0; // seg1[j] := dp[j - 1] - a[j] let mut seg1 = SegmentTree::new(n, -INF, |x, y| *x.max(y)); seg1.update(0, -a[0]); // seg1[j] := dp[j - 1] + a[j] let mut seg2 = SegmentTree::new(n, -INF, |x, y| *x.max(y)); seg2.update(0, a[0]); let mut set1 = BTreeSet::new(); let mut set2 = BTreeSet::new(); for i in 1..n { dp[i] = dp[i].max(dp[i - 1]); let j = set1 .range((a[i], Reverse(0))..) .next() .copied() .map(|(_, Reverse(j))| j + 1) .unwrap_or(0); dp[i] = dp[i].max(seg1.fold(j..i) + a[i]); let j = set2 .range(..=(a[i], n)) .last() .copied() .map(|(_, j)| j + 1) .unwrap_or(0); dp[i] = dp[i].max(seg2.fold(j..i) - a[i]); seg1.update(i, if i == 0 { -a[i] } else { dp[i - 1] - a[i] }); seg2.update(i, if i == 0 { a[i] } else { dp[i - 1] + a[i] }); set1.insert((a[i], Reverse(i))); set2.insert((a[i], i)); } println!("{}", dp[n - 1]); }
//! JIT compilation. use crate::instantiate::SetupError; use crate::object::{build_object, ObjectUnwindInfo}; use cranelift_codegen::ir; use object::write::Object; use wasmtime_debug::{emit_dwarf, DebugInfoData, DwarfSection}; use wasmtime_environ::entity::{EntityRef, PrimaryMap}; use wasmtime_environ::isa::{unwind::UnwindInfo, TargetFrontendConfig, TargetIsa}; use wasmtime_environ::wasm::{DefinedFuncIndex, DefinedMemoryIndex, MemoryIndex}; use wasmtime_environ::{ CacheConfig, Compiler as _C, Module, ModuleAddressMap, ModuleMemoryOffset, ModuleTranslation, ModuleVmctxInfo, StackMaps, Traps, Tunables, VMOffsets, ValueLabelsRanges, }; /// Select which kind of compilation to use. #[derive(Copy, Clone, Debug)] pub enum CompilationStrategy { /// Let Wasmtime pick the strategy. Auto, /// Compile all functions with Cranelift. Cranelift, /// Compile all functions with Lightbeam. #[cfg(feature = "lightbeam")] Lightbeam, } /// A WebAssembly code JIT compiler. /// /// A `Compiler` instance owns the executable memory that it allocates. /// /// TODO: Evolve this to support streaming rather than requiring a `&[u8]` /// containing a whole wasm module at once. /// /// TODO: Consider using cranelift-module. pub struct Compiler { isa: Box<dyn TargetIsa>, strategy: CompilationStrategy, cache_config: CacheConfig, tunables: Tunables, } impl Compiler { /// Construct a new `Compiler`. pub fn new( isa: Box<dyn TargetIsa>, strategy: CompilationStrategy, cache_config: CacheConfig, tunables: Tunables, ) -> Self { Self { isa, strategy, cache_config, tunables, } } } fn _assert_compiler_send_sync() { fn _assert<T: Send + Sync>() {} _assert::<Compiler>(); } fn transform_dwarf_data( isa: &dyn TargetIsa, module: &Module, debug_data: DebugInfoData, address_transform: &ModuleAddressMap, value_ranges: &ValueLabelsRanges, stack_slots: PrimaryMap<DefinedFuncIndex, ir::StackSlots>, unwind_info: PrimaryMap<DefinedFuncIndex, &Option<UnwindInfo>>, ) -> Result<Vec<DwarfSection>, SetupError> { let target_config = isa.frontend_config(); let ofs = VMOffsets::new(target_config.pointer_bytes(), &module.local); let module_vmctx_info = { ModuleVmctxInfo { memory_offset: if ofs.num_imported_memories > 0 { ModuleMemoryOffset::Imported(ofs.vmctx_vmmemory_import(MemoryIndex::new(0))) } else if ofs.num_defined_memories > 0 { ModuleMemoryOffset::Defined( ofs.vmctx_vmmemory_definition_base(DefinedMemoryIndex::new(0)), ) } else { ModuleMemoryOffset::None }, stack_slots, } }; emit_dwarf( isa, &debug_data, &address_transform, &module_vmctx_info, &value_ranges, &unwind_info, ) .map_err(SetupError::DebugInfo) } #[allow(missing_docs)] pub struct Compilation { pub obj: Object, pub unwind_info: Vec<ObjectUnwindInfo>, pub traps: Traps, pub stack_maps: StackMaps, pub address_transform: ModuleAddressMap, } impl Compiler { /// Return the isa. pub fn isa(&self) -> &dyn TargetIsa { self.isa.as_ref() } /// Return the target's frontend configuration settings. pub fn frontend_config(&self) -> TargetFrontendConfig { self.isa.frontend_config() } /// Return the tunables in use by this engine. pub fn tunables(&self) -> &Tunables { &self.tunables } /// Compile the given function bodies. pub(crate) fn compile<'data>( &self, translation: &ModuleTranslation, debug_data: Option<DebugInfoData>, ) -> Result<Compilation, SetupError> { let ( compilation, relocations, address_transform, value_ranges, stack_slots, traps, stack_maps, ) = match self.strategy { // For now, interpret `Auto` as `Cranelift` since that's the most stable // implementation. CompilationStrategy::Auto | CompilationStrategy::Cranelift => { wasmtime_environ::cranelift::Cranelift::compile_module( translation, &*self.isa, &self.cache_config, ) } #[cfg(feature = "lightbeam")] CompilationStrategy::Lightbeam => { wasmtime_environ::lightbeam::Lightbeam::compile_module( translation, &*self.isa, &self.cache_config, ) } } .map_err(SetupError::Compile)?; let dwarf_sections = if debug_data.is_some() && !compilation.is_empty() { let unwind_info = compilation.unwind_info(); transform_dwarf_data( &*self.isa, &translation.module, debug_data.unwrap(), &address_transform, &value_ranges, stack_slots, unwind_info, )? } else { vec![] }; let (obj, unwind_info) = build_object( &*self.isa, &translation.module, compilation, relocations, dwarf_sections, )?; Ok(Compilation { obj, unwind_info, traps, stack_maps, address_transform, }) } }
pub type IRDPSRAPIApplication = *mut ::core::ffi::c_void; pub type IRDPSRAPIApplicationFilter = *mut ::core::ffi::c_void; pub type IRDPSRAPIApplicationList = *mut ::core::ffi::c_void; pub type IRDPSRAPIAttendee = *mut ::core::ffi::c_void; pub type IRDPSRAPIAttendeeDisconnectInfo = *mut ::core::ffi::c_void; pub type IRDPSRAPIAttendeeManager = *mut ::core::ffi::c_void; pub type IRDPSRAPIAudioStream = *mut ::core::ffi::c_void; pub type IRDPSRAPIClipboardUseEvents = *mut ::core::ffi::c_void; pub type IRDPSRAPIDebug = *mut ::core::ffi::c_void; pub type IRDPSRAPIFrameBuffer = *mut ::core::ffi::c_void; pub type IRDPSRAPIInvitation = *mut ::core::ffi::c_void; pub type IRDPSRAPIInvitationManager = *mut ::core::ffi::c_void; pub type IRDPSRAPIPerfCounterLogger = *mut ::core::ffi::c_void; pub type IRDPSRAPIPerfCounterLoggingManager = *mut ::core::ffi::c_void; pub type IRDPSRAPISessionProperties = *mut ::core::ffi::c_void; pub type IRDPSRAPISharingSession = *mut ::core::ffi::c_void; pub type IRDPSRAPISharingSession2 = *mut ::core::ffi::c_void; pub type IRDPSRAPITcpConnectionInfo = *mut ::core::ffi::c_void; pub type IRDPSRAPITransportStream = *mut ::core::ffi::c_void; pub type IRDPSRAPITransportStreamBuffer = *mut ::core::ffi::c_void; pub type IRDPSRAPITransportStreamEvents = *mut ::core::ffi::c_void; pub type IRDPSRAPIViewer = *mut ::core::ffi::c_void; pub type IRDPSRAPIVirtualChannel = *mut ::core::ffi::c_void; pub type IRDPSRAPIVirtualChannelManager = *mut ::core::ffi::c_void; pub type IRDPSRAPIWindow = *mut ::core::ffi::c_void; pub type IRDPSRAPIWindowList = *mut ::core::ffi::c_void; pub type IRDPViewerInputSink = *mut ::core::ffi::c_void; pub type _IRDPSessionEvents = *mut ::core::ffi::c_void; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED: u32 = 340u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_APPFILTER_UPDATE: u32 = 322u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_APPLICATION_CLOSE: u32 = 317u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_APPLICATION_OPEN: u32 = 316u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_APPLICATION_UPDATE: u32 = 318u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_CONNECTED: u32 = 301u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_DISCONNECTED: u32 = 302u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_UPDATE: u32 = 303u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_CTRLLEVEL_CHANGE_REQUEST: u32 = 309u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_CTRLLEVEL_CHANGE_RESPONSE: u32 = 338u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_ERROR: u32 = 304u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_FOCUSRELEASED: u32 = 324u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_PAUSED: u32 = 310u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_RESUMED: u32 = 311u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_SHARED_DESKTOP_SETTINGS_CHANGED: u32 = 325u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_SHARED_RECT_CHANGED: u32 = 323u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_STREAM_CLOSED: u32 = 634u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_STREAM_DATARECEIVED: u32 = 633u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_STREAM_SENDCOMPLETED: u32 = 632u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIEWER_AUTHENTICATED: u32 = 307u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTED: u32 = 305u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTFAILED: u32 = 308u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIEWER_DISCONNECTED: u32 = 306u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_DATARECEIVED: u32 = 314u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_JOIN: u32 = 312u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_LEAVE: u32 = 313u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_SENDCOMPLETED: u32 = 315u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_WINDOW_CLOSE: u32 = 320u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_WINDOW_OPEN: u32 = 319u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_ON_WINDOW_UPDATE: u32 = 321u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_VIEW_MOUSE_BUTTON_RECEIVED: u32 = 700u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_VIEW_MOUSE_MOVE_RECEIVED: u32 = 701u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_EVENT_VIEW_MOUSE_WHEEL_RECEIVED: u32 = 702u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_ADD_TOUCH_INPUT: u32 = 125u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_BEGIN_TOUCH_FRAME: u32 = 124u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_CLOSE: u32 = 101u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_CONNECTTOCLIENT: u32 = 117u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_CONNECTUSINGTRANSPORTSTREAM: u32 = 127u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_CREATE_INVITATION: u32 = 107u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_END_TOUCH_FRAME: u32 = 126u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_GETFRAMEBUFFERBITS: u32 = 149u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_GETSHAREDRECT: u32 = 103u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_OPEN: u32 = 100u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_PAUSE: u32 = 112u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_REQUEST_COLOR_DEPTH_CHANGE: u32 = 115u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_REQUEST_CONTROL: u32 = 108u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_RESUME: u32 = 113u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SENDCONTROLLEVELCHANGERESPONSE: u32 = 148u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SEND_KEYBOARD_EVENT: u32 = 122u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SEND_MOUSE_BUTTON_EVENT: u32 = 119u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SEND_MOUSE_MOVE_EVENT: u32 = 120u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SEND_MOUSE_WHEEL_EVENT: u32 = 121u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SEND_SYNC_EVENT: u32 = 123u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SETSHAREDRECT: u32 = 102u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SET_RENDERING_SURFACE: u32 = 118u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_SHOW_WINDOW: u32 = 114u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STARTREVCONNECTLISTENER: u32 = 116u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STREAMCLOSE: u32 = 426u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STREAMOPEN: u32 = 425u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STREAMREADDATA: u32 = 424u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STREAMSENDDATA: u32 = 423u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STREAM_ALLOCBUFFER: u32 = 421u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_STREAM_FREEBUFFER: u32 = 422u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_TERMINATE_CONNECTION: u32 = 106u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_VIEWERCONNECT: u32 = 104u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_VIEWERDISCONNECT: u32 = 105u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_VIRTUAL_CHANNEL_CREATE: u32 = 109u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_VIRTUAL_CHANNEL_SEND_DATA: u32 = 110u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_METHOD_VIRTUAL_CHANNEL_SET_ACCESS: u32 = 111u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPFILTERENABLED: u32 = 219u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPFILTER_ENABLED: u32 = 218u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPFLAGS: u32 = 223u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPLICATION: u32 = 211u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPLICATION_FILTER: u32 = 215u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPLICATION_LIST: u32 = 217u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_APPNAME: u32 = 214u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_ATTENDEELIMIT: u32 = 235u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_ATTENDEES: u32 = 203u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_ATTENDEE_FLAGS: u32 = 230u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_CHANNELMANAGER: u32 = 206u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_CODE: u32 = 241u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_CONINFO: u32 = 231u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_CONNECTION_STRING: u32 = 232u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_COUNT: u32 = 244u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_CTRL_LEVEL: u32 = 242u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_DBG_CLX_CMDLINE: u32 = 222u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_DISCONNECTED_STRING: u32 = 237u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_DISPIDVALUE: u32 = 200u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_FRAMEBUFFER: u32 = 254u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_FRAMEBUFFER_BPP: u32 = 253u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_FRAMEBUFFER_HEIGHT: u32 = 251u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_FRAMEBUFFER_WIDTH: u32 = 252u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_GROUP_NAME: u32 = 233u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_ID: u32 = 201u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_INVITATION: u32 = 205u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_INVITATIONITEM: u32 = 221u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_INVITATIONS: u32 = 204u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_LOCAL_IP: u32 = 227u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_LOCAL_PORT: u32 = 226u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_PASSWORD: u32 = 234u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_PEER_IP: u32 = 229u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_PEER_PORT: u32 = 228u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_PROTOCOL_TYPE: u32 = 225u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_REASON: u32 = 240u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_REMOTENAME: u32 = 243u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_REVOKED: u32 = 236u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_SESSION_COLORDEPTH: u32 = 239u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_SESSION_PROPERTIES: u32 = 202u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_SHARED: u32 = 220u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_CONTEXT: u32 = 560u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_FLAGS: u32 = 561u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_PAYLOADOFFSET: u32 = 559u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_PAYLOADSIZE: u32 = 558u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_STORAGE: u32 = 555u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_STREAMBUFFER_STORESIZE: u32 = 562u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_USESMARTSIZING: u32 = 238u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_VIRTUAL_CHANNEL_GETFLAGS: u32 = 208u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_VIRTUAL_CHANNEL_GETNAME: u32 = 207u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_VIRTUAL_CHANNEL_GETPRIORITY: u32 = 209u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_WINDOWID: u32 = 210u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_WINDOWNAME: u32 = 213u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_WINDOWSHARED: u32 = 212u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_WINDOW_LIST: u32 = 216u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const DISPID_RDPSRAPI_PROP_WNDFLAGS: u32 = 224u32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIApplication: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc116a484_4b25_4b9f_8a54_b934b06e57fa); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIApplicationFilter: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xe35ace89_c7e8_427e_a4f9_b9da072826bd); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIApplicationList: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x9e31c815_7433_4876_97fb_ed59fe2baa22); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIAttendee: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x74f93bb5_755f_488e_8a29_2390108aef55); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIAttendeeDisconnectInfo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb47d7250_5bdb_405d_b487_caad9c56f4f8); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIAttendeeManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xd7b13a01_f7d4_42a6_8595_12fc8c24e851); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIFrameBuffer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xa4f66bcc_538e_4101_951d_30847adb5101); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIInvitation: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x49174dc6_0731_4b5e_8ee1_83a63d3868fa); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIInvitationManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x53d9c9db_75ab_4271_948a_4c4eb36a8f2b); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPISessionProperties: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xdd7594ff_ea2a_4c06_8fdf_132de48b6510); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPITcpConnectionInfo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xbe49db3f_ebb6_4278_8ce0_d5455833eaee); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIWindow: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x03cf46db_ce45_4d36_86ed_ed28b74398bf); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPIWindowList: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x9c21e2b8_5dd4_42cc_81ba_1c099852e6fa); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSession: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x9b78f0e6_3e05_4a5b_b2e8_e743a8956b65); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPTransportStreamBuffer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x8d4a1c69_f17f_4549_a699_761c6e6b5c0a); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPTransportStreamEvents: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x31e3ab20_5350_483f_9dc6_6748665efdeb); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPViewer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x32be5ed2_5c86_480f_a914_0ff8885a1b3f); #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type ATTENDEE_DISCONNECT_REASON = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const ATTENDEE_DISCONNECT_REASON_MIN: ATTENDEE_DISCONNECT_REASON = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const ATTENDEE_DISCONNECT_REASON_APP: ATTENDEE_DISCONNECT_REASON = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const ATTENDEE_DISCONNECT_REASON_ERR: ATTENDEE_DISCONNECT_REASON = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const ATTENDEE_DISCONNECT_REASON_CLI: ATTENDEE_DISCONNECT_REASON = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const ATTENDEE_DISCONNECT_REASON_MAX: ATTENDEE_DISCONNECT_REASON = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type CHANNEL_ACCESS_ENUM = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_ACCESS_ENUM_NONE: CHANNEL_ACCESS_ENUM = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_ACCESS_ENUM_SENDRECEIVE: CHANNEL_ACCESS_ENUM = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type CHANNEL_FLAGS = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_FLAGS_LEGACY: CHANNEL_FLAGS = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_FLAGS_UNCOMPRESSED: CHANNEL_FLAGS = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_FLAGS_DYNAMIC: CHANNEL_FLAGS = 4i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type CHANNEL_PRIORITY = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_PRIORITY_LO: CHANNEL_PRIORITY = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_PRIORITY_MED: CHANNEL_PRIORITY = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CHANNEL_PRIORITY_HI: CHANNEL_PRIORITY = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type CTRL_LEVEL = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_MIN: CTRL_LEVEL = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_INVALID: CTRL_LEVEL = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_NONE: CTRL_LEVEL = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_VIEW: CTRL_LEVEL = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_INTERACTIVE: CTRL_LEVEL = 3i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_REQCTRL_VIEW: CTRL_LEVEL = 4i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_REQCTRL_INTERACTIVE: CTRL_LEVEL = 5i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CTRL_LEVEL_MAX: CTRL_LEVEL = 5i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPENCOMAPI_ATTENDEE_FLAGS = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const ATTENDEE_FLAGS_LOCAL: RDPENCOMAPI_ATTENDEE_FLAGS = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPENCOMAPI_CONSTANTS = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_MAX_CHANNEL_MESSAGE_SIZE: RDPENCOMAPI_CONSTANTS = 1024i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_MAX_CHANNEL_NAME_LEN: RDPENCOMAPI_CONSTANTS = 8i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_MAX_LEGACY_CHANNEL_MESSAGE_SIZE: RDPENCOMAPI_CONSTANTS = 409600i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_ATTENDEE_ID_EVERYONE: RDPENCOMAPI_CONSTANTS = -1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_ATTENDEE_ID_HOST: RDPENCOMAPI_CONSTANTS = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_CONN_INTERVAL: RDPENCOMAPI_CONSTANTS = 50i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const CONST_ATTENDEE_ID_DEFAULT: RDPENCOMAPI_CONSTANTS = -1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPSRAPI_APP_FLAGS = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const APP_FLAG_PRIVILEGED: RDPSRAPI_APP_FLAGS = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPSRAPI_KBD_CODE_TYPE = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_KBD_CODE_SCANCODE: RDPSRAPI_KBD_CODE_TYPE = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_KBD_CODE_UNICODE: RDPSRAPI_KBD_CODE_TYPE = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPSRAPI_KBD_SYNC_FLAG = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_KBD_SYNC_FLAG_SCROLL_LOCK: RDPSRAPI_KBD_SYNC_FLAG = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_KBD_SYNC_FLAG_NUM_LOCK: RDPSRAPI_KBD_SYNC_FLAG = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_KBD_SYNC_FLAG_CAPS_LOCK: RDPSRAPI_KBD_SYNC_FLAG = 4i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_KBD_SYNC_FLAG_KANA_LOCK: RDPSRAPI_KBD_SYNC_FLAG = 8i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPSRAPI_MOUSE_BUTTON_TYPE = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_MOUSE_BUTTON_BUTTON1: RDPSRAPI_MOUSE_BUTTON_TYPE = 0i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_MOUSE_BUTTON_BUTTON2: RDPSRAPI_MOUSE_BUTTON_TYPE = 1i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_MOUSE_BUTTON_BUTTON3: RDPSRAPI_MOUSE_BUTTON_TYPE = 2i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_MOUSE_BUTTON_XBUTTON1: RDPSRAPI_MOUSE_BUTTON_TYPE = 3i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_MOUSE_BUTTON_XBUTTON2: RDPSRAPI_MOUSE_BUTTON_TYPE = 4i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const RDPSRAPI_MOUSE_BUTTON_XBUTTON3: RDPSRAPI_MOUSE_BUTTON_TYPE = 5i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub type RDPSRAPI_WND_FLAGS = i32; #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub const WND_FLAG_PRIVILEGED: RDPSRAPI_WND_FLAGS = 1i32; #[repr(C)] #[doc = "*Required features: `\"Win32_System_DesktopSharing\"`*"] pub struct __ReferenceRemainingTypes__ { pub __ctrlLevel__: CTRL_LEVEL, pub __attendeeDisconnectReason__: ATTENDEE_DISCONNECT_REASON, pub __channelPriority__: CHANNEL_PRIORITY, pub __channelFlags__: CHANNEL_FLAGS, pub __channelAccessEnum__: CHANNEL_ACCESS_ENUM, pub __rdpencomapiAttendeeFlags__: RDPENCOMAPI_ATTENDEE_FLAGS, pub __rdpsrapiWndFlags__: RDPSRAPI_WND_FLAGS, pub __rdpsrapiAppFlags__: RDPSRAPI_APP_FLAGS, } impl ::core::marker::Copy for __ReferenceRemainingTypes__ {} impl ::core::clone::Clone for __ReferenceRemainingTypes__ { fn clone(&self) -> Self { *self } }
pub trait DegreeTrigonomeric { fn sin_degree(self) -> Self; fn cos_degree(self) -> Self; fn atan2_degree(self, other: Self) -> Self; } const SIN_N90_4: &[isize] = &[0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0]; fn sin_n90(n: isize) -> isize { SIN_N90_4[(n + 4) as usize] } macro_rules! impl_degree_trigonomeric { ($t: ty, $pi: expr) => { impl DegreeTrigonomeric for $t { fn sin_degree(self) -> Self { let v = self % 360.0; let x = v / 90.0; if x == x.floor() { sin_n90(x as isize) as Self } else { (v * $pi / 180.0).sin() } } fn cos_degree(self) -> Self { (90.0 - self).sin_degree() } fn atan2_degree(self, other: Self) -> Self { let v = self.atan2(other); v * 180.0 / $pi } } }; } impl_degree_trigonomeric!(f32, std::f32::consts::PI); impl_degree_trigonomeric!(f64, std::f64::consts::PI); #[test] fn test_sin_cos() { assert_eq!(0.0f32.sin_degree(), 0.0); assert_eq!(45.0f32.sin_degree(), std::f32::consts::SQRT_2/2.0); assert_eq!(90.0f32.sin_degree(), 1.0); assert_eq!(180.0f32.sin_degree(), 0.0); assert_eq!(270.0f32.sin_degree(), -1.0); assert_eq!(360.0f32.sin_degree(), 0.0); assert_eq!(0.0f32.cos_degree(), 1.0); assert_eq!(45.0f32.cos_degree(), std::f32::consts::SQRT_2/2.0); assert_eq!(60.0f32.cos_degree(), 0.5); assert_eq!(90.0f32.cos_degree(), 0.0); }
/// Selection sort pub fn sort<T: Ord + Clone>(list: &Vec<T>) -> Vec<T> { let mut sorted = list.clone(); for index in 0..list.len() { let index_of_least = index_of_least_from(&sorted, index); sorted.swap(index_of_least, index); } return sorted; } fn index_of_least_from<T: Ord + Clone>(list: &Vec<T>, start: usize) -> usize { let mut index_of_least = start; for (index, element) in list.iter().enumerate().skip(start) { if element < &list[index_of_least] { index_of_least = index; } } return index_of_least; }
// 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 carnelian::{ make_message, set_node_color, App, AppAssistant, Color, Label, Message, Paint, Point, Rect, Size, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey, ViewMessages, }; use failure::Error; use fidl_fuchsia_ui_input::{FocusEvent, PointerEvent, PointerEventPhase}; use fuchsia_scenic::{EntityNode, Rectangle, SessionPtr, ShapeNode}; use fuchsia_zircon::{ClockId, Time}; const BACKGROUND_Z: f32 = 0.0; const INDICATOR_Z: f32 = BACKGROUND_Z - 0.01; const BUTTON_Z: f32 = BACKGROUND_Z - 0.01; const BUTTON_BACKGROUND_Z: f32 = BUTTON_Z - 0.01; const BUTTON_LABEL_Z: f32 = BUTTON_BACKGROUND_Z - 0.01; /// enum that defines all messages sent with `App::queue_message` that /// the button view assistant will understand and process. pub enum ButtonMessages { Pressed(Time), } struct ButtonAppAssistant; impl AppAssistant for ButtonAppAssistant { fn setup(&mut self) -> Result<(), Error> { Ok(()) } fn create_view_assistant( &mut self, _: ViewKey, session: &SessionPtr, ) -> Result<ViewAssistantPtr, Error> { Ok(Box::new(ButtonViewAssistant::new(session)?)) } } struct Button { label: Label, background_node: ShapeNode, container: EntityNode, bounds: Rect, bg_color: Color, bg_color_active: Color, bg_color_disabled: Color, fg_color: Color, fg_color_disabled: Color, tracking: bool, active: bool, focused: bool, } impl Button { pub fn new(session: &SessionPtr, text: &str) -> Result<Button, Error> { let mut button = Button { label: Label::new(session, text)?, background_node: ShapeNode::new(session.clone()), container: EntityNode::new(session.clone()), bounds: Rect::zero(), fg_color: Color::white(), bg_color: Color::from_hash_code("#B7410E")?, bg_color_active: Color::from_hash_code("#f0703c")?, fg_color_disabled: Color::from_hash_code("#A0A0A0")?, bg_color_disabled: Color::from_hash_code("#C0C0C0")?, tracking: false, active: false, focused: false, }; // set up the button background button.container.add_child(&button.background_node); set_node_color(session, &button.background_node, &button.bg_color); // Add the label button.container.add_child(button.label.node()); Ok(button) } pub fn set_focused(&mut self, focused: bool) { self.focused = focused; if !focused { self.active = false; self.tracking = false; } } pub fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { // set up paint with different backgrounds depending on whether the button // is active. The active state is true when a pointer has gone down in the // button's bounds and the pointer has not moved outside the bounds since. let paint = if self.focused { Paint { fg: self.fg_color, bg: if self.active { self.bg_color_active } else { self.bg_color }, } } else { Paint { fg: self.fg_color_disabled, bg: self.bg_color_disabled } }; // center the button in the Scenic view by translating the // container node. All child nodes will be positioned relative // to this container let center_x = context.size.width * 0.5; let center_y = context.size.height * 0.5; // pick font size and padding based on the available space let min_dimension = context.size.width.min(context.size.height); let font_size = (min_dimension / 5.0).ceil().min(64.0) as u32; let padding = (min_dimension / 20.0).ceil().max(8.0); self.container.set_translation(center_x, center_y, BUTTON_Z); set_node_color(context.session(), &self.background_node, &paint.bg); // calculate button size based on label's text size // plus padding. let button_size = self.label.dimensions(font_size); let button_w = button_size.width + 2.0 * padding; let button_h = button_size.height + 2.0 * padding; // record bounds for hit testing self.bounds = Rect::new( Point::new(center_x - button_w / 2.0, center_y - button_h / 2.0), Size::new(button_w, button_h), ) .round_out(); self.background_node.set_shape(&Rectangle::new( context.session().clone(), self.bounds.size.width, self.bounds.size.height, )); self.background_node.set_translation(0.0, 0.0, BUTTON_BACKGROUND_Z); self.label.update(font_size, &paint)?; self.label.node().set_translation(0.0, 0.0, BUTTON_LABEL_Z); Ok(()) } pub fn node(&mut self) -> &EntityNode { &self.container } pub fn handle_pointer_event( &mut self, context: &mut ViewAssistantContext, pointer_event: &PointerEvent, ) { if !self.focused { return; } // TODO: extend this to support multiple pointers match pointer_event.phase { PointerEventPhase::Down => { self.active = self.bounds.contains(&Point::new(pointer_event.x, pointer_event.y)); self.tracking = self.active; } PointerEventPhase::Add => {} PointerEventPhase::Hover => {} PointerEventPhase::Move => { if self.tracking { self.active = self.bounds.contains(&Point::new(pointer_event.x, pointer_event.y)); } } PointerEventPhase::Up => { if self.active { context.queue_message(make_message(ButtonMessages::Pressed(Time::get( ClockId::Monotonic, )))); } self.tracking = false; self.active = false; } PointerEventPhase::Remove => { self.active = false; self.tracking = false; } PointerEventPhase::Cancel => { self.active = false; self.tracking = false; } } } } struct ButtonViewAssistant { background_node: ShapeNode, indicator: ShapeNode, button: Button, red_light: bool, } impl ButtonViewAssistant { fn new(session: &SessionPtr) -> Result<ButtonViewAssistant, Error> { Ok(ButtonViewAssistant { background_node: ShapeNode::new(session.clone()), indicator: ShapeNode::new(session.clone()), button: Button::new(&session, "Touch Me")?, red_light: false, }) } } impl ViewAssistant for ButtonViewAssistant { // Called once by Carnelian when the view is first created. Good for setup // that isn't concerned with the size of the view. fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { set_node_color( context.session(), &self.background_node, &Color::from_hash_code("#EBD5B3")?, ); context.root_node().add_child(&self.background_node); context.root_node().add_child(&self.indicator); context.root_node().add_child(self.button.node()); Ok(()) } // Called by Carnelian when the view is resized, after input events are processed // or if sent an explicit Update message. fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { // Position and size the background let center_x = context.size.width * 0.5; let center_y = context.size.height * 0.5; self.background_node.set_shape(&Rectangle::new( context.session().clone(), context.size.width, context.size.height, )); self.background_node.set_translation(center_x, center_y, BACKGROUND_Z); // Position and size the indicator let indicator_y = context.size.height / 5.0; let indicator_size = context.size.height.min(context.size.width) / 8.0; self.indicator.set_shape(&Rectangle::new( context.session().clone(), indicator_size, indicator_size, )); self.indicator.set_translation(center_x, indicator_y, INDICATOR_Z); let indicator_color = if self.red_light { Color::from_hash_code("#ff0000")? } else { Color::from_hash_code("#00ff00")? }; set_node_color(context.session(), &self.indicator, &indicator_color); // Update and position the button self.button.update(context)?; self.button.node().set_translation(center_x, center_y, BUTTON_Z); Ok(()) } fn handle_message(&mut self, message: Message) { if let Some(button_message) = message.downcast_ref::<ButtonMessages>() { match button_message { ButtonMessages::Pressed(value) => { println!("value = {:#?}", value); self.red_light = !self.red_light } } } } fn handle_pointer_event( &mut self, context: &mut ViewAssistantContext, pointer_event: &PointerEvent, ) -> Result<(), Error> { self.button.handle_pointer_event(context, pointer_event); context.queue_message(make_message(ViewMessages::Update)); Ok(()) } fn handle_focus_event( &mut self, context: &mut ViewAssistantContext, focus_event: &FocusEvent, ) -> Result<(), Error> { self.button.set_focused(focus_event.focused); context.queue_message(make_message(ViewMessages::Update)); Ok(()) } } fn main() -> Result<(), Error> { let assistant = ButtonAppAssistant {}; App::run(Box::new(assistant)) }
use crate::messages::*; use crate::orderbook::*; use crate::types::*; use chrono::Local; use std::collections::HashMap; #[allow(dead_code)] pub struct Exchange { books: HashMap<Symbol, OrderBook>, users: HashMap<UserId, UserInfo>, } #[allow(dead_code)] impl Exchange { pub fn new(symbols: Option<Vec<Symbol>>) -> Exchange { match symbols { Some(sym_vec) => { let mut exch = Exchange { books: HashMap::new(), users: HashMap::new(), }; for sym in sym_vec { let sym_copy = sym.clone(); exch.books.insert(sym, OrderBook::new(sym_copy)); } exch } None => Exchange { books: HashMap::new(), users: HashMap::new(), }, } } pub fn process_limit_order(&mut self, msg: LimitOrderMsg){ let order = Order { side: msg.side, price: msg.price, qty: msg.qty, order_id: msg.order_id, time: Local::now(), }; self.books.get_mut(&msg.symbol).unwrap().add_order(order); } }
use std::env; use std::fs::File; use std::io::{self, BufRead, BufReader}; struct Program { pc: i32, acc: i32, } impl Program { pub fn new() -> Program { return Program { pc: 0, acc: 0 }; } fn nop(&mut self) { self.pc += 1; } fn acc(&mut self, arg: i32) { self.acc += arg; self.pc += 1; } fn jmp(&mut self, arg: i32) { self.pc += arg; } fn execute_opcode(&mut self, line: &str) { let mut parts = line.split(" "); if let Some(opcode) = parts.next() { if let Some(arg) = parts.next() { if let Ok(n) = arg.parse::<i32>() { match opcode { "nop" => self.nop(), "acc" => self.acc(n), "jmp" => self.jmp(n), _ => panic!("execute_opcode: opcode '{}' not implemented"), } return; } } } panic!("execute_opcode: invalid line '{}'", line); } pub fn step(&mut self, rom: &Vec<String>) -> usize { if self.pc >= 0 { self.execute_opcode(&rom[self.pc as usize]); } else { panic!("program.step: pc is negative"); } return self.pc as usize; } pub fn get_acc(&self) -> i32 { return self.acc; } pub fn reset(&mut self) { self.pc = 0; self.acc = 0; } } fn main() -> Result<(), io::Error> { let args: Vec<String> = env::args().collect(); let mut program = Program::new(); let reader = BufReader::new(File::open(&args[1]).expect("File::open failed")); let mut rom = reader .lines() .map(|row| row.expect("reader.lines failed")) .collect::<Vec<String>>(); if &args[2] == "1" { let mut history = Vec::<usize>::new(); loop { let pc = program.step(&rom); if history.contains(&pc) { eprintln!("infinite loop at instruction: {}, {}", pc, rom[pc]); break; } history.push(pc); } println!("{}", program.get_acc()); } else if &args[2] == "2" { let mut cursor = 0; loop { for i in cursor..rom.len() { if rom[i].starts_with("nop") || rom[i].starts_with("jmp") { cursor = i; swap_nop_jmp(&mut rom, cursor); break; } } let mut history = Vec::<usize>::new(); loop { let pc = program.step(&rom); if history.contains(&pc) { eprintln!("infinite loop at instruction: {}, {}", pc, rom[pc]); break; } history.push(pc); if pc >= rom.len() { println!("{}", program.get_acc()); return Ok(()); } } swap_nop_jmp(&mut rom, cursor); cursor += 1; program.reset(); } } Ok(()) } fn swap_nop_jmp(rom: &mut Vec<String>, i: usize) { let tmp = String::from(&rom[i]); if tmp.starts_with("nop") { rom[i] = String::from("jmp"); } else if tmp.starts_with("jmp") { rom[i] = String::from("nop"); } rom[i].push_str(&tmp[3..]); } #[cfg(test)] mod tests { #[test] fn test_stuff() { assert_eq!("+13".parse::<i32>().unwrap(), 13); assert_eq!("-13".parse::<i32>().unwrap(), -13); } }
use std::pin::Pin; use async_std::io; use async_std::io::prelude::*; use async_std::task::{Context, Poll}; use futures_core::ready; /// An encoder for chunked encoding. #[derive(Debug)] pub(crate) struct ChunkedEncoder<R> { reader: R, done: bool, } impl<R: Read + Unpin> ChunkedEncoder<R> { /// Create a new instance. pub(crate) fn new(reader: R) -> Self { Self { reader, done: false, } } } impl<R: Read + Unpin> Read for ChunkedEncoder<R> { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { if self.done { return Poll::Ready(Ok(0)); } let reader = &mut self.reader; let max_bytes_to_read = max_bytes_to_read(buf.len()); let bytes = ready!(Pin::new(reader).poll_read(cx, &mut buf[..max_bytes_to_read]))?; if bytes == 0 { self.done = true; } let start = format!("{:X}\r\n", bytes); let start_length = start.as_bytes().len(); let total = bytes + start_length + 2; buf.copy_within(..bytes, start_length); buf[..start_length].copy_from_slice(start.as_bytes()); buf[total - 2..total].copy_from_slice(b"\r\n"); Poll::Ready(Ok(total)) } } fn max_bytes_to_read(buf_len: usize) -> usize { if buf_len < 6 { // the minimum read size is of 6 represents one byte of // content from the body. the other five bytes are 1\r\n_\r\n // where _ is the actual content in question panic!("buffers of length {} are too small for this implementation. if this is a problem for you, please open an issue", buf_len); } let bytes_remaining_after_two_cr_lns = (buf_len - 4) as f64; // the maximum number of bytes that the hex representation of remaining bytes might take let max_bytes_of_hex_framing = bytes_remaining_after_two_cr_lns.log2() / 4f64; (bytes_remaining_after_two_cr_lns - max_bytes_of_hex_framing.ceil()) as usize } #[cfg(test)] mod test_bytes_to_read { #[test] fn simple_check_of_known_values() { // the marked rows are the most important part of this test, // and a nonobvious but intentional consequence of the // implementation. in order to avoid overflowing, we must use // one fewer than the available buffer bytes because // increasing the read size increase the number of framed // bytes by two. This occurs when the hex representation of // the content bytes is near an increase in order of magnitude // (F->10, FF->100, FFF-> 1000, etc) let values = vec![ (6, 1), // 1 (7, 2), // 2 (20, 15), // F (21, 15), // F <- (22, 16), // 10 (23, 17), // 11 (260, 254), // FE (261, 254), // FE <- (262, 255), // FF <- (263, 256), // 100 (4100, 4093), // FFD (4101, 4093), // FFD <- (4102, 4094), // FFE <- (4103, 4095), // FFF <- (4104, 4096), // 1000 ]; for (input, expected) in values { let actual = super::max_bytes_to_read(input); assert_eq!( actual, expected, "\n\nexpected max_bytes_to_read({}) to be {}, but it was {}", input, expected, actual ); // testing the test: let used_bytes = expected + 4 + format!("{:X}", expected).len(); assert!( used_bytes == input || used_bytes == input - 1, "\n\nfor an input of {}, expected used bytes to be {} or {}, but was {}", input, input, input - 1, used_bytes ); } } }
use std::collections::HashMap; use std::fs; use clap::ArgMatches; use rand::{Rng, SeedableRng, prelude::StdRng}; use arrayref::array_ref; use sha2::{Sha256, Digest}; const COMMON_CHARS: [char; 26] = [ 'i', 't', 'a', 'o', 'e', 'n', 's', 'h', 'r', 'd', 'l', 'c', 'u', 'm', 'w', 'f', 'g', 'y', 'p', 'b', 'v', 'k', 'j', 'x', 'q', 'z' ]; pub enum ValueMode { CharBitMap, // the map contains 1 character for each bit position // given a number of bits. ie: if 3 bits, the map contains 4 characters // (1 extra character to explicitly map 0), if 8 bits, the map contains 9 characters. // the value is determined by checking which characters are present, and if // a character is present, that means the bit is set for that char. // duplicate characters are irrelevant, since a bit can only be set once. CharValueMap(usize), // the map contains every character in the alphabet and assigns values ranging // from 0 to 2^(num bits) - 1 in increments of powers of 2. the value is determined // by adding the the value for each character present in a word. duplicate characters // are allowed, since it will increase the value. If the value reaches // 2^(num bits), it overflows and wraps back to 0. } pub enum Algorithm { Shuffle(ValueMode), NoShuffle(ValueMode), } pub fn get_algorithm_from_string(alg_str: &str, num_bits: usize) -> Result<Algorithm, String> { match alg_str { "char-bit" => Ok(Algorithm::NoShuffle(ValueMode::CharBitMap)), "char-bit-shuffle" => Ok(Algorithm::Shuffle(ValueMode::CharBitMap)), "char-value" => Ok(Algorithm::NoShuffle(ValueMode::CharValueMap(num_bits))), "char-value-shuffle" => Ok(Algorithm::Shuffle(ValueMode::CharValueMap(num_bits))), _ => Err(format!("Could not determine algorithm: {}", alg_str)), } } pub fn get_value<'a>(matches: &'a ArgMatches, value_name: &str) -> Result<&'a str, String> { match matches.value_of(value_name) { Some(val) => { Ok(val) }, None => Err(format!("failed to get value of {}", value_name)), } } pub fn get_numerical_value(matches: &ArgMatches, value_name: &str) -> Result<usize, String> { let value_str = get_value(matches, value_name)?; match value_str.parse::<usize>() { Ok(parsed) => Ok(parsed), Err(_) => Err(format!("Failed to parse '{}' as a number", value_str)), } } pub fn make_bit_to_char_map(num_bits: usize) -> HashMap<usize, char> { let mut bit_to_char_map: HashMap<usize, char> = HashMap::new(); for num in 0..(num_bits + 1) { let key = if num == 0 { 0 } else { 1 << (num - 1) }; bit_to_char_map.insert(key, COMMON_CHARS[num as usize]); } bit_to_char_map } pub fn get_max_value(exponent: usize) -> usize { (2 as usize).pow(exponent as u32) - 1 } pub fn make_char_to_value_map(exponent: usize) -> HashMap<char, usize> { let mut char_to_value_map: HashMap<char, usize> = HashMap::new(); let max_val = get_max_value(exponent); let mut current_val = 0; let mut max_it = COMMON_CHARS.len() / 2; for i in 0..max_it { let common_index = i; let uncommon_index = COMMON_CHARS.len() - i - 1; char_to_value_map.insert(COMMON_CHARS[common_index], current_val); char_to_value_map.insert(COMMON_CHARS[uncommon_index], current_val); current_val += 1; if current_val > max_val { current_val = 0; } // current val gets assigned simultaneously to the most common and // least common character at any timestep. for each timestep, // current val gets incremented until it surpasses the maximum val // then wraps back to 0. // eg: maximum val is 7 if max_exponent = 3, // because 2^3 = 8. 8 - 1 = 7. // the first 7 most common characters get mapped 0, 1, 2, ... 7, // as well as the 7 least common characters. // the 9th character on either side then gets mapped to 0 and the // cycle restarts. } char_to_value_map } fn create_hash(text: &str) -> String { let mut hasher = Sha256::default(); hasher.input(text.as_bytes()); format!("{:x}", hasher.result()) } pub fn create_rng_from_seed(text: &str) -> StdRng { let hash = create_hash(text); let seed = array_ref!(hash.as_bytes(), 0, 32); SeedableRng::from_seed(*seed) } pub fn format_text_for_ngrams(text: &str) -> String { let mut new_text: String = text.to_string().to_lowercase(); if text.ends_with('.') { new_text.push(' '); } let without_newlines = new_text.replace("\n", " \n "); let without_carriage_returns = without_newlines.replace("\r", ""); let without_quotes = without_carriage_returns.replace("\"", ""); let without_single_quotes = without_quotes.replace("'", ""); let without_dashes = without_single_quotes.replace("-", " "); let without_commas = without_dashes.replace(", ", " , "); let without_exclamation = without_commas.replace("! ", " ! "); let without_questions = without_exclamation.replace("? ", " ? "); let without_semicolons = without_questions.replace("; ", " ; "); let without_colons = without_semicolons.replace(": ", " : "); let mut with_spaces = without_colons.replace(". ", " . "); with_spaces.pop(); with_spaces = [". ", &with_spaces].join(""); with_spaces } pub fn is_skip_word(word: &str, char_to_bit_map: &HashMap<char, usize>) -> bool { let mut restricted_chars = vec![]; for key in char_to_bit_map.keys() { restricted_chars.push(*key); } let mut skip_word = true; for c in word.chars() { if restricted_chars.contains(&c) { skip_word = false; break; } } skip_word } pub fn get_file_contents(file_name: &str) -> Result<Vec<u8>, String> { match fs::read(file_name) { Ok(data) => Ok(data), Err(_) => Err(format!("Failed to read file: '{}'", file_name)), } } pub fn get_file_contents_as_string(file_name: &str) -> Result<String, String> { match fs::read_to_string(file_name) { Ok(data) => Ok(data), Err(_) => Err(format!("Failed to read file: '{}'", file_name)), } } pub fn get_chars_from_value(val: u8, char_map: &HashMap<usize, char>, sorted_keys: &Vec<usize>) -> String { let mut out_str = String::from(""); let mut val_remaining = val; for num in 0..sorted_keys.len() { let current_byte_val = sorted_keys[num]; if current_byte_val as u8 == val_remaining { let some_char = char_map.get(&current_byte_val).unwrap(); out_str.push(*some_char); // perfect match: ie if map is { 0: 'a', 1: 'b', 2: 'c' } // and the val == 3, first we get to 2, which is less than 3 // so we add a c. next val_remaining is 1. 1 == 1 which maps to 'b' // we push b to the out string, break, and return "cb" break } else if (current_byte_val as u8) < val_remaining { let some_char = char_map.get(&current_byte_val).unwrap(); out_str.push(*some_char); val_remaining -= current_byte_val as u8; } } out_str } pub fn get_value_from_chars(chars: &str, char_map: &HashMap<char, usize>, mode: &ValueMode) -> usize { let mut out_value = 0; let mut chars_checked = vec![]; for c in chars.chars() { match mode { ValueMode::CharBitMap => { if chars_checked.contains(&c) { // if we already checked this character, // dont bother checking again. since // each character represents a bit being set. if there are // multiple characters that does not mean that // the bit is set multiple times... continue } }, _ => (), } if let Some(val) = char_map.get(&c) { out_value += val; } chars_checked.push(c); } match mode { ValueMode::CharBitMap => out_value, ValueMode::CharValueMap(exp) => out_value % (get_max_value(*exp) + 1), } } pub fn shuffle_char_value_map(rng: &mut StdRng, char_to_value_map: &mut HashMap<char, usize>) { let mut char_values = vec![]; let mut char_keys = vec![]; for key in char_to_value_map.keys() { char_keys.push(key.clone()); } char_keys.sort_by(|a, b| a.cmp(b)); for key in &char_keys { char_values.push(char_to_value_map.get(key).unwrap().clone()); } let mut chars = COMMON_CHARS.to_vec(); while chars.len() > 0 { let current_char = chars[0]; let random_index = rng.gen_range(0, chars.len()); let random_char = chars[random_index]; let current_val = char_to_value_map.get(&current_char).unwrap().clone(); let random_val = char_to_value_map.get(&random_char).unwrap().clone(); chars.remove(random_index); chars.remove(0); char_to_value_map.remove(&current_char); char_to_value_map.remove(&random_char); char_to_value_map.insert(current_char, random_val); char_to_value_map.insert(random_char, current_val); } } pub fn fill_bit_to_char_map(rng: &mut StdRng, bit_to_char_map: &mut HashMap<usize, char>) { let mut bit_keys = vec![]; let mut bit_values = vec![]; for key in bit_to_char_map.keys() { bit_keys.push(key.clone()); } bit_keys.sort_by(|a, b| a.cmp(b)); for key in &bit_keys { bit_values.push(bit_to_char_map.get(key).unwrap().clone()); } let mut chars = COMMON_CHARS.to_vec(); for num in 0..bit_keys.len() { let key = bit_keys[num]; let random_index = rng.gen_range(0, chars.len()); let random_char = chars[random_index]; chars.remove(random_index); bit_to_char_map.remove(&key); bit_to_char_map.insert(key, random_char); } } pub fn make_char_to_bit_map(bit_to_char_map: &HashMap<usize, char>) -> HashMap<char, usize> { let mut char_to_bit_map = HashMap::new(); for bit_val in bit_to_char_map.keys() { char_to_bit_map.insert(*bit_to_char_map.get(&bit_val).unwrap() , *bit_val); } char_to_bit_map }
/* * Copyright 2019 André Cipriani Bandarra * * 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. * */ //! This crate implements the WCAG specification for contrast ratio and relative luminance. //! Read more about WCAG at [https://www.w3.org/TR/WCAG20/](https://www.w3.org/TR/WCAG20/). use std::str::FromStr; /// /// A representation for a color with the red, green and blue channels /// #[derive(Debug, PartialOrd, PartialEq)] pub struct Color { r: u8, g: u8, b: u8, } impl Color { /// /// Creates a new [Color]. /// ```rust /// use wcagcontrast::Color; /// use std::str::FromStr; /// /// let color = Color::new(255, 255, 255); /// assert_eq!(color.rgb(), (255, 255, 255)); /// ``` pub fn new(r: u8, g: u8, b: u8) -> Self { Color {r, g, b} } /// /// Generates an ([u8], [u8], [u8]) tuple from the [Color] with the red, green, and blue channels. /// ```rust /// use wcagcontrast::Color; /// use std::str::FromStr; /// /// let color = Color::from_str("#FFFFFF").unwrap(); /// assert_eq!(color.rgb(), (255, 255, 255)); /// ``` pub fn rgb(&self) -> (u8, u8, u8) { (self.r, self.g, self.b) } /// /// Calculates the relative luminance, as described on /// [https://www.w3.org/TR/WCAG20/#relativeluminancedef](https://www.w3.org/TR/WCAG20/#relativeluminancedef) /// /// ```rust /// use wcagcontrast::Color; /// /// let black = Color::new(0, 0, 0); /// let white = Color::new(255, 255, 255); /// assert_eq!(white.relative_luminance(), 1.0); /// assert_eq!(black.relative_luminance(), 0.0); /// ``` /// pub fn relative_luminance(&self) -> f64 { let red_luminance = Color::component_relative_luminance(self.r); let green_luminance = Color::component_relative_luminance(self.g); let blue_luminance = Color::component_relative_luminance(self.b); 0.2126 * red_luminance + 0.7152 * green_luminance + 0.0722 * blue_luminance } /// /// Calculates the contrast ratio, as described on /// [https://www.w3.org/TR/WCAG20/#contrast-ratiodef](https://www.w3.org/TR/WCAG20/#contrast-ratiodef) /// /// ```rust /// use wcagcontrast::Color; /// /// let black = Color::new(0, 0, 0); /// let white = Color::new(255, 255, 255); /// assert_eq!(black.contrast_ratio(&white), 21.0); /// assert_eq!(black.contrast_ratio(&black), 1.0); /// assert_eq!(white.contrast_ratio(&white), 1.0); /// ``` /// pub fn contrast_ratio(&self, other: &Color) -> f64 { let self_luminance = self.relative_luminance(); let other_luminance = other.relative_luminance(); let (lighter, darker) = if self_luminance > other_luminance { (self_luminance, other_luminance) } else { (other_luminance, self_luminance) }; (lighter + 0.05) / (darker + 0.05) } /// /// Calculates the luminance of a single color component. /// fn component_relative_luminance(color_component: u8) -> f64 { let c = color_component as f64 / 255.0; if c <= 0.03928 { c / 12.92 } else { f64::powf((c + 0.055) / 1.055, 2.4) } } } impl FromStr for Color { type Err = std::num::ParseIntError; /// ```rust /// use wcagcontrast::Color; /// use std::str::FromStr; /// /// let color = Color::from_str("#FFFFFF").unwrap(); /// assert_eq!(color.rgb(), (255, 255, 255)); /// ``` fn from_str(s: &str) -> Result<Self, Self::Err> { let r = u8::from_str_radix(&s[1 .. 3], 16)?; let g = u8::from_str_radix(&s[3 .. 5], 16)?; let b = u8::from_str_radix(&s[5 .. 7], 16)?; Ok(Color::new(r, g, b)) } } impl From<(u8, u8, u8)> for Color { fn from(tuple: (u8, u8, u8)) -> Self { Color::new(tuple.0, tuple.1, tuple.2) } } #[cfg(test)] mod test { use super::*; #[test] fn color_from_hex() { assert_eq!( Color::from_str("#000000").unwrap(), Color::new(0, 0, 0) ); assert_eq!( Color::from_str("#FFFFFF").unwrap(), Color::new(255, 255, 255) ); assert_eq!( Color::from_str("#ffffff").unwrap(), Color::new(255, 255, 255) ); } #[test] fn calculates_correct_ratio() { assert_eq!( Color::new(0, 0, 0) .contrast_ratio(&Color::new(255, 255, 255)), 21.0 ); assert_eq!( Color::new(255, 255, 255) .contrast_ratio(&Color::new(0, 0, 0)), 21.0 ); assert_eq!( Color::new(255, 255, 255) .contrast_ratio(&Color::new(255, 255, 255)), 1.0 ); } #[test] fn calculates_relative_luminance() { assert_eq!(Color::new(255, 255, 255).relative_luminance(), 1.0); assert_eq!(Color::new(0, 0, 0).relative_luminance(), 0.0); } }
use actix::Actor; use actix_rt::System; use bus::BusActor; use chain::{ChainActor, ChainActorRef}; use config::{ConsensusStrategy, NodeConfig, PacemakerStrategy}; use consensus::dummy::{DummyConsensus, DummyHeader}; use logger::prelude::*; use network::network::NetworkActor; use starcoin_genesis::Genesis; use starcoin_miner::MinerActor; use starcoin_miner::MinerClientActor; use starcoin_sync_api::SyncMetadata; use starcoin_txpool_api::TxPoolAsyncService; use starcoin_wallet_api::WalletAccount; use std::sync::Arc; use storage::cache_storage::CacheStorage; use storage::storage::StorageInstance; use storage::Storage; use sync::SyncActor; use tokio::time::{delay_for, Duration}; use traits::ChainAsyncService; use txpool::TxPoolRef; use types::{ account_address::AccountAddress, peer_info::{PeerId, PeerInfo}, }; #[test] fn test_miner_with_schedule_pacemaker() { ::logger::init_for_test(); let rt = tokio::runtime::Runtime::new().unwrap(); let handle = rt.handle().clone(); let mut system = System::new("test"); let fut = async move { let peer_id = Arc::new(PeerId::random()); let mut config = NodeConfig::random_for_test(); config.miner.pacemaker_strategy = PacemakerStrategy::Schedule; config.miner.dev_period = 1; config.miner.consensus_strategy = ConsensusStrategy::Dummy; let config = Arc::new(config); let bus = BusActor::launch(); let storage = Arc::new( Storage::new(StorageInstance::new_cache_instance(CacheStorage::new())).unwrap(), ); let key_pair = config.network.network_keypair(); let _address = AccountAddress::from_public_key(&key_pair.public_key); let genesis = Genesis::build(config.net()).unwrap(); let genesis_hash = genesis.block().header().id(); let startup_info = genesis.execute(storage.clone()).unwrap(); let txpool = { let best_block_id = startup_info.master.get_head(); TxPoolRef::start( config.tx_pool.clone(), storage.clone(), best_block_id, bus.clone(), ) }; let network = NetworkActor::launch( config.clone(), bus.clone(), handle.clone(), genesis_hash, PeerInfo::default(), ); let sync_metadata = SyncMetadata::new(config.clone(), bus.clone()); let chain = ChainActor::launch( config.clone(), startup_info.clone(), storage.clone(), Some(network.clone()), bus.clone(), txpool.clone(), sync_metadata.clone(), ) .unwrap(); let miner_account = WalletAccount::random(); let _miner = MinerActor::< DummyConsensus, TxPoolRef, ChainActorRef<DummyConsensus>, Storage, DummyHeader, >::launch( config.clone(), bus.clone(), storage.clone(), txpool.clone(), chain.clone(), None, miner_account, ); MinerClientActor::new(config.miner.clone()).start(); let _sync = SyncActor::launch( config.clone(), bus, peer_id, chain.clone(), txpool.clone(), network.clone(), storage.clone(), sync_metadata.clone(), ) .unwrap(); delay_for(Duration::from_millis(6 * 1000)).await; let number = chain.clone().master_head_header().await.unwrap().number(); info!("current block number: {}", number); assert!(number > 1); }; system.block_on(fut); drop(rt); } #[ignore] #[test] fn test_miner_with_ondemand_pacemaker() { ::logger::init_for_test(); let rt = tokio::runtime::Runtime::new().unwrap(); let handle = rt.handle().clone(); let mut system = System::new("test"); let fut = async move { let peer_id = Arc::new(PeerId::random()); let mut conf = NodeConfig::random_for_test(); conf.miner.pacemaker_strategy = PacemakerStrategy::Ondemand; conf.miner.consensus_strategy = ConsensusStrategy::Dummy; let config = Arc::new(conf); let bus = BusActor::launch(); let storage = Arc::new( Storage::new(StorageInstance::new_cache_instance(CacheStorage::new())).unwrap(), ); let key_pair = config.network.network_keypair(); let _address = AccountAddress::from_public_key(&key_pair.public_key); let genesis = Genesis::build(config.net()).unwrap(); let genesis_hash = genesis.block().header().id(); let startup_info = genesis.execute(storage.clone()).unwrap(); let txpool = { let best_block_id = startup_info.master.get_head(); TxPoolRef::start( config.tx_pool.clone(), storage.clone(), best_block_id, bus.clone(), ) }; let network = NetworkActor::launch( config.clone(), bus.clone(), handle.clone(), genesis_hash, PeerInfo::default(), ); let sync_metadata = SyncMetadata::new(config.clone(), bus.clone()); let chain = ChainActor::launch( config.clone(), startup_info.clone(), storage.clone(), Some(network.clone()), bus.clone(), txpool.clone(), sync_metadata.clone(), ) .unwrap(); let receiver = txpool.clone().subscribe_txns().await.unwrap(); let miner_account = WalletAccount::random(); let _miner = MinerActor::< DummyConsensus, TxPoolRef, ChainActorRef<DummyConsensus>, Storage, DummyHeader, >::launch( config.clone(), bus.clone(), storage.clone(), txpool.clone(), chain.clone(), Some(receiver), miner_account, ); MinerClientActor::new(config.miner.clone()).start(); let _sync = SyncActor::launch( config.clone(), bus, peer_id, chain.clone(), txpool.clone(), network.clone(), storage.clone(), sync_metadata.clone(), ) .unwrap(); delay_for(Duration::from_millis(6 * 10 * 1000)).await; let number = chain.clone().master_head_header().await.unwrap().number(); info!("{}", number); assert!(number > 0); delay_for(Duration::from_millis(1000)).await; }; system.block_on(fut); drop(rt); }
pub mod codegen; pub mod parser; pub mod source; use crate::codegen::*; use crate::parser::*; use crate::source::*; use std::env; use std::process; use std::fs::File; use std::io::Write; use std::path::Path; /** * 1. Read file or directory * 2. parse each vm files to VMCommand(s) * 3. generate hack asm from VMCommand(s) * */ pub fn process() { // get filename or directory from args let arg = get_first_arg(); let (dir, vm_name) = parse_arg(&arg); let sources = read_sources(&arg).unwrap_or_else(|err| { println!("cannot read file: {}", err); process::exit(1); }); let results: Vec<ParseResult> = sources.map(|src| parse(&src.code, &src.vm_name)).collect(); let errors: Vec<&anyhow::Error> = results.iter().map(|res| &res.errors).flatten().collect(); if !errors.is_empty() { println!("parse error: "); errors.into_iter().for_each(|err| println!(" {:?}", err)); process::exit(1); } // generate code let (asm, errors) = generate(results); if !errors.is_empty() { println!("codegen error: "); errors.into_iter().for_each(|err| println!(" {:?}", err)); process::exit(1); } // write to file write_asm(&dir, &vm_name, &asm); println!("Asm:"); println!("{}", &asm); } fn get_first_arg() -> String { // get first arg let args: Vec<String> = env::args().collect(); let name = args.get(1).unwrap_or_else(|| { println!("not enough arguments"); process::exit(1); }); String::from(name) } fn parse_arg(arg: &str) -> (String, String) { let path = Path::new(arg); if !path.exists() { println!("no such path or filename: {}", arg); process::exit(1); } let basename = path .file_name() .unwrap_or_else(|| { println!("invalid filename: {}", arg); process::exit(1); }) .to_string_lossy() .into_owned(); let dir = if path.is_dir() { path } else { path.parent().unwrap_or_else(|| { println!("invalid filename: {}", arg); process::exit(1); }) }; let vm_name = if path.is_dir() { basename } else { if basename.ends_with(".vm") { basename.replace(".vm", "") } else { println!("filename is expected to be ends with .vm: {}", arg); process::exit(1); } }; (dir.to_string_lossy().into_owned(), vm_name) } fn write_asm(dir: &str, vm_name: &str, asm: &str) { let path = Path::new(dir); let filename = format!("{}.asm", vm_name); let filename = path.join(filename); File::create(&filename) .unwrap_or_else(|err| { println!("cannot open file: {}", err); process::exit(1); }) .write_all(asm.as_bytes()) .unwrap_or_else(|err| { println!("cannot write file: {}", err); process::exit(1); }); println!("write asm to {}", &filename.to_string_lossy()); }
use ::amethyst::ecs::*; use dirty::Dirty; use serde::de::DeserializeOwned; use serde::Serialize; use std::fs::File; use std::io::Read as IORead; use std::io::Write as IOWrite; use std::marker::PhantomData; /// If the tracked resource changes, this will be checked to make sure it is a proper time to save. pub trait ShouldSave { fn save_ready(&self) -> bool; fn set_save_ready(&mut self, ready: bool); } /// System used to automatically save a Resource T to a file. /// On load, it will attempt to load it from the file and if it fails, it will use T::default(). /// The resource in question will be wrapped into a `Dirty<T>` value inside of specs to keep track of changes made to the resource. /// This `System` will save the resource each time there is a modification. /// It is best used with resources that are modified less than once every second. pub struct AutoSaveSystem<T> { /// Absolute path. save_path: String, _phantom_data: PhantomData<T>, } impl<T> AutoSaveSystem<T> where T: Serialize + DeserializeOwned + Default + ShouldSave + Send + Sync + 'static, { /// Create a new `AutoSaveSystem`. /// Save path is an absolute path. pub fn new(save_path: String) -> (Self, Option<Dirty<T>>) { // attempt loading let dirty = if let Ok(mut f) = File::open(&save_path) { let mut buf = String::new(); if let Ok(_) = f.read_to_string(&mut buf) { if let Ok(o) = ron::de::from_str::<T>(&buf) { Some(Dirty::new(o)) } else { error!( "Failed to deserialize save file: {}.\nThe file might be corrupted.", save_path ); None } } else { error!("Failed to read content of save file: {}", save_path); None } } else { warn!( "Failed to load save file: {}. It will be created during the next save.", save_path ); None }; ( AutoSaveSystem { save_path, _phantom_data: PhantomData, }, dirty, ) } } impl<'a, T> System<'a> for AutoSaveSystem<T> where T: Serialize + DeserializeOwned + Default + ShouldSave + Send + Sync + 'static, { type SystemData = (Write<'a, Dirty<T>>,); fn run(&mut self, (mut data,): Self::SystemData) { if data.dirty() { data.clear(); let value = data.read(); let string_data = ron::ser::to_string(&value).expect(&format!( "Unable to serialize the save struct for: {}", self.save_path )); let file = File::create(&self.save_path); match file { Ok(mut f) => { // Write all serialized data to file. let res = f.write_all(string_data.as_bytes()); if res.is_err() { error!( "Failed to write serialized save data to the file. Error: {:?}", res.err().expect( "unreachable: We know there is an error from the if clause." ) ); } } Err(e) => { error!( "Failed to create or load the save file \"{}\". Error: {:?}", &self.save_path, e ); } } } } }