text stringlengths 8 4.13M |
|---|
use super::schema::{verbs};
#[derive(Queryable)]
pub struct Verb {
pub id: i32,
pub pronoun: i8,
pub infinitive: String,
pub tense: i8,
pub conjugated: String,
pub phonex: String,
pub infinitive_phonex: String,
pub verb_group: i8,
pub type_verb: i8,
pub verbe_intransitif: i8,
pub verbe_intransitif_direct: i8,
pub verbe_intransitif_indirect: i8,
pub verbe_pronomial: i8,
pub verbe_impersonnel: i8,
pub verbe_auxilliaire_etre: i8,
pub verbe_auxilliaire_avoir: i8
}
#[derive(Insertable)]
#[table_name="verbs"]
pub struct NewVerb<'a> {
pub pronoun: i32,
pub infinitive: &'a str,
pub tense: i32,
pub conjugated: &'a str,
pub phonex: &'a str,
pub infinitive_phonex: &'a str,
pub verb_group: i32,
pub type_verb: i32,
pub verbe_intransitif: i32,
pub verbe_intransitif_direct: i32,
pub verbe_intransitif_indirect: i32,
pub verbe_pronomial: i32,
pub verbe_impersonnel: i32,
pub verbe_auxilliaire_etre: i32,
pub verbe_auxilliaire_avoir: i32
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::{self, Fail};
use std::io;
#[derive(Clone, Debug, PartialEq, Eq, Fail)]
pub enum ResourcePathError {
#[fail(display = "object names must be at least 1 byte")]
NameEmpty,
#[fail(display = "object names must be at most 255 bytes")]
NameTooLong,
#[fail(display = "object names cannot contain the NULL byte")]
NameContainsNull,
#[fail(display = "object names cannot be '.'")]
NameIsDot,
#[fail(display = "object names cannot be '..'")]
NameIsDotDot,
#[fail(display = "object paths cannot start with '/'")]
PathStartsWithSlash,
#[fail(display = "object paths cannot end with '/'")]
PathEndsWithSlash,
#[fail(display = "object paths must be at least 1 byte")]
PathIsEmpty,
// TODO(PKG-597) allow newline once meta/contents supports it in blob paths
#[fail(display = r"object names cannot contain the newline character '\n'")]
NameContainsNewline,
}
#[derive(Debug, Eq, Fail, PartialEq)]
pub enum PackageNameError {
#[fail(display = "package names cannot be empty")]
Empty,
#[fail(display = "package names must be at most 100 latin-1 characters, '{}'", invalid_name)]
TooLong { invalid_name: String },
#[fail(
display = "package names must consist of only digits (0 to 9), lower-case letters (a to z), hyphen (-), and period (.), '{}'",
invalid_name
)]
InvalidCharacter { invalid_name: String },
}
#[derive(Debug, Eq, Fail, PartialEq)]
pub enum PackageVariantError {
#[fail(display = "package variants cannot be empty")]
Empty,
#[fail(
display = "package variants must be at most 100 latin-1 characters, '{}'",
invalid_variant
)]
TooLong { invalid_variant: String },
#[fail(
display = "package variants must consist of only digits (0 to 9), lower-case letters (a to z), hyphen (-), and period (.), '{}'",
invalid_variant
)]
InvalidCharacter { invalid_variant: String },
}
#[derive(Debug, Fail)]
pub enum CreationManifestError {
#[fail(display = "manifest contains an invalid resource path '{}'. {}", path, cause)]
ResourcePath {
#[cause]
cause: ResourcePathError,
path: String,
},
#[fail(display = "attempted to deserialize creation manifest from malformed json: {}", _0)]
Json(#[cause] serde_json::Error),
#[fail(display = "package external content cannot be in 'meta/' directory: {}", path)]
ExternalContentInMetaDirectory { path: String },
#[fail(display = "package far content must be in 'meta/' directory: {}", path)]
FarContentNotInMetaDirectory { path: String },
}
impl From<serde_json::Error> for CreationManifestError {
fn from(err: serde_json::Error) -> Self {
CreationManifestError::Json(err)
}
}
#[derive(Debug, Fail)]
pub enum MetaContentsError {
#[fail(display = "invalid resource path '{}'", path)]
ResourcePath {
#[cause]
cause: ResourcePathError,
path: String,
},
#[fail(display = "package external content cannot be in 'meta/' directory: '{}'", path)]
ExternalContentInMetaDirectory { path: String },
#[fail(display = "entry has no '=': '{}'", entry)]
EntryHasNoEqualsSign { entry: String },
#[fail(display = "duplicate resource path: '{}'", path)]
DuplicateResourcePath { path: String },
#[fail(display = "io error: '{}'", _0)]
IoError(#[cause] io::Error),
#[fail(display = "invalid hash: '{}'", _0)]
ParseHash(#[cause] fuchsia_merkle::ParseHashError),
}
impl From<io::Error> for MetaContentsError {
fn from(err: io::Error) -> Self {
MetaContentsError::IoError(err)
}
}
impl From<fuchsia_merkle::ParseHashError> for MetaContentsError {
fn from(err: fuchsia_merkle::ParseHashError) -> Self {
MetaContentsError::ParseHash(err)
}
}
#[derive(Debug, Fail)]
pub enum MetaPackageError {
#[fail(display = "invalid package name '{}'", _0)]
PackageName(#[cause] PackageNameError),
#[fail(display = "invalid package variant '{}'", _0)]
PackageVariant(#[cause] PackageVariantError),
#[fail(display = "attempted to deserialize meta/package from malformed json: {}", _0)]
Json(#[cause] serde_json::Error),
}
impl From<PackageNameError> for MetaPackageError {
fn from(err: PackageNameError) -> Self {
MetaPackageError::PackageName(err)
}
}
impl From<PackageVariantError> for MetaPackageError {
fn from(err: PackageVariantError) -> Self {
MetaPackageError::PackageVariant(err)
}
}
impl From<serde_json::Error> for MetaPackageError {
fn from(err: serde_json::Error) -> Self {
MetaPackageError::Json(err)
}
}
#[derive(Debug, Fail)]
pub enum BuildError {
#[fail(display = "io error: '{}'", _0)]
IoError(#[cause] io::Error),
#[fail(display = "meta contents error: '{}'", _0)]
MetaContents(#[cause] MetaContentsError),
#[fail(display = "meta package error: '{}'", _0)]
MetaPackage(#[cause] MetaPackageError),
#[fail(
display = "the creation manifest contained a resource path that conflicts with a generated resource path: '{}'",
conflicting_resource_path
)]
ConflictingResource { conflicting_resource_path: String },
#[fail(display = "fuchsia_archive::write error: {}", _0)]
ArchiveWrite(#[cause] failure::Error),
}
impl From<io::Error> for BuildError {
fn from(err: io::Error) -> Self {
BuildError::IoError(err)
}
}
impl From<MetaContentsError> for BuildError {
fn from(err: MetaContentsError) -> Self {
BuildError::MetaContents(err)
}
}
impl From<MetaPackageError> for BuildError {
fn from(err: MetaPackageError) -> Self {
BuildError::MetaPackage(err)
}
}
|
use std::ops::Not;
type StockId = String;
#[derive(Debug)]
pub enum Command {
Create { id: StockId },
Update { id: StockId, qty: u32 },
}
#[derive(Debug, Default, Clone)]
pub struct Stock {
pub id: StockId,
pub qty: u32,
}
impl Stock {
pub fn handle(self, cmd: &Command) -> Stock {
match cmd {
Command::Create { id } =>
if self.id.is_empty() && id.is_empty().not() {
Stock { id: id.clone(), ..self }
} else {
self
}
Command::Update { id, qty } =>
if id.is_empty().not() && self.id.eq(id) {
Stock { qty: *qty, ..self }
} else {
self
}
}
}
} |
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Weak;
use common_config::GlobalConfig;
use common_exception::Result;
use common_meta_app::principal::RoleInfo;
use common_meta_app::principal::UserInfo;
use common_settings::Settings;
use parking_lot::RwLock;
use crate::sessions::QueryContextShared;
pub struct SessionContext {
abort: AtomicBool,
settings: Arc<Settings>,
current_catalog: RwLock<String>,
current_database: RwLock<String>,
// The current tenant can be determined by databend-query's config file, or by X-DATABEND-TENANT
// if it's in management mode. If databend-query is not in management mode, the current tenant
// can not be modified at runtime.
current_tenant: RwLock<String>,
// The current user is determined by the authentication phase on each connection. It will not be
// changed during a session.
current_user: RwLock<Option<UserInfo>>,
// Each session have a current role which takes effects, the privileges from the user's other
// roles will not take effect. The user can switch to another available role by `SET ROLE`.
// If the current_role is not set, it takes the user's default role.
current_role: RwLock<Option<RoleInfo>>,
// The role granted to user by external auth provider, when auth_role is provided, the current
// user's all other roles are overridden by this role.
auth_role: RwLock<Option<String>>,
// The client IP from the client.
client_host: RwLock<Option<SocketAddr>>,
io_shutdown_tx: RwLock<Option<Box<dyn FnOnce() + Send + Sync + 'static>>>,
query_context_shared: RwLock<Weak<QueryContextShared>>,
// We store `query_id -> query_result_cache_key` to session context, so that we can fetch
// query result through previous query_id easily.
query_ids_results: RwLock<Vec<(String, Option<String>)>>,
}
impl SessionContext {
pub fn try_create(settings: Arc<Settings>) -> Result<Arc<Self>> {
Ok(Arc::new(SessionContext {
settings,
abort: Default::default(),
current_user: Default::default(),
current_role: Default::default(),
auth_role: Default::default(),
current_tenant: Default::default(),
client_host: Default::default(),
current_catalog: RwLock::new("default".to_string()),
current_database: RwLock::new("default".to_string()),
io_shutdown_tx: Default::default(),
query_context_shared: Default::default(),
query_ids_results: Default::default(),
}))
}
// Get abort status.
pub fn get_abort(&self) -> bool {
self.abort.load(Ordering::Relaxed)
}
// Set abort status.
pub fn set_abort(&self, v: bool) {
self.abort.store(v, Ordering::Relaxed);
}
pub fn get_settings(&self) -> Arc<Settings> {
self.settings.clone()
}
pub fn get_changed_settings(&self) -> Arc<Settings> {
Arc::new(self.settings.get_changed_settings())
}
pub fn apply_changed_settings(&self, changed_settings: Arc<Settings>) -> Result<()> {
self.settings.apply_changed_settings(changed_settings)
}
// Get current catalog name.
pub fn get_current_catalog(&self) -> String {
let lock = self.current_catalog.read();
lock.clone()
}
// Set current catalog.
pub fn set_current_catalog(&self, catalog_name: String) {
let mut lock = self.current_catalog.write();
*lock = catalog_name
}
// Get current database.
pub fn get_current_database(&self) -> String {
let lock = self.current_database.read();
lock.clone()
}
// Set current database.
pub fn set_current_database(&self, db: String) {
let mut lock = self.current_database.write();
*lock = db
}
// Return the current role if it's set. If the current role is not set, it'll take the user's
// default role.
pub fn get_current_role(&self) -> Option<RoleInfo> {
let lock = self.current_role.read();
lock.clone()
}
pub fn set_current_role(&self, role: Option<RoleInfo>) {
let mut lock = self.current_role.write();
*lock = role
}
pub fn get_current_tenant(&self) -> String {
let conf = GlobalConfig::instance();
if conf.query.internal_enable_sandbox_tenant {
let sandbox_tenant = self.settings.get_sandbox_tenant().unwrap_or_default();
if !sandbox_tenant.is_empty() {
return sandbox_tenant;
}
}
if conf.query.management_mode {
let lock = self.current_tenant.read();
if !lock.is_empty() {
return lock.clone();
}
}
conf.query.tenant_id.clone()
}
pub fn set_current_tenant(&self, tenant: String) {
let mut lock = self.current_tenant.write();
*lock = tenant;
}
// Get current user
pub fn get_current_user(&self) -> Option<UserInfo> {
let lock = self.current_user.read();
lock.clone()
}
// Set the current user after authentication
pub fn set_current_user(&self, user: UserInfo) {
let mut lock = self.current_user.write();
*lock = Some(user);
}
// Get auth role. Auth role is the role granted by authenticator.
pub fn get_auth_role(&self) -> Option<String> {
let lock = self.auth_role.read();
lock.clone()
}
pub fn set_auth_role(&self, role: Option<String>) {
let mut lock = self.auth_role.write();
*lock = role;
}
pub fn get_client_host(&self) -> Option<SocketAddr> {
let lock = self.client_host.read();
*lock
}
pub fn set_client_host(&self, sock: Option<SocketAddr>) {
let mut lock = self.client_host.write();
*lock = sock
}
pub fn set_io_shutdown_tx<F: FnOnce() + Send + Sync + 'static>(&self, f: F) {
let mut lock = self.io_shutdown_tx.write();
if let Some(old_fun) = lock.take() {
*lock = Some(Box::new(move || {
old_fun();
f();
}));
return;
}
*lock = Some(Box::new(f));
}
// Take the io_shutdown_tx and the self.io_shuttdown_tx is None.
pub fn take_io_shutdown_tx(&self) -> Option<Box<dyn FnOnce() + Send + Sync + 'static>> {
let mut lock = self.io_shutdown_tx.write();
lock.take()
}
pub fn get_current_query_id(&self) -> Option<String> {
self.query_context_shared
.read()
.upgrade()
.map(|shared| shared.init_query_id.read().clone())
}
pub fn get_query_context_shared(&self) -> Option<Arc<QueryContextShared>> {
let lock = self.query_context_shared.read();
lock.upgrade()
}
pub fn set_query_context_shared(&self, ctx: Weak<QueryContextShared>) {
let mut lock = self.query_context_shared.write();
*lock = ctx
}
pub fn get_query_result_cache_key(&self, query_id: &str) -> Option<String> {
let lock = self.query_ids_results.read();
for (qid, result_cache_key) in (*lock).iter().rev() {
if qid.eq_ignore_ascii_case(query_id) {
return result_cache_key.clone();
}
}
None
}
pub fn update_query_ids_results(&self, query_id: String, value: Option<String>) {
let mut lock = self.query_ids_results.write();
// Here we use reverse iteration, as it is not common to modify elements from earlier.
for (idx, (qid, _)) in (*lock).iter().rev().enumerate() {
if qid.eq_ignore_ascii_case(&query_id) {
// update value iff value is some.
if let Some(v) = value {
(*lock)[idx] = (query_id, Some(v))
}
return;
}
}
lock.push((query_id, value))
}
pub fn get_last_query_id(&self, index: i32) -> String {
let lock = self.query_ids_results.read();
let query_ids_len = lock.len();
let idx = if index < 0 {
query_ids_len as i32 + index
} else {
index
};
if idx < 0 || idx > (query_ids_len - 1) as i32 {
return "".to_string();
}
(*lock)[idx as usize].0.clone()
}
pub fn get_query_id_history(&self) -> HashSet<String> {
let lock = self.query_ids_results.read();
HashSet::from_iter(lock.iter().map(|result| result.clone().0))
}
}
|
use crate::{
context::RpcContext,
v02::{method::call::FunctionCall, types::reply::FeeEstimate},
};
use pathfinder_common::{BlockId, EthereumAddress};
use serde::Deserialize;
use super::common::prepare_handle_and_block;
#[derive(Deserialize, Debug, PartialEq, Eq)]
pub struct EstimateMessageFeeInput {
pub message: FunctionCall,
pub sender_address: EthereumAddress,
pub block_id: BlockId,
}
crate::error::generate_rpc_error_subset!(
EstimateMessageFeeError: BlockNotFound,
ContractNotFound,
ContractError
);
impl From<crate::cairo::ext_py::CallFailure> for EstimateMessageFeeError {
fn from(c: crate::cairo::ext_py::CallFailure) -> Self {
use crate::cairo::ext_py::CallFailure::*;
match c {
NoSuchBlock => Self::BlockNotFound,
NoSuchContract => Self::ContractNotFound,
ExecutionFailed(_) | InvalidEntryPoint => Self::ContractError,
Internal(_) | Shutdown => Self::Internal(anyhow::anyhow!("Internal error")),
}
}
}
pub async fn estimate_message_fee(
context: RpcContext,
input: EstimateMessageFeeInput,
) -> Result<FeeEstimate, EstimateMessageFeeError> {
let (handle, gas_price, when, pending_timestamp, pending_update) =
prepare_handle_and_block(&context, input.block_id).await?;
let result = handle
.estimate_message_fee(
input.sender_address,
input.message.into(),
when,
gas_price,
pending_update,
pending_timestamp,
)
.await?;
Ok(result)
}
#[cfg(test)]
mod tests {
use pathfinder_common::macro_prelude::*;
use pathfinder_common::{
BlockHash, BlockHeader, BlockNumber, BlockTimestamp, Chain, GasPrice, StateUpdate,
};
use pathfinder_storage::{JournalMode, Storage};
use primitive_types::H160;
use starknet_gateway_test_fixtures::class_definitions::{
CAIRO_1_1_0_BALANCE_CASM_JSON, CAIRO_1_1_0_BALANCE_SIERRA_JSON,
};
use tempfile::tempdir;
use super::*;
#[test]
fn test_parse_input_named() {
let input_json = serde_json::json!({
"message": {
"contract_address": "0x57dde83c18c0efe7123c36a52d704cf27d5c38cdf0b1e1edc3b0dae3ee4e374",
"entry_point_selector": "0xc73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be01",
"calldata": ["0x1", "0x2"],
},
"sender_address": "0x0000000000000000000000000000000000000000",
"block_id": {"block_number": 1},
});
let input = EstimateMessageFeeInput::deserialize(&input_json).unwrap();
assert_eq!(
input,
EstimateMessageFeeInput {
message: FunctionCall {
contract_address: contract_address!(
"0x57dde83c18c0efe7123c36a52d704cf27d5c38cdf0b1e1edc3b0dae3ee4e374"
),
entry_point_selector: entry_point!(
"0xc73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be01"
),
calldata: vec![call_param!("0x1"), call_param!("0x2"),],
},
sender_address: EthereumAddress(H160::zero()),
block_id: BlockId::Number(BlockNumber::new_or_panic(1)),
}
);
}
#[test]
fn test_parse_input_positional() {
let input_json = serde_json::json!([
{
"contract_address": "0x57dde83c18c0efe7123c36a52d704cf27d5c38cdf0b1e1edc3b0dae3ee4e374",
"entry_point_selector": "0xc73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be01",
"calldata": ["0x1", "0x2"],
},
"0x0000000000000000000000000000000000000000",
{"block_number": 1},
]);
let input = EstimateMessageFeeInput::deserialize(&input_json).unwrap();
assert_eq!(
input,
EstimateMessageFeeInput {
message: FunctionCall {
contract_address: contract_address!(
"0x57dde83c18c0efe7123c36a52d704cf27d5c38cdf0b1e1edc3b0dae3ee4e374"
),
entry_point_selector: entry_point!(
"0xc73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be01"
),
calldata: vec![call_param!("0x1"), call_param!("0x2"),],
},
sender_address: EthereumAddress(H160::zero()),
block_id: BlockId::Number(BlockNumber::new_or_panic(1)),
}
);
}
enum Setup {
Full,
SkipBlock,
SkipContract,
}
async fn setup(mode: Setup) -> anyhow::Result<RpcContext> {
let dir = tempdir().expect("tempdir");
let mut db_path = dir.path().to_path_buf();
db_path.push("db.sqlite");
let storage = Storage::migrate(db_path, JournalMode::WAL)
.expect("storage")
.create_pool(std::num::NonZeroU32::new(1).expect("one"))
.expect("storage");
{
let mut db = storage.connection().expect("db connection");
let tx = db.transaction().expect("tx");
let class_hash =
class_hash!("0x0484c163658bcce5f9916f486171ac60143a92897533aa7ff7ac800b16c63311");
tx.insert_sierra_class(
&sierra_hash!("0x0484c163658bcce5f9916f486171ac60143a92897533aa7ff7ac800b16c63311"),
CAIRO_1_1_0_BALANCE_SIERRA_JSON,
&casm_hash!("0x0484c163658bcce5f9916f486171ac60143a92897533aa7ff7ac800b16c63311"),
CAIRO_1_1_0_BALANCE_CASM_JSON,
"cairo-lang-starknet 1.1.0",
)
.expect("insert class");
let block_number = BlockNumber::GENESIS + 1;
if !matches!(mode, Setup::SkipBlock) {
let header = BlockHeader::builder()
.with_number(block_number)
.with_timestamp(BlockTimestamp::new_or_panic(1))
.with_gas_price(GasPrice(1))
.finalize_with_hash(BlockHash::ZERO);
tx.insert_block_header(&header).unwrap();
}
if !matches!(mode, Setup::SkipBlock | Setup::SkipContract) {
let contract_address = contract_address!(
"0x57dde83c18c0efe7123c36a52d704cf27d5c38cdf0b1e1edc3b0dae3ee4e374"
);
let state_update =
StateUpdate::default().with_deployed_contract(contract_address, class_hash);
tx.insert_state_update(block_number, &state_update).unwrap();
}
tx.commit().unwrap();
}
let (call_handle, _join_handle) = crate::cairo::ext_py::start(
storage.path().into(),
std::num::NonZeroUsize::try_from(1).unwrap(),
futures::future::pending(),
Chain::Testnet,
)
.await
.unwrap();
let rpc = RpcContext::for_tests()
.with_storage(storage)
.with_call_handling(call_handle);
Ok(rpc)
}
fn input() -> EstimateMessageFeeInput {
EstimateMessageFeeInput {
message: FunctionCall {
contract_address: contract_address!(
"0x57dde83c18c0efe7123c36a52d704cf27d5c38cdf0b1e1edc3b0dae3ee4e374"
),
entry_point_selector: entry_point!(
"0x31ee153a27e249dc4bade6b861b37ef1e1ea0a4c0bf73b7405a02e9e72f7be3"
),
calldata: vec![call_param!("0x1")],
},
sender_address: EthereumAddress(H160::zero()),
block_id: BlockId::Number(BlockNumber::new_or_panic(1)),
}
}
#[tokio::test]
async fn test_estimate_message_fee() {
let expected = FeeEstimate {
gas_consumed: 0x42d1.into(),
gas_price: 1.into(),
overall_fee: 0x42d1.into(),
};
let rpc = setup(Setup::Full).await.expect("RPC context");
let result = estimate_message_fee(rpc, input()).await.expect("result");
assert_eq!(result, expected);
}
#[tokio::test]
async fn test_error_missing_contract() {
let rpc = setup(Setup::SkipContract).await.expect("RPC context");
assert_matches::assert_matches!(
estimate_message_fee(rpc, input()).await,
Err(EstimateMessageFeeError::ContractNotFound)
);
}
#[tokio::test]
async fn test_error_missing_block() {
let rpc = setup(Setup::SkipBlock).await.expect("RPC context");
assert_matches::assert_matches!(
estimate_message_fee(rpc, input()).await,
Err(EstimateMessageFeeError::BlockNotFound)
);
}
#[tokio::test]
async fn test_error_invalid_selector() {
let mut input = input();
let invalid_selector = entry_point!("0xDEADBEEF");
input.message.entry_point_selector = invalid_selector;
let rpc = setup(Setup::Full).await.expect("RPC context");
assert_matches::assert_matches!(
estimate_message_fee(rpc, input).await,
Err(EstimateMessageFeeError::ContractError)
);
}
}
|
#![allow(warnings)]
extern crate rand;
extern crate regex;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate nom;
pub mod imaperror;
#[macro_export]
macro_rules! try_imap {
($old_state:expr, $expr:expr) => (match $expr {
Result::Ok(val) => val,
Result::Err(err) => {
return Result::Err(($old_state, From::from(err)))
}
})
}
pub mod validate_helpers;
pub mod response;
pub mod parser;
pub mod client;
pub mod connection;
pub mod mailbox;
|
extern crate serde_ion;
fn main() {}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Start the random number generator."]
pub tasks_start: TASKS_START,
#[doc = "0x04 - Stop the random number generator."]
pub tasks_stop: TASKS_STOP,
_reserved0: [u8; 248usize],
#[doc = "0x100 - New random number generated and written to VALUE register."]
pub events_valrdy: EVENTS_VALRDY,
_reserved1: [u8; 252usize],
#[doc = "0x200 - Shortcut for the RNG."]
pub shorts: SHORTS,
_reserved2: [u8; 256usize],
#[doc = "0x304 - Interrupt enable set register"]
pub intenset: INTENSET,
#[doc = "0x308 - Interrupt enable clear register"]
pub intenclr: INTENCLR,
_reserved3: [u8; 504usize],
#[doc = "0x504 - Configuration register."]
pub config: CONFIG,
#[doc = "0x508 - RNG random number."]
pub value: VALUE,
}
#[doc = "Start the random number generator."]
pub struct TASKS_START {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start the random number generator."]
pub mod tasks_start;
#[doc = "Stop the random number generator."]
pub struct TASKS_STOP {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop the random number generator."]
pub mod tasks_stop;
#[doc = "New random number generated and written to VALUE register."]
pub struct EVENTS_VALRDY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "New random number generated and written to VALUE register."]
pub mod events_valrdy;
#[doc = "Shortcut for the RNG."]
pub struct SHORTS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Shortcut for the RNG."]
pub mod shorts;
#[doc = "Interrupt enable set register"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt enable set register"]
pub mod intenset;
#[doc = "Interrupt enable clear register"]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt enable clear register"]
pub mod intenclr;
#[doc = "Configuration register."]
pub struct CONFIG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Configuration register."]
pub mod config;
#[doc = "RNG random number."]
pub struct VALUE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "RNG random number."]
pub mod value;
|
use crate::{
cpu::CPU,
debug::widget::Widget,
register::{Flag, Reg16, Registers},
Src,
};
use std::{borrow::Cow, io::Stdout};
use tui::{
backend::CrosstermBackend,
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Style},
widgets::{Block, Borders, Paragraph, Text},
Frame,
};
/// Represents the widget responsible for displaying the current values of
/// the different registers of the CPU.
pub struct RegisterView<'a> {
registers: Registers,
text: Vec<Text<'a>>,
flags: Vec<Text<'a>>,
init: bool,
selected: bool,
title_style: Style,
}
impl<'a> Widget for RegisterView<'a> {
fn refresh(&mut self, cpu: &CPU) {
let space = Text::Raw(Cow::Borrowed(" "));
let registers = vec![
(Reg16::BC, false),
(Reg16::AF, true),
(Reg16::DE, false),
(Reg16::SP, true),
(Reg16::HL, false),
];
let text = registers
.into_iter()
.flat_map(|(r, l)| {
if l {
vec![self.get_register(cpu, r, l)]
} else {
vec![self.get_register(cpu, r, l), space.clone()]
}
})
.collect::<Vec<_>>();
let pc = Reg16::PC.read(cpu);
let pc = Text::Raw(Cow::Owned(format!("PC: 0x{:04x}\n", pc)));
self.text = text
.into_iter()
.chain(std::iter::once(pc))
.collect::<Vec<_>>();
let flags = vec![
(Flag::Z, false),
(Flag::N, true),
(Flag::H, false),
(Flag::C, true),
];
let flags = flags
.into_iter()
.flat_map(|(f, l)| {
if l {
vec![self.get_flag(cpu, f, l)]
} else {
vec![self.get_flag(cpu, f, l), space.clone()]
}
})
.collect::<Vec<_>>();
self.flags = flags;
}
fn draw(&mut self, f: &mut Frame<CrosstermBackend<Stdout>>, chunk: Rect, cpu: &CPU) {
if !self.init {
self.init = true;
self.refresh(cpu);
}
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunk);
let paragraph_registers = Paragraph::new(self.text.iter())
.block(
Block::default()
.title("Registers")
.borders(Borders::ALL)
.title_style(self.title_style),
)
.alignment(Alignment::Center);
let paragraph_flags = Paragraph::new(self.flags.iter())
.block(Block::default().title("Flags").borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(paragraph_registers, chunks[0]);
f.render_widget(paragraph_flags, chunks[1]);
}
fn select(&mut self) {
self.selected = true;
self.title_style = Style::default().fg(Color::Yellow);
}
fn deselect(&mut self) {
self.selected = false;
self.title_style = Style::default();
}
fn is_selected(&self) -> bool {
self.selected
}
}
impl<'a> RegisterView<'a> {
/// Creates a new `RegisterView` widget.
pub fn new() -> RegisterView<'a> {
RegisterView {
registers: Registers::new(),
text: vec![],
flags: vec![],
init: false,
selected: false,
title_style: Style::default(),
}
}
fn get_register(&mut self, cpu: &CPU, reg: Reg16, line_break: bool) -> Text<'a> {
let value = reg.read(cpu);
let line_break = if line_break { "\n" } else { "" };
if value != self.registers.get_16(®) {
self.registers.set_16(®, value);
Text::Styled(
Cow::Owned(format!("{}: 0x{:04x}{}", reg, value, line_break)),
Style::default().bg(Color::White).fg(Color::Black),
)
} else {
Text::Raw(Cow::Owned(format!(
"{}: 0x{:04x}{}",
reg, value, line_break
)))
}
}
fn get_flag(&mut self, cpu: &CPU, flag: Flag, line_break: bool) -> Text<'a> {
let value = flag.read(cpu);
let line_break = if line_break { "\n" } else { "" };
if value != self.registers.get_flag(&flag) {
self.registers.set_flag(&flag, value);
Text::Styled(
Cow::Owned(format!("{}: {}{}", flag, value as u8, line_break)),
Style::default().bg(Color::White).fg(Color::Black),
)
} else {
Text::Raw(Cow::Owned(format!(
"{}: {}{}",
flag, value as u8, line_break
)))
}
}
}
|
use embedded_graphics::{
draw_target::DrawTarget,
pixelcolor::PixelColor,
prelude::Primitive,
primitives::{PrimitiveStyle, PrimitiveStyleBuilder, StrokeAlignment},
Drawable,
};
use embedded_gui::{
widgets::{
border::{Border, BorderProperties},
Widget,
},
WidgetRenderer,
};
use crate::{themes::Theme, EgCanvas, ToRectangle};
pub struct BorderStyle<C>
where
C: PixelColor,
{
color: C,
width: u32,
}
impl<C> BorderStyle<C>
where
C: PixelColor,
{
fn build_style(&self) -> PrimitiveStyle<C> {
PrimitiveStyleBuilder::new()
.stroke_alignment(StrokeAlignment::Inside)
.stroke_color(self.color)
.stroke_width(self.width)
.build()
}
}
impl<C> Default for BorderStyle<C>
where
C: Theme,
{
fn default() -> Self {
Self {
color: C::BORDER_COLOR,
width: 1,
}
}
}
impl<C> BorderProperties for BorderStyle<C>
where
C: PixelColor,
{
type Color = C;
fn get_border_width(&self) -> u32 {
self.width
}
fn set_border_color(&mut self, color: Self::Color) {
self.color = color;
}
}
// TODO: draw target should be clipped to widget's bounds, so this can be restored to Border
impl<W, C, DT> WidgetRenderer<EgCanvas<DT>> for Border<W, BorderStyle<C>>
where
W: Widget + WidgetRenderer<EgCanvas<DT>>,
C: PixelColor,
DT: DrawTarget<Color = C>,
BorderStyle<C>: BorderProperties,
{
fn draw(&mut self, canvas: &mut EgCanvas<DT>) -> Result<(), DT::Error> {
let style = self.border_properties.build_style();
self.bounding_box()
.to_rectangle()
.into_styled(style)
.draw(&mut canvas.target)?;
self.inner.draw(canvas)
}
}
|
//! Terminal I/O stream operations.
//!
//! This API automatically supports setting arbitrary I/O speeds, on any
//! platform that supports them, including Linux and the BSDs.
//!
//! The [`speed`] module contains various predefined speed constants which
//! are more likely to be portable, however any `u32` value can be passed to
//! [`Termios::set_input_speed`], and it will simply fail if the speed is not
//! supported by the platform.
#[cfg(not(any(target_os = "espidf", target_os = "haiku", target_os = "wasi")))]
mod ioctl;
#[cfg(not(target_os = "wasi"))]
mod tc;
#[cfg(not(windows))]
mod tty;
#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
mod types;
#[cfg(not(any(target_os = "espidf", target_os = "haiku", target_os = "wasi")))]
pub use ioctl::*;
#[cfg(not(target_os = "wasi"))]
pub use tc::*;
#[cfg(not(windows))]
pub use tty::*;
#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
pub use types::*;
|
use crate::{
lttp::{
item::{
Armor,
Gloves,
Magic,
Shield,
Sword,
},
RandoLogic,
},
GameState,
};
use serde::Deserialize;
use std::convert::TryInto;
use tracing::error;
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum Rule {
BlueBoomerang,
Bomb,
BombosMedallion,
Book,
Boots,
Bottle,
Bow,
ByrnaCane,
Cape,
EtherMedallion,
FireRod,
Flippers,
Flute,
FluteActivated,
Hammer,
HookShot,
IceRod,
Lantern,
Mirror,
MoonPearl,
Mushroom,
Net,
Powder,
QuakeMedallion,
RedBoomerang,
Shovel,
Silvers,
SomariaCane,
Armor1,
Armor2,
Gloves1,
Gloves2,
Magic1,
Magic2,
Shield1,
Shield2,
Shield3,
Sword1,
Sword2,
Sword3,
Sword4,
BluePendant,
GreenPendant,
RedPendant,
CanBlockLasers,
CanEnterEastDarkWorldDeathMountain,
CanEnterEastDeathMountain,
CanEnterMireArea,
CanEnterNorthEastDarkWorld,
CanEnterNorthWestDarkWorld,
CanEnterSouthDarkWorld,
CanEnterWestDeathMountain,
CanExtendMagic,
CanFly,
CanGoBeatAgahnim1,
BeatAgahnim1,
CanLiftDarkRocks,
CanLiftRocks,
CanLightTorches,
CanMeltThings,
CanShootArrows,
CanSpinSpeed,
GlitchedLinkInDarkWorld,
CanEnterDesertPalace,
MayEnterDesertPalace,
Rupee,
AllSevenCrystals,
BothRedCrystals,
}
impl Rule {
pub fn check(self, state: &GameState) -> bool {
#[allow(clippy::match_same_arms)]
match self {
Rule::BlueBoomerang => state.blue_boomerang,
Rule::Bomb => state.bomb > 0,
Rule::BombosMedallion => state.bombos_medallion,
Rule::Book => state.book,
Rule::Boots => state.boots,
Rule::Bottle => state.bottle,
Rule::Bow => state.bow,
Rule::ByrnaCane => state.cane_byrna,
Rule::Cape => state.cape,
Rule::EtherMedallion => state.ether_medallion,
Rule::FireRod => state.fire_rod,
Rule::Flippers => state.flippers,
Rule::Flute => state.flute,
Rule::FluteActivated => state.flute_activated,
Rule::Hammer => state.hammer,
Rule::HookShot => state.hook_shot,
Rule::IceRod => state.ice_rod,
Rule::Lantern => state.lantern,
Rule::Mirror => state.mirror,
Rule::MoonPearl => state.moon_pearl,
Rule::Mushroom => state.mushroom,
Rule::Net => state.net,
Rule::Powder => state.powder,
Rule::QuakeMedallion => state.quake_medallion,
Rule::RedBoomerang => state.red_boomerang,
Rule::Shovel => state.shovel,
Rule::Silvers => state.silvers,
Rule::SomariaCane => state.cane_somaria,
Rule::Armor1 => state.armor_level >= Armor::BlueMail,
Rule::Armor2 => state.armor_level >= Armor::RedMail,
Rule::Gloves1 => state.gloves >= Gloves::PowerGlove,
Rule::Gloves2 => state.gloves >= Gloves::TitansMitt,
Rule::Magic1 => state.magic_progression >= Magic::Half,
Rule::Magic2 => state.magic_progression >= Magic::Quarter,
Rule::Shield1 => state.shield_level >= Shield::FightersShield,
Rule::Shield2 => state.shield_level >= Shield::RedShield,
Rule::Shield3 => state.shield_level >= Shield::MirrorShield,
Rule::Sword1 => state.sword_level >= Sword::FightersSword,
Rule::Sword2 => state.sword_level >= Sword::MasterSword,
Rule::Sword3 => state.sword_level >= Sword::TemperedSword,
Rule::Sword4 => state.sword_level >= Sword::GoldenSword,
Rule::BluePendant => state.pendant.blue,
Rule::GreenPendant => state.pendant.green,
Rule::RedPendant => state.pendant.red,
Rule::CanLiftRocks => Rule::Gloves1.check(state),
Rule::CanLiftDarkRocks => Rule::Gloves2.check(state),
Rule::CanLightTorches => Rule::FireRod.check(state) || Rule::Lantern.check(state),
Rule::CanMeltThings => {
Rule::FireRod.check(state)
|| (Rule::BombosMedallion.check(state) && Rule::Sword1.check(state))
}
Rule::CanFly => Rule::Flute.check(state),
Rule::CanSpinSpeed => {
Rule::Boots.check(state)
&& (Rule::Sword1.check(state) || Rule::HookShot.check(state))
}
Rule::CanShootArrows => Rule::Bow.check(state),
Rule::CanBlockLasers => Rule::Shield3.check(state),
Rule::CanExtendMagic => Rule::Magic1.check(state) || Rule::Bottle.check(state),
Rule::GlitchedLinkInDarkWorld => {
Rule::MoonPearl.check(state) || Rule::Bottle.check(state)
}
// TODO (#420): Really need to be tracking if Agahnim 1 has already been beaten.
Rule::BeatAgahnim1 => false,
Rule::AllSevenCrystals => {
state.crystal.one
&& state.crystal.two
&& state.crystal.three
&& state.crystal.four
&& state.crystal.five
&& state.crystal.six
&& state.crystal.seven
}
Rule::BothRedCrystals => false,
x => {
error!("check has not been implemented for {:?}", x);
unimplemented!()
}
}
}
pub fn check_quantity(self, state: &GameState, quantity: u16) -> bool {
match self {
Rule::Bomb => state.bomb >= quantity.try_into().unwrap(),
Rule::Bottle => state.bottle_count >= quantity.try_into().unwrap(),
Rule::Rupee => state.rupees >= quantity,
x => {
error!("check_quantity has not been implemented for {:?}", x);
unimplemented!();
}
}
}
#[allow(clippy::too_many_lines)]
pub fn check_with_options(
self,
state: &GameState,
logic: RandoLogic,
agahnim_check: bool,
allow_out_of_logic_glitches: bool,
) -> bool {
match self {
Rule::CanGoBeatAgahnim1 => {
Rule::BeatAgahnim1.check(state)
|| (allow_out_of_logic_glitches || Rule::Lantern.check(state))
&& (Rule::Cape.check(state) || Rule::Sword2.check(state))
&& Rule::Sword1.check(state)
}
Rule::CanEnterNorthEastDarkWorld => {
match logic {
RandoLogic::Glitchless => {
Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
false,
allow_out_of_logic_glitches,
))
|| (Rule::Hammer.check(state)
&& Rule::CanLiftRocks.check(state)
&& Rule::MoonPearl.check(state))
|| (Rule::CanLiftDarkRocks.check(state)
&& Rule::Flippers.check(state)
&& Rule::MoonPearl.check(state))
}
RandoLogic::OverWorldGlitches => {
Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
false,
allow_out_of_logic_glitches,
))
|| (Rule::MoonPearl.check(state)
&& ((Rule::CanLiftDarkRocks.check(state)
&& (Rule::Boots.check(state) || Rule::Flippers.check(state)))
|| (Rule::Hammer.check(state)
&& Rule::CanLiftRocks.check(state))))
|| (Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
false,
allow_out_of_logic_glitches,
) && ((Rule::Mirror.check(state)
&& Rule::CanSpinSpeed.check(state))
|| (Rule::MoonPearl.check(state)
&& (Rule::Mirror.check(state) || Rule::Boots.check(state)))))
}
RandoLogic::MajorGlitches => {
Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
false,
allow_out_of_logic_glitches,
))
|| (Rule::MoonPearl.check(state)
&& (Rule::CanLiftDarkRocks.check(state)
&& (Rule::Boots.check(state) || Rule::Flippers.check(state)))
|| (Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state)))
|| (Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
false,
allow_out_of_logic_glitches,
) && (Rule::Bottle.check(state)
|| (Rule::Mirror.check(state) && Rule::CanSpinSpeed.check(state))
|| (Rule::MoonPearl.check(state)
&& (Rule::Mirror.check(state) || Rule::Boots.check(state)))))
}
}
}
Rule::CanEnterNorthWestDarkWorld => {
match logic {
RandoLogic::Glitchless => {
Rule::MoonPearl.check(state)
&& ((Rule::CanEnterNorthEastDarkWorld.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && Rule::HookShot.check(state)
&& (Rule::Flippers.check(state)
|| Rule::CanLiftRocks.check(state)
|| Rule::Hammer.check(state)))
|| (Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state))
|| Rule::CanLiftDarkRocks.check(state))
}
RandoLogic::OverWorldGlitches => {
Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && (Rule::Mirror.check(state)
|| (Rule::Boots.check(state) && Rule::MoonPearl.check(state)))
|| (Rule::MoonPearl.check(state)
&& (Rule::CanLiftDarkRocks.check(state)
|| (Rule::Hammer.check(state)
&& Rule::CanLiftRocks.check(state))
|| ((Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
)))
&& Rule::HookShot.check(state)
&& (Rule::Hammer.check(state)
|| Rule::CanLiftRocks.check(state)
|| Rule::Flippers.check(state)))))
}
RandoLogic::MajorGlitches => {
Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) || (Rule::MoonPearl.check(state)
&& (Rule::CanLiftDarkRocks.check(state)
|| (Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state))
|| ((Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
)))
&& Rule::HookShot.check(state)
&& (Rule::Hammer.check(state)
|| Rule::CanLiftRocks.check(state)
|| Rule::Flippers.check(state)))))
}
}
}
Rule::CanEnterSouthDarkWorld => {
match logic {
RandoLogic::Glitchless => {
Rule::MoonPearl.check(state)
&& (Rule::CanLiftDarkRocks.check(state)
|| (Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state))
|| (Rule::CanEnterNorthEastDarkWorld.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && (Rule::Hammer.check(state)
|| (Rule::HookShot.check(state)
&& (Rule::Flippers.check(state)
|| Rule::CanLiftRocks.check(state))))))
}
RandoLogic::OverWorldGlitches => {
(Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && (Rule::Mirror.check(state)
|| (Rule::Boots.check(state) && Rule::MoonPearl.check(state))))
|| (Rule::MoonPearl.check(state)
&& (Rule::CanLiftDarkRocks.check(state)
|| (Rule::Hammer.check(state)
&& Rule::CanLiftRocks.check(state))
|| ((Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
)))
&& (Rule::Hammer.check(state)
|| Rule::HookShot.check(state)
&& (Rule::Flippers.check(state)
|| Rule::CanLiftRocks.check(state))))))
}
RandoLogic::MajorGlitches => {
Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) || (Rule::MoonPearl.check(state)
&& (Rule::CanLiftDarkRocks.check(state)
|| (Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state))
|| ((Rule::BeatAgahnim1.check(state)
|| (agahnim_check
&& Rule::CanGoBeatAgahnim1.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
)))
&& (Rule::Hammer.check(state)
|| (Rule::HookShot.check(state)
&& (Rule::Flippers.check(state)
|| Rule::CanLiftRocks.check(state)))))))
}
}
}
Rule::CanEnterMireArea => {
match logic {
RandoLogic::Glitchless => {
Rule::CanFly.check(state) && Rule::CanLiftDarkRocks.check(state)
}
RandoLogic::OverWorldGlitches => {
Rule::CanLiftDarkRocks.check(state)
&& (Rule::CanFly.check(state) || Rule::Boots.check(state))
|| (Rule::MoonPearl.check(state)
&& Rule::Boots.check(state)
&& Rule::CanEnterSouthDarkWorld.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
))
}
RandoLogic::MajorGlitches => {
(Rule::Bottle.check(state)
&& Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
))
|| (Rule::CanLiftDarkRocks.check(state)
&& (Rule::CanFly.check(state)
|| Rule::Bottle.check(state)
|| Rule::Boots.check(state)))
|| (Rule::GlitchedLinkInDarkWorld.check(state)
&& Rule::Boots.check(state)
&& Rule::CanEnterSouthDarkWorld.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
))
}
}
}
Rule::CanEnterWestDeathMountain => {
match logic {
RandoLogic::Glitchless => {
Rule::CanFly.check(state)
|| (Rule::CanLiftRocks.check(state)
&& (allow_out_of_logic_glitches || Rule::Lantern.check(state)))
}
RandoLogic::OverWorldGlitches => {
Rule::Boots.check(state)
|| Rule::CanFly.check(state)
|| (Rule::CanLiftRocks.check(state)
&& (allow_out_of_logic_glitches || Rule::Lantern.check(state)))
}
RandoLogic::MajorGlitches => {
Rule::Boots.check(state)
|| Rule::Bottle.check(state)
|| Rule::CanFly.check(state)
|| (Rule::CanLiftRocks.check(state)
&& (allow_out_of_logic_glitches || Rule::Lantern.check(state)))
}
}
}
Rule::CanEnterEastDeathMountain => {
match logic {
RandoLogic::Glitchless => {
Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && (Rule::HookShot.check(state)
|| (Rule::Mirror.check(state) && Rule::Hammer.check(state)))
}
RandoLogic::OverWorldGlitches => {
Rule::Boots.check(state)
|| (Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && (Rule::HookShot.check(state)
|| (Rule::Mirror.check(state) && Rule::Hammer.check(state))))
}
RandoLogic::MajorGlitches => {
Rule::Boots.check(state)
|| (Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
) && (Rule::HookShot.check(state) || Rule::Mirror.check(state)))
}
}
}
Rule::CanEnterEastDarkWorldDeathMountain => {
match logic {
RandoLogic::Glitchless => {
Rule::CanLiftDarkRocks.check(state)
&& Rule::CanEnterEastDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
)
}
RandoLogic::OverWorldGlitches => {
(Rule::MoonPearl.check(state) && Rule::Book.check(state))
|| ((Rule::CanLiftRocks.check(state)
|| (Rule::Hammer.check(state) && Rule::Book.check(state)))
&& Rule::CanEnterEastDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
))
}
RandoLogic::MajorGlitches => {
Rule::MoonPearl.check(state)
|| (Rule::Bottle.check(state) && Rule::Boots.check(state))
|| ((Rule::CanLiftRocks.check(state)
|| (Rule::Hammer.check(state) && Rule::Boots.check(state)))
&& Rule::CanEnterEastDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
))
|| (Rule::Mirror.check(state)
&& Rule::CanEnterWestDeathMountain.check_with_options(
state,
logic,
agahnim_check,
allow_out_of_logic_glitches,
))
}
}
}
Rule::CanEnterDesertPalace | Rule::MayEnterDesertPalace => true,
x => x.check(state),
}
}
}
|
use std::{
collections::HashMap,
fs::{self, File},
process::{self, Command, Stdio},
str,
time::Duration,
path::{PathBuf, Path},
sync::mpsc,
};
use rbx_dom_weak::{RbxTree, RbxInstanceProperties};
use tempfile::{tempdir, TempDir};
use roblox_install::RobloxStudio;
use crate::{
place::{RunInRbxPlace},
plugin::{RunInRbxPlugin},
message_receiver::{Message, RobloxMessage, MessageReceiver, MessageReceiverOptions},
};
/// A wrapper for process::Child that force-kills the process on drop.
struct KillOnDrop(process::Child);
impl Drop for KillOnDrop {
fn drop(&mut self) {
let _ignored = self.0.kill();
}
}
pub struct PlaceRunnerOptions<'a> {
pub port: u16,
pub timeout: u16,
pub lua_script: &'a str,
}
pub struct PlaceRunner {
_work_dir: TempDir,
place_file_path: PathBuf,
plugin_file_path: PathBuf,
studio_exec_path: PathBuf,
port: u16,
}
impl PlaceRunner {
pub fn new<'a>(tree: RbxTree, options: PlaceRunnerOptions) -> PlaceRunner {
let work_dir = tempdir()
.expect("Could not create temporary directory");
let place_file_path = work_dir.path().join("place.rbxlx");
create_run_in_roblox_place(&place_file_path, tree, options.port);
let studio_install = RobloxStudio::locate()
.expect("Could not find Roblox Studio installation");
let plugin_file_path = studio_install.plugins_path()
.join(format!("run_in_roblox-{}.rbxmx", options.port));
create_run_in_roblox_plugin(&plugin_file_path, options.port, options.timeout, options.lua_script);
PlaceRunner {
// Tie the lifetime of this TempDir to our own lifetime, so that it
// doesn't get cleaned up until we're dropped
_work_dir: work_dir,
place_file_path,
plugin_file_path,
studio_exec_path: studio_install.application_path().to_path_buf(),
port: options.port,
}
}
pub fn run_with_sender(&self, message_processor: mpsc::Sender<Option<RobloxMessage>>) {
let message_receiver = MessageReceiver::start(MessageReceiverOptions {
port: self.port,
});
let _studio_process = KillOnDrop(Command::new(&self.studio_exec_path)
.arg(format!("{}", self.place_file_path.display()))
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("Couldn't start Roblox Studio"));
match message_receiver.recv_timeout(Duration::from_secs(20)).expect("Timeout reached") {
Message::Start => {},
_ => panic!("Invalid first message received"),
}
loop {
let message = message_receiver.recv();
match message {
Message::Start => {},
Message::Stop => {
message_processor.send(None).expect("Could not send stop message");
break;
},
Message::Messages(roblox_messages) => {
for message in roblox_messages.into_iter() {
message_processor.send(Some(message)).expect("Could not send message");
}
}
}
}
message_receiver.stop();
let _ignored = fs::remove_file(&self.plugin_file_path);
}
}
pub fn open_rbx_place_file(path: &Path, extension: &str) -> RbxTree {
let mut file = File::open(path)
.expect("Couldn't open file");
let mut tree = RbxTree::new(RbxInstanceProperties {
name: String::from("Place"),
class_name: String::from("DataModel"),
properties: HashMap::new(),
});
let root_id = tree.get_root_id();
match extension {
"rbxl" => rbx_binary::decode(&mut tree, root_id, &mut file)
.expect("Couldn't decode binary place file"),
"rbxlx" => {
tree = rbx_xml::from_reader_default(file)
.expect("Couldn't decode XML place file");
},
_ => unreachable!(),
}
tree
}
fn create_run_in_roblox_place(place_file_path: &PathBuf, tree: RbxTree, port: u16) {
let place_file = File::create(place_file_path)
.expect("Could not create temporary place file");
let place = RunInRbxPlace::new(tree, port);
place.write(&place_file).expect("Could not serialize temporary place file to disk");
}
fn create_run_in_roblox_plugin<'a>(plugin_file_path: &PathBuf, port: u16, timeout: u16, lua_script: &'a str) {
let plugin = RunInRbxPlugin::new(port, timeout, lua_script);
let plugin_file = File::create(&plugin_file_path)
.expect("Could not create temporary plugin file");
plugin.write(plugin_file).expect("Could not serialize plugin file to disk");
}
|
//! Config-related stuff.
use std::{num::NonZeroUsize, sync::Arc, time::Duration};
use backoff::BackoffConfig;
use compactor_scheduler::SchedulerConfig;
use iox_catalog::interface::Catalog;
use iox_query::exec::Executor;
use iox_time::TimeProvider;
use parquet_file::storage::ParquetStorage;
use crate::components::parquet_files_sink::ParquetFilesSink;
/// Multiple from `max_desired_file_size_bytes` to compute the minimum value for
/// `max_compact_size_bytes`. Since `max_desired_file_size_bytes` is softly enforced, actual file
/// sizes can exceed it. A single compaction job must be able to compact > 1 max sized file, so the
/// multiple should be at least 3.
const MIN_COMPACT_SIZE_MULTIPLE: usize = 3;
/// Config to set up a compactor.
#[derive(Debug, Clone)]
pub struct Config {
/// Metric registry.
pub metric_registry: Arc<metric::Registry>,
/// trace collector
pub trace_collector: Option<Arc<dyn trace::TraceCollector>>,
/// Central catalog.
pub catalog: Arc<dyn Catalog>,
/// Scheduler configuration.
pub scheduler_config: SchedulerConfig,
/// Store holding the actual parquet files.
pub parquet_store_real: ParquetStorage,
/// Store holding temporary files.
pub parquet_store_scratchpad: ParquetStorage,
/// Executor.
pub exec: Arc<Executor>,
/// Time provider.
pub time_provider: Arc<dyn TimeProvider>,
/// Backoff config
pub backoff_config: BackoffConfig,
/// Number of partitions that should be compacted in parallel.
///
/// This should usually be larger than the compaction job concurrency since one partition can spawn multiple
/// compaction jobs.
pub partition_concurrency: NonZeroUsize,
/// Number of compaction jobs concurrently scheduled to DataFusion.
///
/// This should usually be smaller than the partition concurrency since one partition can spawn multiple compaction
/// jobs.
pub df_concurrency: NonZeroUsize,
/// Number of jobs PER PARTITION that move files in and out of the scratchpad.
pub partition_scratchpad_concurrency: NonZeroUsize,
/// Desired max size of compacted parquet files
/// It is a target desired value than a guarantee
pub max_desired_file_size_bytes: u64,
/// Percentage of desired max file size.
/// If the estimated compacted result is too small, no need to split it.
/// This percentage is to determine how small it is:
/// < percentage_max_file_size * max_desired_file_size_bytes:
/// This value must be between (0, 100)
pub percentage_max_file_size: u16,
/// Split file percentage
/// If the estimated compacted result is neither too small nor too large, it will be split
/// into 2 files determined by this percentage.
/// . Too small means: < percentage_max_file_size * max_desired_file_size_bytes
/// . Too large means: > max_desired_file_size_bytes
/// . Any size in the middle will be considered neither too small nor too large
/// This value must be between (0, 100)
pub split_percentage: u16,
/// Maximum duration of the per-partition compaction task.
pub partition_timeout: Duration,
/// Shadow mode.
///
/// This will NOT write / commit any output to the object store or catalog.
///
/// This is mostly useful for debugging.
pub shadow_mode: bool,
/// Enable Scratchpad
///
/// Enabled by default, if this is set to false, the compactor will not use the scratchpad
///
/// This is useful for disabling the scratchpad in production to evaluate the performance & memory impacts.
pub enable_scratchpad: bool,
/// Minimum number of L1 files to compact to L2
/// This is to prevent too many small files
pub min_num_l1_files_to_compact: usize,
/// Only process all discovered partitions once.
pub process_once: bool,
/// Simulate compactor w/o any object store interaction. No parquet
/// files will be read or written.
///
/// This will still use the catalog
///
/// This is useful for testing.
pub simulate_without_object_store: bool,
/// Use the provided [`ParquetFilesSink`] to create parquet files
/// (used for testing)
pub parquet_files_sink_override: Option<Arc<dyn ParquetFilesSink>>,
/// Ensure that ALL errors (including object store errors) result in "skipped" partitions.
///
/// This is mostly useful for testing.
pub all_errors_are_fatal: bool,
/// Maximum number of columns in the table of a partition that will be considered get comapcted
/// If there are more columns, the partition will be skipped
/// This is to prevent too many columns in a table
pub max_num_columns_per_table: usize,
/// max number of files per compaction plan
pub max_num_files_per_plan: usize,
/// Limit the number of partition fetch queries to at most the specified
/// number of queries per second.
///
/// Queries are smoothed over the full second.
pub max_partition_fetch_queries_per_second: Option<usize>,
}
impl Config {
/// Maximum input bytes (from parquet files) per compaction. If there is more data, we ignore
/// the partition (for now) as a self-protection mechanism.
pub fn max_compact_size_bytes(&self) -> usize {
self.max_desired_file_size_bytes as usize * MIN_COMPACT_SIZE_MULTIPLE
}
}
|
use std::net::ToSocketAddrs;
use std::path::Path;
use std::sync::{mpsc, Arc, Mutex};
use std::time::Duration;
use getch_rs::{Getch, Key};
use crate::repl;
use crate::flag;
use crate::setting;
use crate::default;
pub async fn run(
host: &str,
mut flags: flag::Flags,
params: Option<setting::Params>,
){
let tcp_connect_timeout = params.as_ref().map_or_else(|| default::TCP_CONNECT_TIMEOUT, |p| p.tcp_connect_timeout);
let receiver = {
let hosts = to_SocketAddr(host);
if hosts.is_empty() {
eprintln!("Could not connect: {}", host);
std::process::exit(1);
} else {
let mut result = None;
for host in hosts {
let r = std::net::TcpStream::connect_timeout(&host, Duration::from_secs(tcp_connect_timeout));
if r.is_ok() {
result = Some(r);
break;
}
}
result.unwrap_or_else(|| {
eprintln!("Could not connect: {}", host);
std::process::exit(1);
}).unwrap_or_else(|e| {
eprintln!("Could not connect: {}", e);
std::process::exit(1);
})
}
};
receiver.set_read_timeout(Some(Duration::from_secs(1))).unwrap();
let transmitter = receiver.try_clone().expect("Failed to clone from receiver");
let (tx, rx) = mpsc::channel();
// If write_file is already exists
if let Some(write_file) = flags.write_file() {
if Path::new(&write_file).exists() {
if !*flags.append() {
let g = Getch::new();
println!("\"{}\" is already exists!", &write_file);
println!("Press ENTER to continue overwrite");
match g.getch() {
Ok(Key::Char('\r')) => (), // continue
_ => std::process::exit(0), // exit
}
}
} else if *flags.append() {
let g = Getch::new();
println!("\"{}\" is not exists!", &write_file);
println!("Press ENTER to create the file and continue");
match g.getch() {
Ok(Key::Char('\r')) => (), // continue
_ => std::process::exit(0), // exit
}
*flags.append_mut() = false;
}
}
// Check if params exists
if params.is_none() {
*flags.nocolor_mut() = true;
}
println!("Type \"~.\" to exit.");
println!("Connecting... {}", host);
let flags = Arc::new(Mutex::new(flags));
let flags_clone = flags.clone();
tokio::select! {
_ = tokio::spawn(repl::receiver(receiver, rx, flags_clone, params)) => {
println!("\n\x1b[0mDisconnected.");
std::process::exit(0);
}
_ = tokio::spawn(repl::transmitter(transmitter, tx, flags)) => {}
}
}
// Check if the port number is attached
#[allow(non_snake_case)]
fn to_SocketAddr(host: &str) -> Vec<std::net::SocketAddr> {
host.to_socket_addrs().unwrap().collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
#[test]
#[allow(non_snake_case)]
fn test_to_SocketAddr() {
let tests_ipaddr = vec![
(
"127.0.0.1:23",
vec![SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 23))],
),
(
"127.0.0.1:12321",
vec![SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 12321))],
),
(
"::1:23",
vec![SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 23, 0, 0))],
),
(
"[::1]:23",
vec![SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 23, 0, 0))],
),
(
"[::1]:12321",
vec![SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 12321, 0, 0))],
),
];
let tests_hostname = vec![
(
"localhost:23",
vec![SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 23))],
vec![
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 23, 0, 0)),
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 23)),
],
),
];
for (input, expect) in tests_ipaddr {
assert_eq!(to_SocketAddr(input), expect);
}
for (input, expect, or_expect) in tests_hostname {
assert!(
to_SocketAddr(input) == expect
|| to_SocketAddr(input) == or_expect
);
}
}
#[test]
#[should_panic]
#[allow(non_snake_case)]
fn should_fail_to_SocketAddr() {
let tests_ipaddr = vec![
(
"127.0.0.1",
vec![SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 23))],
),
];
for (input, expect) in tests_ipaddr {
assert_eq!(to_SocketAddr(input), expect);
}
}
}
|
// The microcall project is under MIT License.
// Copyright (c) 2018 Tzu-Chiao Yeh
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use futures;
use futures::{Future, Stream};
use futures::future::{FutureResult, ok};
use hyper::{Body, Client, Error, Get, Post, Request, Response, StatusCode};
use hyper;
use hyper::server::{Http, Service};
use tokio_core;
use tokio_core::reactor::Handle;
use uuid::Uuid;
use action;
#[derive(Debug)]
pub struct FunctionMeta {
pub name: String,
}
struct Controller {
client: hyper::Client<hyper::client::HttpConnector, Body>,
handle: Handle,
function_metas: Arc<RwLock<HashMap<Uuid, FunctionMeta>>>,
}
impl Controller {
fn new(
client: hyper::Client<hyper::client::HttpConnector, Body>,
handle: Handle,
function_metas: Arc<RwLock<HashMap<Uuid, FunctionMeta>>>,
) -> Self {
Controller {
client,
handle,
function_metas,
}
}
}
#[inline]
fn get_root() -> Box<FutureResult<Response, Error>> {
Box::new(ok(Response::new()
.with_status(StatusCode::Ok)
.with_body("Hello World!")))
}
fn get_all(
function_metas: Arc<RwLock<HashMap<Uuid, FunctionMeta>>>,
) -> Box<FutureResult<Response, Error>> {
let function_meta_mut_ref = function_metas.read().unwrap();
let mut format_string = String::new();
for (id, meta) in function_meta_mut_ref.iter() {
format_string += format!("{:?}, {:?}\n", *id, *meta).as_str();
}
Box::new(ok(Response::new()
.with_status(StatusCode::Ok)
.with_body(format_string)))
}
fn bad_request() -> Box<FutureResult<Response, Error>> {
let mut response = Response::new();
response.set_status(StatusCode::NotFound);
Box::new(ok(response))
}
impl Service for Controller {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = Box<Future<Item=Self::Response, Error=Self::Error>>;
fn call(&self, req: Request) -> Self::Future {
match (req.method(), req.path()) {
// Root path, say welcome message, remains for performance test.
(&Get, "/") => get_root(),
// Get all existed function instances.
(&Get, "/all") => get_all(self.function_metas.clone()),
// Deploy a function instance.
(&Post, "/deploy") => {
action::post_deploy(req, self.function_metas.clone(), self.client.clone())
}
// Invoke an endpoint/function
_ if &req.path()[0..10] == "/endpoint/" => action::get_endpoint(req, &self.client),
_ if &req.path()[0..14] == "/uds-endpoint/" => {
action::get_uds_endpoint(req, self.handle.clone())
}
// 400
_ => bad_request(),
}
}
}
pub fn launch(addr_str: &str) {
let addr = addr_str.parse().unwrap();
let mut core = tokio_core::reactor::Core::new().unwrap();
let handle = core.handle();
let client_handle = core.handle();
let uds_handle = core.handle();
let client = Client::configure().build(&client_handle);
let function_metas = RwLock::new(HashMap::new());
let arc = Arc::new(function_metas);
let serve = Http::new()
.serve_addr_handle(&addr, &handle, move || {
Ok(Controller::new(
client.clone(),
uds_handle.clone(),
arc.clone(),
))
})
.unwrap();
info!("Listening on http://{}", serve.incoming_ref().local_addr());
let h2 = handle.clone();
handle.spawn(
serve
.for_each(move |conn| {
h2.clone().spawn(conn.map(|_| ()).map_err(|_| ()));
Ok(())
})
.map_err(|_| ()),
);
core.run(futures::future::empty::<(), ()>()).unwrap();
}
|
use crate::{
geom::{Circle, Line, Rectangle, Scalar, Shape, Transform, Triangle, Vector},
graphics::{Color, GpuTriangle, Image, Mesh}
};
use std::iter;
/// Some object that can be drawn to the screen
pub trait Drawable {
/// Draw the object to the Mesh
fn draw<'a>(&self, mesh: &mut Mesh, background: Background<'a>, transform: Transform, z: impl Scalar);
}
/// The background to use for a given drawable
///
/// While each Drawable can define its own behavior, the recommended behavior
/// is that the Image be applied in proportion to the relative position of
/// the vertices. This means the left-most vertex should use the left edge
/// of the image, the right-most vertex should use the right edge of the image, etc.
#[derive(Copy, Clone)]
pub enum Background<'a> {
/// A uniform color background
Col(Color),
/// A textured background
Img(&'a Image),
/// A color and image blended multiplicatively
Blended(&'a Image, Color)
}
impl<'a> Background<'a> {
/// Return either the stored Image or None
pub fn image(&self) -> Option<&Image> {
match self {
Background::Col(_) => None,
Background::Img(img) | Background::Blended(img, _) => Some(img),
}
}
/// Return either the stored Color or Color::WHITE
pub fn color(&self) -> Color {
match self {
Background::Col(color) |Background::Blended(_, color) => *color,
Background::Img(_) => Color::WHITE,
}
}
}
impl Drawable for Vector {
fn draw<'a>(&self, mesh: &mut Mesh, bkg: Background<'a>, trans: Transform, z: impl Scalar) {
Rectangle::new(*self, Vector::ONE).draw(mesh, bkg, trans, z);
}
}
impl Drawable for Rectangle {
fn draw<'a>(&self, mesh: &mut Mesh, bkg: Background<'a>, trans: Transform, z: impl Scalar) {
let trans = Transform::translate(self.top_left() + self.size() / 2)
* trans
* Transform::translate(-self.size() / 2)
* Transform::scale(self.size());
let tex_trans = bkg.image().map(|img| img.projection(Rectangle::new_sized((1, 1))));
let offset = mesh.add_positioned_vertices(
[Vector::ZERO, Vector::X, Vector::ONE, Vector::Y].iter().cloned(), trans, tex_trans, bkg);
mesh.triangles.push(GpuTriangle::new(offset, [0, 1, 2], z, bkg));
mesh.triangles.push(GpuTriangle::new(offset, [2, 3, 0], z, bkg));
}
}
impl Drawable for Circle {
fn draw<'a>(&self, mesh: &mut Mesh, bkg: Background<'a>, trans: Transform, z: impl Scalar) {
let trans = Transform::translate(self.center())
* trans
* Transform::scale(Vector::ONE * self.radius);
let tex_trans = bkg.image().map(|img| img.projection(self.bounding_box()));
let offset = mesh.add_positioned_vertices(CIRCLE_POINTS.iter().cloned(), trans, tex_trans, bkg);
mesh.triangles.extend(iter::repeat(z)
.take(CIRCLE_POINTS.len() - 1)
.enumerate()
.map(|(index, z)| GpuTriangle::new(offset, [0, index as u32, index as u32 + 1], z, bkg)));
}
}
impl Drawable for Triangle {
fn draw<'a>(&self, mesh: &mut Mesh, bkg: Background<'a>, trans: Transform, z: impl Scalar) {
let trans = Transform::translate(self.center())
* trans
* Transform::translate(-self.center());
let tex_transform = bkg.image().map(|image| image.projection(self.bounding_box()));
let offset = mesh.add_positioned_vertices([self.a, self.b, self.c].iter().cloned(),
trans, tex_transform, bkg);
mesh.triangles.push(GpuTriangle::new(offset, [0, 1, 2], z, bkg));
}
}
impl Drawable for Line {
fn draw<'a>(&self, mesh: &mut Mesh, bkg: Background<'a>, trans: Transform, z: impl Scalar) {
// create rectangle in right size
let rect = Rectangle::new((self.a.x, self.a.y + self.t / 2.0), (self.a.distance(self.b), self.t));
let trans = Transform::translate((self.a + self.b) / 2 - rect.center())
* trans
* Transform::rotate((self.b - self.a).angle());
rect.draw(mesh, bkg, trans, z);
}
}
// Until there's serious compile-time calculations in Rust,
// it's best to just pre-write the points on a rasterized circle
// Python script to generate the array:
/*
import math
from math import pi
def points_on_circumference(center=(0, 0), r=50, n=100):
n -= 1
return [
(
center[0]+(math.cos(2 * pi / n * x) * r), # x
center[1] + (math.sin(2 * pi / n * x) * r) # y
) for x in range(0, n + 1)]
number_of_points = 64
points = points_on_circumference(center=(0,0),r=1, n=number_of_points)
print("const CIRCLE_POINTS: [Vector; %i] = [" % number_of_points)
for point in points:
print(" Vector { x: %s, y: %s }," % (point[0], point[1]))
print("];")
*/
const CIRCLE_POINTS: [Vector; 64] = [
Vector { x: 1.0, y: 0.0 },
Vector { x: 0.9950307753654014, y: 0.09956784659581666 },
Vector { x: 0.9801724878485438, y: 0.19814614319939758 },
Vector { x: 0.9555728057861407, y: 0.2947551744109042 },
Vector { x: 0.9214762118704076, y: 0.38843479627469474 },
Vector { x: 0.8782215733702285, y: 0.47825397862131824 },
Vector { x: 0.8262387743159949, y: 0.5633200580636221 },
Vector { x: 0.766044443118978, y: 0.6427876096865394 },
Vector { x: 0.6982368180860729, y: 0.7158668492597184 },
Vector { x: 0.6234898018587336, y: 0.7818314824680298 },
Vector { x: 0.5425462638657594, y: 0.8400259231507714 },
Vector { x: 0.4562106573531629, y: 0.8898718088114687 },
Vector { x: 0.365341024366395, y: 0.9308737486442042 },
Vector { x: 0.27084046814300516, y: 0.962624246950012 },
Vector { x: 0.17364817766693022, y: 0.9848077530122081 },
Vector { x: 0.07473009358642417, y: 0.9972037971811801 },
Vector { x: -0.024930691738072913, y: 0.9996891820008162 },
Vector { x: -0.12434370464748516, y: 0.9922392066001721 },
Vector { x: -0.22252093395631434, y: 0.9749279121818236 },
Vector { x: -0.31848665025168454, y: 0.9479273461671317 },
Vector { x: -0.41128710313061156, y: 0.9115058523116731 },
Vector { x: -0.5000000000000002, y: 0.8660254037844385 },
Vector { x: -0.58374367223479, y: 0.8119380057158564 },
Vector { x: -0.6616858375968595, y: 0.7497812029677341 },
Vector { x: -0.7330518718298263, y: 0.6801727377709194 },
Vector { x: -0.7971325072229225, y: 0.6038044103254774 },
Vector { x: -0.8532908816321556, y: 0.5214352033794981 },
Vector { x: -0.900968867902419, y: 0.43388373911755823 },
Vector { x: -0.9396926207859084, y: 0.3420201433256685 },
Vector { x: -0.969077286229078, y: 0.24675739769029342 },
Vector { x: -0.9888308262251285, y: 0.14904226617617428 },
Vector { x: -0.9987569212189223, y: 0.04984588566069704 },
Vector { x: -0.9987569212189223, y: -0.04984588566069723 },
Vector { x: -0.9888308262251285, y: -0.14904226617617447 },
Vector { x: -0.969077286229078, y: -0.24675739769029362 },
Vector { x: -0.9396926207859084, y: -0.34202014332566866 },
Vector { x: -0.9009688679024191, y: -0.433883739117558 },
Vector { x: -0.8532908816321555, y: -0.5214352033794983 },
Vector { x: -0.7971325072229224, y: -0.6038044103254775 },
Vector { x: -0.7330518718298262, y: -0.6801727377709195 },
Vector { x: -0.6616858375968594, y: -0.7497812029677342 },
Vector { x: -0.5837436722347898, y: -0.8119380057158565 },
Vector { x: -0.4999999999999996, y: -0.8660254037844388 },
Vector { x: -0.4112871031306116, y: -0.9115058523116731 },
Vector { x: -0.3184866502516841, y: -0.9479273461671318 },
Vector { x: -0.2225209339563146, y: -0.9749279121818236 },
Vector { x: -0.12434370464748495, y: -0.9922392066001721 },
Vector { x: -0.024930691738073156, y: -0.9996891820008162 },
Vector { x: 0.07473009358642436, y: -0.9972037971811801 },
Vector { x: 0.17364817766693083, y: -0.984807753012208 },
Vector { x: 0.2708404681430051, y: -0.962624246950012 },
Vector { x: 0.3653410243663954, y: -0.9308737486442041 },
Vector { x: 0.45621065735316285, y: -0.8898718088114687 },
Vector { x: 0.5425462638657597, y: -0.8400259231507713 },
Vector { x: 0.6234898018587334, y: -0.7818314824680299 },
Vector { x: 0.698236818086073, y: -0.7158668492597183 },
Vector { x: 0.7660444431189785, y: -0.6427876096865389 },
Vector { x: 0.8262387743159949, y: -0.563320058063622 },
Vector { x: 0.8782215733702288, y: -0.4782539786213178 },
Vector { x: 0.9214762118704076, y: -0.38843479627469474 },
Vector { x: 0.9555728057861408, y: -0.2947551744109039 },
Vector { x: 0.9801724878485438, y: -0.19814614319939772 },
Vector { x: 0.9950307753654014, y: -0.09956784659581641 },
Vector { x: 1.0, y: 0.0 },
];
|
// 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_base::base::tokio;
use common_exception::Result;
use common_meta_app::storage::StorageFsConfig;
use common_meta_app::storage::StorageParams;
use common_meta_app::storage::StorageS3Config;
use databend_query::sessions::TableContext;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_storage_accessor_s3() -> Result<()> {
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/bucket"))
.respond_with(ResponseTemplate::new(404))
.mount(&mock_server)
.await;
let mut conf = crate::tests::ConfigBuilder::create().config();
conf.storage.params = StorageParams::S3(StorageS3Config {
region: "us-east-2".to_string(),
endpoint_url: mock_server.uri(),
bucket: "bucket".to_string(),
disable_credential_loader: true,
..Default::default()
});
let (_guard, qctx) = crate::tests::create_query_context_with_config(conf, None).await?;
let _ = qctx.get_data_operator()?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_storage_accessor_fs() -> Result<()> {
let mut conf = crate::tests::ConfigBuilder::create().config();
conf.storage.params = StorageParams::Fs(StorageFsConfig {
root: "/tmp".to_string(),
});
let (_guard, qctx) = crate::tests::create_query_context_with_config(conf, None).await?;
let _ = qctx.get_data_operator()?;
Ok(())
}
|
use std::{collections::HashMap, fs, path::PathBuf, process::Command, sync::Arc};
use ide::{AnalysisHost, Change, FileId, InlayKind, TextSize};
use rust_analyzer::cli::load_cargo::{load_workspace_at, LoadCargoConfig};
use toml::Value;
use vfs::VfsPath;
use super::*;
/// A no-op preprocessor.
pub struct Nop;
impl Nop {
pub fn new() -> Nop {
Nop
}
}
const CODE_START: &str = "```rust";
const CODE_END: &str = "```";
const DEFAULT_CSS: &str = include_str!("default.css");
fn run_on_codes<F: FnMut(&str) -> String>(text: &str, mut run_on_code: F, css: &str) -> String {
let mut result = String::new();
let mut iter = text.split(CODE_START);
result += css;
result += iter.next().unwrap();
for x in iter {
result += r#"<pre><code class="language-rust hljs">"#;
let (code, content) = x.split_once(CODE_END).unwrap();
result += &run_on_code(code);
result += "</code></pre>";
result += content;
}
result
}
fn raw_code(code: &str) -> String {
let mut result = "".to_string();
for l in code.lines() {
if let Some(x) = l.strip_prefix("# ") {
result += x;
} else {
result += l;
}
result += "\n";
}
result
}
fn escape_html_char(c: char) -> String {
match c {
'<' => "<",
'>' => ">",
'&' => "&",
_ => return c.to_string(),
}
.to_string()
}
#[derive(Default)]
struct HoverStore {
map: HashMap<String, usize>,
}
impl HoverStore {
fn get_id(&mut self, hover: String) -> usize {
if let Some(x) = self.map.get(&hover) {
return *x;
}
let id = self.map.len();
self.map.insert(hover, id);
id
}
fn to_vec(self) -> Vec<String> {
let mut r = vec!["".to_string(); self.map.len()];
for (k, v) in self.map {
r[v] = k;
}
r
}
}
struct MyRA {
host: AnalysisHost,
file_id: FileId,
}
impl MyRA {
fn setup(cargo_toml: Option<PathBuf>) -> Result<Self, Error> {
let path_str = "/tmp/mdbook-ra/playcrate";
let p = PathBuf::from(path_str);
if p.exists() {
fs::remove_dir_all(&p)?;
}
Command::new("cargo")
.args(["init", "--bin", path_str])
.spawn()?
.wait()?;
if let Some(p) = cargo_toml {
fs::copy(p, "/tmp/mdbook-ra/playcrate/Cargo.toml").unwrap();
}
let no_progress = &|_| ();
let load_config = LoadCargoConfig {
load_out_dirs_from_check: true,
with_proc_macro: true,
prefill_caches: false,
};
let (host, vfs, _) = load_workspace_at(&p, &Default::default(), &load_config, no_progress)?;
Ok(MyRA {
host,
file_id: vfs
.file_id(&VfsPath::new_real_path(format!("{}/src/main.rs", path_str)))
.unwrap(),
})
}
fn analysis(&mut self, code: String) -> Analysis {
let mut change = Change::new();
change.change_file(self.file_id, Some(Arc::new(code)));
self.host.apply_change(change);
self.host.analysis()
}
}
#[derive(Default)]
struct MyConfig {
disabled_by_default: bool,
cargo_toml: Option<PathBuf>,
custom_css: Option<PathBuf>,
}
impl Preprocessor for Nop {
fn name(&self) -> &str {
"ra"
}
fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book, Error> {
let config = {
let mut c = MyConfig::default();
if let Some(m) = ctx.config.get_preprocessor(self.name()) {
if m.get("disabled_by_default") == Some(&true.into()) {
c.disabled_by_default = true;
}
if let Some(Value::String(s)) = m.get("cargo_toml") {
c.cargo_toml = Some(PathBuf::from(s));
}
if let Some(Value::String(s)) = m.get("custom_css") {
c.custom_css = Some(PathBuf::from(s));
}
}
c
};
let css = format!(
"<style>\n{}</style>",
match config.custom_css {
Some(p) => fs::read_to_string(p).unwrap(),
None => DEFAULT_CSS.to_string(),
}
);
let mut ra = MyRA::setup(config.cargo_toml)?;
let disabled = config.disabled_by_default;
book.for_each_mut(|book_item| {
let chapter = if let mdbook::BookItem::Chapter(c) = book_item {
c
} else {
eprintln!("{:#?}", book_item);
return;
};
let mut hover_store = HoverStore::default();
chapter.content = run_on_codes(&chapter.content, |original_code| {
let (flags, code) = original_code.split_once("\n").unwrap();
let main_added = &format!("# #![allow(unused)]\n# fn main() {{\n{}# }}", code);
let code = if code.contains("fn main") {
code
} else {
&main_added
};
eprintln!("{}", flags);
if flags.contains("ra_disabled") || disabled && !flags.contains("ra_enabled") {
return original_code.to_string();
}
let mut result = String::new();
let analysis = ra.analysis(raw_code(code).to_string());
let file_id = ra.file_id;
let static_index = StaticIndex::compute(&analysis);
let file = static_index
.files
.into_iter()
.find(|x| x.file_id == file_id)
.unwrap();
let mut additions: HashMap<usize, String> = Default::default();
let mut add = |r: TextSize, s: String| {
*additions.entry(r.into()).or_insert("".to_string()) += &s;
};
for (r, id) in file.tokens {
let token = static_index.tokens.get(id).unwrap();
let hover_string = token
.hover
.as_ref()
.map(|x| &x.markup)
.map(|x| x.to_string());
let hover_string = if let Some(x) = hover_string {
x
} else {
continue;
};
let hover_id = hover_store.get_id(hover_string);
add(
r.start(),
format!(r#"<span class="ra" data-hover="{}">"#, hover_id),
);
add(r.end(), "</span>".to_string());
}
for hint in file.inlay_hints {
if matches!(hint.kind, InlayKind::TypeHint | InlayKind::ChainingHint) {
add(
hint.range.end(),
format!(
r#"<span class="inlay-hint">: {}</span>"#,
{
let mut result = "".to_string();
for c in hint.label.to_string().chars() {
result += &escape_html_char(c);
}
result
}
),
);
} else {
add(
hint.range.start(),
format!(
r#"<span class="inlay-hint">{}: </span>"#,
hint.label.to_string()
),
);
}
}
let mut i = 0;
for l in code.lines() {
if let Some(x) = l.strip_prefix("# ") {
i += x.len() + 1;
result += r#"<span class="boring">"#;
result += x;
result += "\n";
result += r#"</span>"#;
continue;
}
for c in l.chars() {
if let Some(x) = additions.get(&i) {
result += x;
}
result += &escape_html_char(c);
i += 1;
}
result += "\n";
i += 1;
}
result
}, &css);
let mut json = "".to_string();
for x in &hover_store.to_vec() {
json += &format!("'{}',", markdown_to_html(x, &Default::default()).replace("'", "#$%").replace('\n', "\\n").replace("<pre", "<per").replace("<code", "<cide"));
}
chapter.content += &format!(
r#"
<script src="https://unpkg.com/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://unpkg.com/tippy.js@6.3.2/dist/tippy-bundle.umd.min.js" integrity="sha384-vApKv6LkBdPwmt/fNiQrBCVCZvuniXpG0b5UZhVrGAq1zXdZRSsPcWjGdVxkZJtX" crossorigin="anonymous"></script>
<script>
const hoverData = [{}].map((x)=>x.replaceAll('#$%', "'").replaceAll('<per', '<pre').replaceAll('<cide', '<code'));
window.onload = () => {{
console.log("hello");
tippy('.ra', {{
content: (x) => {{
const div = document.createElement('div');
div.innerHTML = hoverData[x.dataset.hover];
div.className = 'hover-holder';
div.querySelectorAll('code').forEach((y) => y.innerHTML = hljs.highlight('rust', y.innerText).value);
return div;
}},
allowHTML: true,
delay: [200, 0],
interactive: true,
maxWidth: '80vw',
appendTo: document.querySelector('.content'),
}});
}};
</script>
"#,
json,
);
});
Ok(book)
}
fn supports_renderer(&self, renderer: &str) -> bool {
renderer != "not-supported"
}
}
|
//! Convenience macros for logging and introspecting HCL2 parse results.
#[macro_export]
macro_rules! interrobang {
($text:expr) => {
println!("########################################");
println!("-- text:");
println!("<<<\n{}\n>>>", $text);
};
($text:expr, $result:expr) => {
interrobang!($text);
println!("-- parse result:");
match &$result {
Ok((ref remaining, ref ast)) => {
println!("Parse ok!");
println!("-- remaining:");
println!("<<<{:#?}>>>", remaining.0);
println!("-- ast:");
println!("{:#?}", ast);
}
Err(ref e) => {
println!("Parse failed, error:");
println!("<<<\n{:#?}\n>>>", e);
}
}
};
}
/// Fully parse a string, but don't check the resulting AST.
///
/// ```
/// # #[macro_use] extern crate hcl_parser;
///
/// use hcl_parser::hcl2::parser::parse;
///
/// fn main() {
/// let text = "foo = true\n";
/// try_recognize!(parse, text);
/// }
/// ```
#[macro_export]
macro_rules! try_recognize {
($func:ident, $text:expr) => {
let result = $func($text.into());
interrobang!($text, result);
let (remaining, ast) = result.expect("Parse failure");
assert!(remaining.is_empty());
};
}
/// Fully parse a string into a specific AST - or `panic` while trying.
///
/// ```
/// # #[macro_use] extern crate hcl_parser;
///
/// use hcl_parser::hcl2::parser::*;
/// use hcl_parser::hcl2::ast::*;
///
/// fn main() {
/// let text = "foo = true\n";
/// let expected = Body(
/// vec![
/// Attribute {
/// ident: "foo".into(),
/// expr: Expression::ExprTerm(true.into()),
/// }.into()
/// ]
/// );
///
/// try_parse_to!(parse, text, expected);
/// }
/// ```
#[macro_export]
macro_rules! try_parse_to {
($func:ident, $text:expr, $expected:expr) => {
let result = $func($text.into());
interrobang!($text, result);
let (remaining, ast) = result.expect("Parse failure");
assert!(remaining.is_empty());
assert_eq!($expected, ast);
};
}
|
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
output_manager_service::TxId,
transaction_service::{
error::{TransactionServiceError, TransactionServiceProtocolError},
handle::TransactionEvent,
service::TransactionServiceResources,
storage::database::{TransactionBackend, TransactionStatus},
},
};
use futures::{channel::mpsc::Receiver, FutureExt, StreamExt};
use log::*;
use std::{convert::TryFrom, sync::Arc, time::Duration};
use tari_comms::types::CommsPublicKey;
use tari_comms_dht::{domain_message::OutboundDomainMessage, outbound::OutboundEncryption};
use tari_core::{
base_node::proto::{
base_node as BaseNodeProto,
base_node::{
base_node_service_request::Request as BaseNodeRequestProto,
base_node_service_response::Response as BaseNodeResponseProto,
},
},
mempool::{
proto::mempool as MempoolProto,
service::{MempoolResponse, MempoolServiceResponse},
TxStorageResponse,
},
transactions::transaction::TransactionOutput,
};
use tari_crypto::tari_utilities::{hex::Hex, Hashable};
use tari_p2p::tari_message::TariMessageType;
use tokio::time::delay_for;
const LOG_TARGET: &str = "wallet::transaction_service::protocols::chain_monitoring_protocol";
/// This protocol defines the process of monitoring a mempool and base node to detect when a Broadcast transaction is
/// Mined or leaves the mempool in which case it should be cancelled
pub struct TransactionChainMonitoringProtocol<TBackend>
where TBackend: TransactionBackend + Clone + 'static
{
id: u64,
tx_id: TxId,
resources: TransactionServiceResources<TBackend>,
timeout: Duration,
base_node_public_key: CommsPublicKey,
mempool_response_receiver: Option<Receiver<MempoolServiceResponse>>,
base_node_response_receiver: Option<Receiver<BaseNodeProto::BaseNodeServiceResponse>>,
}
impl<TBackend> TransactionChainMonitoringProtocol<TBackend>
where TBackend: TransactionBackend + Clone + 'static
{
pub fn new(
id: u64,
tx_id: TxId,
resources: TransactionServiceResources<TBackend>,
timeout: Duration,
base_node_public_key: CommsPublicKey,
mempool_response_receiver: Receiver<MempoolServiceResponse>,
base_node_response_receiver: Receiver<BaseNodeProto::BaseNodeServiceResponse>,
) -> Self
{
Self {
id,
tx_id,
resources,
timeout,
base_node_public_key,
mempool_response_receiver: Some(mempool_response_receiver),
base_node_response_receiver: Some(base_node_response_receiver),
}
}
/// The task that defines the execution of the protocol.
pub async fn execute(mut self) -> Result<u64, TransactionServiceProtocolError> {
let mut mempool_response_receiver = self
.mempool_response_receiver
.take()
.ok_or_else(|| TransactionServiceProtocolError::new(self.id, TransactionServiceError::InvalidStateError))?;
let mut base_node_response_receiver = self
.base_node_response_receiver
.take()
.ok_or_else(|| TransactionServiceProtocolError::new(self.id, TransactionServiceError::InvalidStateError))?;
trace!(
target: LOG_TARGET,
"Starting chain monitoring protocol for TxId: {} with Protocol ID: {}",
self.tx_id,
self.id
);
// This is the main loop of the protocol and following the following steps
// 1) Check transaction being monitored is still in the Broadcast state and needs to be monitored
// 2) Send a MempoolRequest::GetTxStateWithExcessSig to Mempool and a Mined? Request to base node
// 3) Wait for both a Mempool response and Base Node response for the correct Id OR a Timeout
// a) If the Tx is not in the mempool AND is not mined the protocol ends and Tx should be cancelled
// b) If the Tx is in the mempool AND not mined > perform another iteration
// c) If the Tx is in the mempool AND mined then update the status of the Tx and end the protocol
// c) Timeout is reached > Start again
loop {
let completed_tx = match self.resources.db.get_completed_transaction(self.tx_id).await {
Ok(tx) => tx,
Err(e) => {
error!(
target: LOG_TARGET,
"Cannot find Completed Transaction (TxId: {}) referred to by this Chain Monitoring Protocol: \
{:?}",
self.tx_id,
e
);
return Err(TransactionServiceProtocolError::new(
self.id,
TransactionServiceError::TransactionDoesNotExistError,
));
},
};
if completed_tx.status != TransactionStatus::Broadcast {
debug!(
target: LOG_TARGET,
"Transaction (TxId: {}) no longer in Broadcast state and will stop being monitored for being Mined",
self.tx_id
);
return Ok(self.id);
}
let mut hashes = Vec::new();
for o in completed_tx.transaction.body.outputs() {
hashes.push(o.hash());
}
info!(
target: LOG_TARGET,
"Sending Transaction Mined? request for TxId: {} and Kernel Signature {} to Base Node (Contains {} \
outputs)",
completed_tx.tx_id,
completed_tx.transaction.body.kernels()[0]
.excess_sig
.get_signature()
.to_hex(),
hashes.len(),
);
// Send Mempool query
let tx_excess_sig = completed_tx.transaction.body.kernels()[0].excess_sig.clone();
let mempool_request = MempoolProto::MempoolServiceRequest {
request_key: self.id,
request: Some(MempoolProto::mempool_service_request::Request::GetTxStateWithExcessSig(
tx_excess_sig.into(),
)),
};
self.resources
.outbound_message_service
.send_direct(
self.base_node_public_key.clone(),
OutboundEncryption::None,
OutboundDomainMessage::new(TariMessageType::MempoolRequest, mempool_request.clone()),
)
.await
.map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?;
// Send Base Node query
let request = BaseNodeRequestProto::FetchUtxos(BaseNodeProto::HashOutputs { outputs: hashes });
let service_request = BaseNodeProto::BaseNodeServiceRequest {
request_key: self.id,
request: Some(request),
};
self.resources
.outbound_message_service
.send_direct(
self.base_node_public_key.clone(),
OutboundEncryption::None,
OutboundDomainMessage::new(TariMessageType::BaseNodeRequest, service_request),
)
.await
.map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?;
let mut delay = delay_for(self.timeout).fuse();
let mut received_mempool_response = None;
let mut mempool_response_received = false;
let mut base_node_response_received = false;
// Loop until both a Mempool response AND a Base node response is received OR the Timeout expires.
loop {
futures::select! {
mempool_response = mempool_response_receiver.select_next_some() => {
//We must first check the Base Node response before checking the mempool repsonse so we will keep it for the end of the round
received_mempool_response = Some(mempool_response);
mempool_response_received = true;
},
base_node_response = base_node_response_receiver.select_next_some() => {
//We can immediately check the Base Node Response
if self
.handle_base_node_response(completed_tx.tx_id, base_node_response)
.await?
{
// Tx is mined!
return Ok(self.id);
}
base_node_response_received = true;
},
() = delay => {
break;
},
}
// If we have received both responses from this round we can check the mempool status and then continue
// to next round
if received_mempool_response.is_some() && base_node_response_received {
if let Some(mempool_response) = received_mempool_response {
if !self
.handle_mempool_response(completed_tx.tx_id, mempool_response)
.await?
{
return Err(TransactionServiceProtocolError::new(
self.id,
TransactionServiceError::MempoolRejection,
));
}
}
break;
}
}
if mempool_response_received && base_node_response_received {
info!(
target: LOG_TARGET,
"Base node and Mempool response received. TxId: {:?} not mined yet.", completed_tx.tx_id,
);
// Finish out the rest of this period before moving onto next round
delay.await;
}
info!(
target: LOG_TARGET,
"Chain monitoring process timed out for Transaction TX_ID: {}", completed_tx.tx_id
);
let _ = self
.resources
.event_publisher
.send(Arc::new(TransactionEvent::TransactionMinedRequestTimedOut(
completed_tx.tx_id,
)))
.map_err(|e| {
trace!(
target: LOG_TARGET,
"Error sending event, usually because there are no subscribers: {:?}",
e
);
e
});
}
}
async fn handle_mempool_response(
&mut self,
tx_id: TxId,
response: MempoolServiceResponse,
) -> Result<bool, TransactionServiceProtocolError>
{
// Handle a receive Mempool Response
match response.response {
MempoolResponse::Stats(_) => {
error!(target: LOG_TARGET, "Invalid Mempool response variant");
},
MempoolResponse::State(_) => {
error!(target: LOG_TARGET, "Invalid Mempool response variant");
},
MempoolResponse::TxStorage(ts) => {
let completed_tx = match self.resources.db.get_completed_transaction(tx_id).await {
Ok(tx) => tx,
Err(e) => {
error!(
target: LOG_TARGET,
"Cannot find Completed Transaction (TxId: {}) referred to by this Chain Monitoring \
Protocol: {:?}",
self.tx_id,
e
);
return Err(TransactionServiceProtocolError::new(
self.id,
TransactionServiceError::TransactionDoesNotExistError,
));
},
};
match completed_tx.status {
TransactionStatus::Broadcast => match ts {
// Getting this response means the Mempool Rejected this transaction so it will be
// cancelled.
TxStorageResponse::NotStored => {
error!(
target: LOG_TARGET,
"Mempool response received for TxId: {:?}. Transaction was REJECTED. Cancelling \
transaction.",
tx_id
);
if let Err(e) = self
.resources
.output_manager_service
.cancel_transaction(completed_tx.tx_id)
.await
{
error!(
target: LOG_TARGET,
"Failed to Cancel outputs for TX_ID: {} after failed sending attempt with error \
{:?}",
completed_tx.tx_id,
e
);
}
if let Err(e) = self.resources.db.cancel_completed_transaction(completed_tx.tx_id).await {
error!(
target: LOG_TARGET,
"Failed to Cancel TX_ID: {} after failed sending attempt with error {:?}",
completed_tx.tx_id,
e
);
}
let _ = self
.resources
.event_publisher
.send(Arc::new(TransactionEvent::TransactionCancelled(self.id)))
.map_err(|e| {
trace!(
target: LOG_TARGET,
"Error sending event, usually because there are no subscribers: {:?}",
e
);
e
});
return Err(TransactionServiceProtocolError::new(
self.id,
TransactionServiceError::MempoolRejection,
));
},
// Any other variant of this enum means the transaction has been received by the
// base_node and is in one of the various mempools
_ => {
// If this transaction is still in the Completed State it should be upgraded to the
// Broadcast state
info!(
target: LOG_TARGET,
"Completed Transaction (TxId: {} and Kernel Excess Sig: {}) detected in Base Node \
Mempool in {:?}",
completed_tx.tx_id,
completed_tx.transaction.body.kernels()[0]
.excess_sig
.get_signature()
.to_hex(),
ts
);
return Ok(true);
},
},
_ => (),
}
},
}
Ok(true)
}
async fn handle_base_node_response(
&mut self,
tx_id: TxId,
response: BaseNodeProto::BaseNodeServiceResponse,
) -> Result<bool, TransactionServiceProtocolError>
{
let response: Vec<tari_core::transactions::proto::types::TransactionOutput> = match response.response {
Some(BaseNodeResponseProto::TransactionOutputs(outputs)) => outputs.outputs,
_ => {
return Ok(false);
},
};
let completed_tx = match self.resources.db.get_completed_transaction(tx_id).await {
Ok(tx) => tx,
Err(e) => {
error!(
target: LOG_TARGET,
"Cannot find Completed Transaction (TxId: {}) referred to by this Chain Monitoring Protocol: {:?}",
self.tx_id,
e
);
return Err(TransactionServiceProtocolError::new(
self.id,
TransactionServiceError::TransactionDoesNotExistError,
));
},
};
if completed_tx.status == TransactionStatus::Broadcast {
let mut check = true;
for output in response.iter() {
let transaction_output = TransactionOutput::try_from(output.clone()).map_err(|_| {
TransactionServiceProtocolError::new(
self.id,
TransactionServiceError::ConversionError("Could not convert Transaction Output".to_string()),
)
})?;
check = check &&
completed_tx
.transaction
.body
.outputs()
.iter()
.any(|item| item == &transaction_output);
}
// If all outputs are present then mark this transaction as mined.
if check && !response.is_empty() {
self.resources
.output_manager_service
.confirm_transaction(
completed_tx.tx_id,
completed_tx.transaction.body.inputs().clone(),
completed_tx.transaction.body.outputs().clone(),
)
.await
.map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?;
self.resources
.db
.mine_completed_transaction(completed_tx.tx_id)
.await
.map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?;
let _ = self
.resources
.event_publisher
.send(Arc::new(TransactionEvent::TransactionMined(completed_tx.tx_id)))
.map_err(|e| {
trace!(
target: LOG_TARGET,
"Error sending event, usually because there are no subscribers: {:?}",
e
);
e
});
info!(
target: LOG_TARGET,
"Transaction (TxId: {:?}) detected as mined on the Base Layer", completed_tx.tx_id
);
return Ok(true);
}
}
Ok(false)
}
}
|
use crate::advent;
pub const DAY05A: advent::Sol<Vec<Seat>, i32> = advent::Sol {
day: 5,
part: advent::Part::Part1,
parse: parse,
solve: solve1,
show: i32::to_string,
};
pub const DAY05B: advent::Sol<Vec<Seat>, i32> = advent::Sol {
day: 5,
part: advent::Part::Part2,
parse: parse,
solve: solve2,
show: i32::to_string,
};
type Seat = String;
fn solve2(seats: Vec<Seat>) -> i32 {
let mut ids: Vec<i32> = seats.into_iter().map(seat_id).collect();
ids.sort();
for i in 0..ids.len() {
if ids[i+1] != ids[i] + 1 {
return ids[i] + 1;
}
}
return -1;
}
fn solve1(seats: Vec<Seat>) -> i32 {
match seats.into_iter().map(seat_id).max() {
Some(max) => max,
None => -1
}
}
fn seat_id(seat: Seat) -> i32 {
let bin: String = seat.chars().map(|c| match c {
'B'|'R' => '1',
'F'|'L' => '0',
_ => c
}).collect();
isize::from_str_radix(bin.as_str(), 2).unwrap() as i32
}
fn parse(input: String) -> Vec<Seat> {
input.trim_end().lines().map(str::to_string).collect()
} |
use crate::sources::LSPSupport;
use log::trace;
use ropey::Rope;
use tower_lsp::lsp_types::*;
/// cleanup the text of a definition so it can be included in completions
pub fn clean_type_str(type_str: &str, ident: &str) -> String {
let endings: &[_] = &[';', ','];
// remove anything after an equals sign
let eq_offset = type_str.find('=').unwrap_or_else(|| type_str.len());
let mut result = type_str.to_string();
result.replace_range(eq_offset.., "");
result
.trim_start()
.trim_end()
.trim_end_matches(endings)
.trim_end_matches(ident)
.trim_end()
.split_whitespace()
.collect::<Vec<&str>>()
.join(" ")
.replace("[ ", "[")
.replace(" ]", "]")
.replace(" : ", ":")
}
pub fn copy_defs(defs: &[Box<dyn Definition>]) -> Vec<Box<dyn Definition>> {
let mut decs: Vec<Box<dyn Definition>> = Vec::new();
for def in defs {
decs.push(Box::new(GenericDec {
ident: def.ident(),
byte_idx: def.byte_idx(),
url: def.url(),
type_str: def.type_str(),
completion_kind: def.completion_kind(),
symbol_kind: def.symbol_kind(),
def_type: def.def_type(),
}))
}
decs
}
pub fn copy_scopes(scopes: &[Box<dyn Scope>]) -> Vec<Box<dyn Scope>> {
let mut scope_decs: Vec<Box<dyn Scope>> = Vec::new();
for scope in scopes {
let mut scope_copy = GenericScope {
ident: scope.ident(),
byte_idx: scope.byte_idx(),
start: scope.start(),
end: scope.end(),
url: scope.url(),
type_str: scope.type_str(),
completion_kind: scope.completion_kind(),
symbol_kind: scope.symbol_kind(),
def_type: scope.def_type(),
defs: Vec::new(),
scopes: Vec::new(),
};
scope_copy.defs.extend(copy_defs(scope.defs()));
scope_copy.scopes.extend(copy_scopes(scope.scopes()));
scope_decs.push(Box::new(scope_copy))
}
scope_decs
}
/// A definition of any SystemVerilog variable or construct
pub trait Definition: std::fmt::Debug + Sync + Send {
// identifier
fn ident(&self) -> String;
// byte index in file of definition
fn byte_idx(&self) -> usize;
// url pointing to the file the definition is in
fn url(&self) -> Url;
// cleaned up text of the definition
fn type_str(&self) -> String;
// the kind of this definition, for use in completions
fn completion_kind(&self) -> CompletionItemKind;
// the kind of this definition, for use in showing document symbols
// for some reason this kind is different than CompletionItemKind
fn symbol_kind(&self) -> SymbolKind;
// the kind of this definition, simplified for internal use
fn def_type(&self) -> DefinitionType;
// whether the definition identifier starts with the given token
fn starts_with(&self, token: &str) -> bool;
// constructs the completion for this definition
fn completion(&self) -> CompletionItem;
fn dot_completion(&self, scope_tree: &GenericScope) -> Vec<CompletionItem>;
}
pub trait Scope: std::fmt::Debug + Definition + Sync + Send {
// the start byte of this scope
fn start(&self) -> usize;
// the end byte of this scope
fn end(&self) -> usize;
// all the within this scope
fn defs(&self) -> &Vec<Box<dyn Definition>>;
// all the scopes within this scope, ex. task inside a module
fn scopes(&self) -> &Vec<Box<dyn Scope>>;
// the definition of this scope
fn definition(&self) -> GenericDec {
GenericDec {
ident: self.ident(),
byte_idx: self.byte_idx(),
url: self.url(),
type_str: self.type_str(),
completion_kind: self.completion_kind(),
symbol_kind: self.symbol_kind(),
def_type: DefinitionType::GenericScope,
}
}
/// return a completion from the scope tree, this function should be called on the global scope
fn get_completion(&self, token: &str, byte_idx: usize, url: &Url) -> Vec<CompletionItem> {
let mut completions: Vec<CompletionItem> = Vec::new();
// first we need to go down the scope tree, to the scope the user is invoking a completion
// in
for scope in self.scopes() {
if &scope.url() == url && scope.start() <= byte_idx && byte_idx <= scope.end() {
completions = scope.get_completion(token, byte_idx, url);
break;
}
}
// now that we are in the users scope, we can attempt to find a relevant completion
// we proceed back upwards through the scope tree, adding any definitions that match
// the users token
let completion_idents: Vec<String> = completions.iter().map(|x| x.label.clone()).collect();
for def in self.defs() {
if !completion_idents.contains(&def.ident()) && def.starts_with(token) {
completions.push(def.completion());
}
}
for scope in self.scopes() {
if scope.starts_with(token) {
completions.push(scope.completion());
}
}
completions
}
/// return a dot completion from the scope tree, this function should be called on the global
/// scope
fn get_dot_completion(
&self,
token: &str,
byte_idx: usize,
url: &Url,
scope_tree: &GenericScope,
) -> Vec<CompletionItem> {
trace!("dot entering: {}, token: {}", self.ident(), token);
trace!("{:?}", self.scopes());
// first we need to go down the scope tree, to the scope the user is invoking a completion
// in
for scope in self.scopes() {
trace!(
"{}, {}, {}, {}",
scope.ident(),
byte_idx,
scope.start(),
scope.end()
);
if &scope.url() == url && scope.start() <= byte_idx && byte_idx <= scope.end() {
eprintln!("checking dot completion: {}", scope.ident());
let result = scope.get_dot_completion(token, byte_idx, url, scope_tree);
if !result.is_empty() {
return result;
}
}
}
// now that we are in the users scope, we can attempt to find the relevant definition
// we proceed back upwards through the scope tree, and if a definition matches our token,
// we invoke dot completion on that definition and pass it the syntax tree
for def in self.defs() {
trace!("def: {:?}", def);
if def.starts_with(token) {
trace!("complete def: {:?}", def);
return def.dot_completion(scope_tree);
}
}
for scope in self.scopes() {
if scope.starts_with(token) {
trace!("found dot-completion scope: {}", scope.ident());
return scope.dot_completion(scope_tree);
}
}
Vec::new()
}
/// return a definition from the scope tree, this function should be called on the global
/// scope
fn get_definition(&self, token: &str, byte_idx: usize, url: &Url) -> Option<GenericDec> {
let mut definition: Option<GenericDec> = None;
for scope in self.scopes() {
if &scope.url() == url && scope.start() <= byte_idx && byte_idx <= scope.end() {
definition = scope.get_definition(token, byte_idx, url);
break;
}
}
if definition.is_none() {
for def in self.defs() {
if def.ident() == token {
return Some(GenericDec {
ident: def.ident(),
byte_idx: def.byte_idx(),
url: def.url(),
type_str: def.type_str(),
completion_kind: def.completion_kind(),
symbol_kind: def.symbol_kind(),
def_type: DefinitionType::Net,
});
}
}
for scope in self.scopes() {
if scope.ident() == token {
return Some(scope.definition());
}
}
}
definition
}
/// returns all symbols in a document
fn document_symbols(&self, uri: &Url, doc: &Rope) -> Vec<DocumentSymbol> {
let mut symbols: Vec<DocumentSymbol> = Vec::new();
for scope in self.scopes() {
if &scope.url() == uri {
#[allow(deprecated)]
symbols.push(DocumentSymbol {
name: scope.ident(),
detail: Some(scope.type_str()),
kind: scope.symbol_kind(),
deprecated: None,
range: Range::new(doc.byte_to_pos(scope.start()), doc.byte_to_pos(scope.end())),
selection_range: Range::new(
doc.byte_to_pos(scope.byte_idx()),
doc.byte_to_pos(scope.byte_idx() + scope.ident().len()),
),
children: Some(scope.document_symbols(uri, doc)),
tags: None,
})
}
}
for def in self.defs() {
#[allow(deprecated)]
symbols.push(DocumentSymbol {
name: def.ident(),
detail: Some(def.type_str()),
kind: def.symbol_kind(),
deprecated: None,
range: Range::new(
doc.byte_to_pos(def.byte_idx()),
doc.byte_to_pos(def.byte_idx() + def.ident().len()),
),
selection_range: Range::new(
doc.byte_to_pos(def.byte_idx()),
doc.byte_to_pos(def.byte_idx() + def.ident().len()),
),
children: None,
tags: None,
})
}
symbols
}
/// highlight all references of a symbol
fn document_highlights(
&self,
uri: &Url,
doc: &Rope,
// all references in the doc's syntax tree
references: Vec<(String, usize)>,
// byte_idx of symbol definition
byte_idx: usize,
) -> Vec<DocumentHighlight> {
// to find references we need to grab references from locations downward from the
// definition
for scope in self.scopes() {
if &scope.url() == uri && scope.start() <= byte_idx && byte_idx <= scope.end() {
return scope.document_highlights(uri, doc, references, byte_idx);
}
}
// we should now be in the scope of the definition, so we can grab all references
// in this scope. This also grabs references below this scope.
references
.iter()
.filter(|x| self.start() <= x.1 && x.1 <= self.end())
.map(|x| DocumentHighlight {
range: Range::new(doc.byte_to_pos(x.1), doc.byte_to_pos(x.1 + x.0.len())),
kind: None,
})
.collect()
}
}
#[derive(Debug, Clone, Copy)]
pub enum DefinitionType {
Port,
Net,
Data,
Modport,
Subroutine,
ModuleInstantiation,
GenericScope,
Class,
}
#[derive(Debug)]
pub struct PortDec {
pub ident: String,
pub byte_idx: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub interface: Option<String>,
pub modport: Option<String>,
}
impl PortDec {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
type_str: String::new(),
completion_kind: CompletionItemKind::Property,
symbol_kind: SymbolKind::Property,
def_type: DefinitionType::Port,
interface: None,
modport: None,
url: url.clone(),
}
}
}
impl Definition for PortDec {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, scope_tree: &GenericScope) -> Vec<CompletionItem> {
for scope in &scope_tree.scopes {
if let Some(interface) = &self.interface {
if &scope.ident() == interface {
return match &self.modport {
Some(modport) => {
for def in scope.defs() {
if def.starts_with(&modport) {
return def.dot_completion(scope_tree);
}
}
Vec::new()
}
None => scope
.defs()
.iter()
.filter(|x| !x.starts_with(&scope.ident()))
.map(|x| x.completion())
.collect(),
};
}
}
}
Vec::new()
}
}
#[derive(Debug)]
pub struct GenericDec {
pub ident: String,
pub byte_idx: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
}
impl GenericDec {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Variable,
symbol_kind: SymbolKind::Unknown,
def_type: DefinitionType::Net,
}
}
}
impl Definition for GenericDec {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, _: &GenericScope) -> Vec<CompletionItem> {
Vec::new()
}
}
#[derive(Debug)]
pub struct PackageImport {
pub ident: String,
pub byte_idx: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub asterisk: bool,
pub import_ident: Option<String>,
}
impl PackageImport {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Text,
symbol_kind: SymbolKind::Namespace,
def_type: DefinitionType::Data,
asterisk: false,
import_ident: None,
}
}
}
impl Definition for PackageImport {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident.clone())),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, _: &GenericScope) -> Vec<CompletionItem> {
Vec::new()
}
}
#[derive(Debug)]
pub struct SubDec {
pub ident: String,
pub byte_idx: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub start: usize,
pub end: usize,
pub defs: Vec<Box<dyn Definition>>,
pub scopes: Vec<Box<dyn Scope>>,
}
impl SubDec {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Function,
symbol_kind: SymbolKind::Function,
def_type: DefinitionType::Subroutine,
start: 0,
end: 0,
defs: Vec::new(),
scopes: Vec::new(),
}
}
}
impl Definition for SubDec {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, _: &GenericScope) -> Vec<CompletionItem> {
Vec::new()
}
}
impl Scope for SubDec {
fn start(&self) -> usize {
self.start
}
fn end(&self) -> usize {
self.end
}
fn defs(&self) -> &Vec<Box<dyn Definition>> {
&self.defs
}
fn scopes(&self) -> &Vec<Box<dyn Scope>> {
&self.scopes
}
}
#[derive(Debug)]
pub struct ModportDec {
pub ident: String,
pub byte_idx: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub ports: Vec<Box<dyn Definition>>,
}
impl ModportDec {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Interface,
symbol_kind: SymbolKind::Interface,
def_type: DefinitionType::Modport,
ports: Vec::new(),
}
}
}
impl Definition for ModportDec {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, _: &GenericScope) -> Vec<CompletionItem> {
self.ports.iter().map(|x| x.completion()).collect()
}
}
#[derive(Debug)]
pub struct ModInst {
pub ident: String,
pub byte_idx: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub mod_ident: String,
}
impl ModInst {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Module,
symbol_kind: SymbolKind::Module,
def_type: DefinitionType::ModuleInstantiation,
mod_ident: String::new(),
}
}
}
impl Definition for ModInst {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, scope_tree: &GenericScope) -> Vec<CompletionItem> {
for scope in &scope_tree.scopes {
if scope.ident() == self.mod_ident {
return scope
.defs()
.iter()
.filter(|x| !x.starts_with(&scope.ident()))
.map(|x| x.completion())
.collect();
}
}
Vec::new()
}
}
#[derive(Debug)]
pub struct GenericScope {
pub ident: String,
pub byte_idx: usize,
pub start: usize,
pub end: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub defs: Vec<Box<dyn Definition>>,
pub scopes: Vec<Box<dyn Scope>>,
}
impl GenericScope {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
start: 0,
end: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Module,
symbol_kind: SymbolKind::Module,
def_type: DefinitionType::GenericScope,
defs: Vec::new(),
scopes: Vec::new(),
}
}
#[cfg(test)]
pub fn contains_scope(&self, scope_ident: &str) -> bool {
for scope in &self.scopes {
if scope.starts_with(scope_ident) {
return true;
}
}
false
}
}
impl Definition for GenericScope {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, scope_tree: &GenericScope) -> Vec<CompletionItem> {
for scope in scope_tree.scopes() {
if scope.ident() == self.ident {
return scope
.defs()
.iter()
.filter(|x| !x.starts_with(&scope.ident()))
.map(|x| x.completion())
.collect();
}
}
Vec::new()
}
}
impl Scope for GenericScope {
fn start(&self) -> usize {
self.start
}
fn end(&self) -> usize {
self.end
}
fn defs(&self) -> &Vec<Box<dyn Definition>> {
&self.defs
}
fn scopes(&self) -> &Vec<Box<dyn Scope>> {
&self.scopes
}
}
#[derive(Debug)]
pub struct ClassDec {
pub ident: String,
pub byte_idx: usize,
pub start: usize,
pub end: usize,
pub url: Url,
pub type_str: String,
pub completion_kind: CompletionItemKind,
pub symbol_kind: SymbolKind,
pub def_type: DefinitionType,
pub defs: Vec<Box<dyn Definition>>,
pub scopes: Vec<Box<dyn Scope>>,
// class, package
pub extends: (Vec<String>, Option<String>),
// class, package
pub implements: Vec<(String, Option<String>)>,
pub interface: bool,
}
impl ClassDec {
pub fn new(url: &Url) -> Self {
Self {
ident: String::new(),
byte_idx: 0,
start: 0,
end: 0,
url: url.clone(),
type_str: String::new(),
completion_kind: CompletionItemKind::Class,
symbol_kind: SymbolKind::Class,
def_type: DefinitionType::Class,
defs: Vec::new(),
scopes: Vec::new(),
extends: (Vec::new(), None),
implements: Vec::new(),
interface: false,
}
}
}
impl Definition for ClassDec {
fn ident(&self) -> String {
self.ident.clone()
}
fn byte_idx(&self) -> usize {
self.byte_idx
}
fn url(&self) -> Url {
self.url.clone()
}
fn type_str(&self) -> String {
self.type_str.clone()
}
fn completion_kind(&self) -> CompletionItemKind {
self.completion_kind
}
fn symbol_kind(&self) -> SymbolKind {
self.symbol_kind
}
fn def_type(&self) -> DefinitionType {
self.def_type
}
fn starts_with(&self, token: &str) -> bool {
self.ident.starts_with(token)
}
fn completion(&self) -> CompletionItem {
CompletionItem {
label: self.ident.clone(),
detail: Some(clean_type_str(&self.type_str, &self.ident)),
kind: Some(self.completion_kind),
..CompletionItem::default()
}
}
fn dot_completion(&self, scope_tree: &GenericScope) -> Vec<CompletionItem> {
for scope in scope_tree.scopes() {
if scope.ident() == self.ident {
return scope
.defs()
.iter()
.filter(|x| !x.starts_with(&scope.ident()))
.map(|x| x.completion())
.collect();
}
}
Vec::new()
}
}
impl Scope for ClassDec {
fn start(&self) -> usize {
self.start
}
fn end(&self) -> usize {
self.end
}
fn defs(&self) -> &Vec<Box<dyn Definition>> {
&self.defs
}
fn scopes(&self) -> &Vec<Box<dyn Scope>> {
&self.scopes
}
}
|
use std::fmt::Debug;
use std::marker;
use std::ops::{Add, Mul, Sub};
use cgmath::num_traits::{Float, NumCast};
use cgmath::{BaseFloat, EuclideanSpace, InnerSpace, One, Rotation, Zero};
use collision::Contact;
use super::{Inertia, Mass, Material, PartialCrossProduct, Velocity};
use {NextFrame, Pose};
const POSITIONAL_CORRECTION_PERCENT: f32 = 0.2;
const POSITIONAL_CORRECTION_K_SLOP: f32 = 0.01;
/// Changes computed from contact resolution.
///
/// Optionally contains the new pose and/or velocity of a body after contact resolution.
///
/// ### Type parameters:
///
/// - `B`: Transform type (`BodyPose3` or similar)
/// - `P`: Point type, usually `Point2` or `Point3`
/// - `R`: Rotational quantity, usually `Basis2` or `Quaternion`
/// - `A`: Angular velocity, usually `Scalar` or `Vector3`
#[derive(Debug, PartialEq)]
pub struct SingleChangeSet<B, P, R, A>
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
R: Rotation<P>,
A: Clone,
B: Pose<P, R>,
{
pose: Option<B>,
velocity: Option<NextFrame<Velocity<P::Diff, A>>>,
m: marker::PhantomData<(P, R)>,
}
impl<B, P, R, A> Default for SingleChangeSet<B, P, R, A>
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
R: Rotation<P>,
A: Clone,
B: Pose<P, R>,
{
fn default() -> Self {
Self {
pose: None,
velocity: None,
m: marker::PhantomData,
}
}
}
impl<B, P, R, A> SingleChangeSet<B, P, R, A>
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
R: Rotation<P>,
A: Clone,
B: Pose<P, R>,
{
#[allow(dead_code)]
fn new(pose: Option<B>, velocity: Option<NextFrame<Velocity<P::Diff, A>>>) -> Self {
SingleChangeSet {
pose,
velocity,
m: marker::PhantomData,
}
}
fn add_pose(&mut self, pose: Option<B>) {
self.pose = pose;
}
fn add_velocity(&mut self, velocity: Option<NextFrame<Velocity<P::Diff, A>>>) {
self.velocity = velocity;
}
/// Apply any changes to the next frame pose and/or velocity
pub fn apply(
self,
pose: Option<&mut NextFrame<B>>,
velocity: Option<&mut NextFrame<Velocity<P::Diff, A>>>,
) {
if let (Some(pose), Some(update_pose)) = (pose, self.pose) {
pose.value = update_pose;
}
if let (Some(velocity), Some(update_velocity)) = (velocity, self.velocity) {
*velocity = update_velocity;
}
}
}
/// Data used for contact resolution
///
/// ### Type parameters:
///
/// - `B`: Transform type (`BodyPose3` or similar)
/// - `P`: Point type, usually `Point2` or `Point3`
/// - `R`: Rotational quantity, usually `Basis2` or `Quaternion`
/// - `A`: Angular velocity, usually `Scalar` or `Vector3`
/// - `I`: Inertia, usually `Scalar` or `Matrix3`
pub struct ResolveData<'a, B, P, R, I, A>
where
P: EuclideanSpace + 'a,
P::Scalar: BaseFloat,
R: Rotation<P> + 'a,
I: 'a,
A: Clone + 'a,
B: Pose<P, R> + 'a,
{
/// Velocity for next frame
pub velocity: Option<&'a NextFrame<Velocity<P::Diff, A>>>,
/// Position for next frame
pub pose: &'a B,
/// Mass
pub mass: &'a Mass<P::Scalar, I>,
/// Material
pub material: &'a Material,
m: marker::PhantomData<(P, R)>,
}
impl<'a, B, P, R, I, A> ResolveData<'a, B, P, R, I, A>
where
P: EuclideanSpace + 'a,
P::Scalar: BaseFloat,
R: Rotation<P> + 'a,
I: 'a,
A: Clone + 'a,
B: Pose<P, R> + 'a,
{
/// Create resolve data
pub fn new(
velocity: Option<&'a NextFrame<Velocity<P::Diff, A>>>,
pose: &'a B,
mass: &'a Mass<P::Scalar, I>,
material: &'a Material,
) -> Self {
ResolveData {
velocity,
pose,
mass,
material,
m: marker::PhantomData,
}
}
}
/// Perform contact resolution.
///
/// Will compute any new poses and/or velocities, by doing impulse resolution of the given contact.
///
/// ### Parameters:
///
/// - `contact`: The contact; contact normal must point from shape A -> B
/// - `a`: Resolution data for shape A
/// - `b`: Resolution data for shape B
///
/// ### Returns
///
/// Tuple of change sets, first change set is for shape A, second change set for shape B.
///
/// ### Type parameters:
///
/// - `B`: Transform type (`BodyPose3` or similar)
/// - `P`: Point type, usually `Point2` or `Point3`
/// - `R`: Rotational quantity, usually `Basis2` or `Quaternion`
/// - `A`: Angular velocity, usually `Scalar` or `Vector3`
/// - `I`: Inertia, usually `Scalar` or `Matrix3`
/// - `O`: Internal type used for unifying cross products for 2D/3D, usually `Scalar` or `Vector3`
pub fn resolve_contact<'a, B, P, R, I, A, O>(
contact: &Contact<P>,
a: &ResolveData<'a, B, P, R, I, A>,
b: &ResolveData<'a, B, P, R, I, A>,
) -> (SingleChangeSet<B, P, R, A>, SingleChangeSet<B, P, R, A>)
where
P: EuclideanSpace + 'a,
P::Scalar: BaseFloat,
R: Rotation<P> + 'a,
P::Diff: Debug + Zero + Clone + InnerSpace + PartialCrossProduct<P::Diff, Output = O>,
O: PartialCrossProduct<P::Diff, Output = P::Diff>,
A: PartialCrossProduct<P::Diff, Output = P::Diff> + Clone + Zero + 'a,
&'a A: Sub<O, Output = A> + Add<O, Output = A>,
I: Inertia<Orientation = R> + Mul<O, Output = O>,
B: Pose<P, R> + 'a,
{
let a_velocity = a.velocity.map(|v| v.value.clone()).unwrap_or_default();
let b_velocity = b.velocity.map(|v| v.value.clone()).unwrap_or_default();
let a_inverse_mass = a.mass.inverse_mass();
let b_inverse_mass = b.mass.inverse_mass();
let total_inverse_mass = a_inverse_mass + b_inverse_mass;
// Do positional correction, so bodies aren't penetrating as much any longer.
let (a_position_new, b_position_new) =
positional_correction(contact, a.pose, b.pose, a_inverse_mass, b_inverse_mass);
let mut a_set = SingleChangeSet::default();
a_set.add_pose(a_position_new);
let mut b_set = SingleChangeSet::default();
b_set.add_pose(b_position_new);
// This only happens when we have 2 infinite masses colliding. We only do positional correction
// for the bodies and return early
if total_inverse_mass == P::Scalar::zero() {
return (a_set, b_set);
}
let r_a = contact.contact_point - a.pose.transform_point(P::origin());
let r_b = contact.contact_point - b.pose.transform_point(P::origin());
let p_a_dot = *a_velocity.linear() + a_velocity.angular().cross(&r_a);
let p_b_dot = *b_velocity.linear() + b_velocity.angular().cross(&r_b);
let rv = p_b_dot - p_a_dot;
let velocity_along_normal = contact.normal.dot(rv);
// Check if shapes are already separating, if so only do positional correction
if velocity_along_normal > P::Scalar::zero() {
return (a_set, b_set);
}
// Compute impulse force
let a_res: P::Scalar = a.material.restitution();
let b_res: P::Scalar = b.material.restitution();
let e = a_res.min(b_res);
let numerator = -(P::Scalar::one() + e) * velocity_along_normal;
let a_tensor = a.mass.world_inverse_inertia(&a.pose.rotation());
let b_tensor = b.mass.world_inverse_inertia(&b.pose.rotation());
let term3 = contact
.normal
.dot((a_tensor * (r_a.cross(&contact.normal))).cross(&r_a));
let term4 = contact
.normal
.dot((b_tensor * (r_b.cross(&contact.normal))).cross(&r_b));
let j = numerator / (a_inverse_mass + b_inverse_mass + term3 + term4);
let impulse = contact.normal * j;
// Compute new velocities based on mass and the computed impulse
let a_velocity_new = a.velocity.map(|v| NextFrame {
value: Velocity::new(
*v.value.linear() - impulse * a_inverse_mass,
v.value.angular() - a_tensor * r_a.cross(&impulse),
),
});
let b_velocity_new = b.velocity.map(|v| NextFrame {
value: Velocity::new(
*v.value.linear() + impulse * b_inverse_mass,
v.value.angular() + b_tensor * r_b.cross(&impulse),
),
});
a_set.add_velocity(a_velocity_new);
b_set.add_velocity(b_velocity_new);
(a_set, b_set)
}
/// Do positional correction for colliding bodies.
///
/// Will only do correction for a percentage of the penetration depth, to avoid stability issues.
///
/// ### Parameters:
///
/// - `contact`: Contact information, normal must point from A -> B
/// - `a_position`: World coordinates of center of mass for body A
/// - `b_position`: World coordinates of center of mass for body B
/// - `a_inverse_mass`: Inverse mass of body A
/// - `b_inverse_mass`: Inverse mass of body B
///
/// ### Returns:
///
/// Tuple with new positions for the given bodies
///
/// ### Type parameters:
///
/// - `S`: Scalar type
/// - `B`: Transform type (`BodyPose3` or similar)
/// - `P`: Positional quantity, usually `Point2` or `Point3`
/// - `R`: Rotational quantity, usually `Basis2` or `Quaternion`
fn positional_correction<S, B, P, R>(
contact: &Contact<P>,
a_position: &B,
b_position: &B,
a_inverse_mass: S,
b_inverse_mass: S,
) -> (Option<B>, Option<B>)
where
S: BaseFloat,
P: EuclideanSpace<Scalar = S>,
R: Rotation<P>,
P::Diff: Debug + Zero + Clone + InnerSpace,
B: Pose<P, R>,
{
let total_inverse_mass = a_inverse_mass + b_inverse_mass;
let k_slop: S = NumCast::from(POSITIONAL_CORRECTION_K_SLOP).unwrap();
let percent: S = NumCast::from(POSITIONAL_CORRECTION_PERCENT).unwrap();
let correction_penetration_depth = contact.penetration_depth - k_slop;
let correction_magnitude =
correction_penetration_depth.max(S::zero()) / total_inverse_mass * percent;
let correction = contact.normal * correction_magnitude;
let a_position_new = new_pose(a_position, correction * -a_inverse_mass);
let b_position_new = new_pose(b_position, correction * b_inverse_mass);
(Some(a_position_new), Some(b_position_new))
}
fn new_pose<B, P, R>(next_frame: &B, correction: P::Diff) -> B
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
R: Rotation<P>,
P::Diff: Clone,
B: Pose<P, R>,
{
B::new(next_frame.position() + correction, next_frame.rotation())
}
#[cfg(test)]
mod tests {
use cgmath::{Basis2, One, Point2, Vector2};
use collision::{CollisionStrategy, Contact};
use super::*;
use collide::ContactEvent;
use BodyPose;
#[test]
fn test_resolve_2d_f32() {
let mass = Mass::<f32, f32>::new_with_inertia(0.5, 0.);
let material = Material::default();
let left_velocity = NextFrame {
value: Velocity::new(Vector2::<f32>::new(1., 0.), 0.),
};
let left_pose = BodyPose::new(Point2::origin(), Basis2::one());
let right_velocity = NextFrame {
value: Velocity::new(Vector2::new(-2., 0.), 0.),
};
let right_pose = BodyPose::new(Point2::new(1., 0.), Basis2::one());
let contact = ContactEvent::new(
(1, 2),
Contact::new_impl(CollisionStrategy::FullResolution, Vector2::new(1., 0.), 0.5),
);
let set = resolve_contact(
&contact.contact,
&ResolveData::new(Some(&left_velocity), &left_pose, &mass, &material),
&ResolveData::new(Some(&right_velocity), &right_pose, &mass, &material),
);
assert_eq!(
(
SingleChangeSet::new(
Some(BodyPose::new(
Point2::new(-0.04900000075250864, 0.),
Basis2::one()
)),
Some(NextFrame {
value: Velocity::new(Vector2::new(-2., 0.), 0.),
}),
),
SingleChangeSet::new(
Some(BodyPose::new(
Point2::new(1.0490000007525087, 0.),
Basis2::one()
)),
Some(NextFrame {
value: Velocity::new(Vector2::new(1., 0.), 0.),
}),
)
),
set
);
}
#[test]
fn test_resolve_2d_f64() {
let mass = Mass::<f64, f64>::new_with_inertia(0.5, 0.);
let material = Material::default();
let left_velocity = NextFrame {
value: Velocity::new(Vector2::<f64>::new(1., 0.), 0.),
};
let left_pose = BodyPose::new(Point2::origin(), Basis2::one());
let right_velocity = NextFrame {
value: Velocity::new(Vector2::new(-2., 0.), 0.),
};
let right_pose = BodyPose::new(Point2::new(1., 0.), Basis2::one());
let contact = ContactEvent::new(
(1, 2),
Contact::new_impl(CollisionStrategy::FullResolution, Vector2::new(1., 0.), 0.5),
);
let set = resolve_contact(
&contact.contact,
&ResolveData::new(Some(&left_velocity), &left_pose, &mass, &material),
&ResolveData::new(Some(&right_velocity), &right_pose, &mass, &material),
);
assert_eq!(
(
SingleChangeSet::new(
Some(BodyPose::new(
Point2::new(-0.04900000075250864, 0.),
Basis2::one()
)),
Some(NextFrame {
value: Velocity::new(Vector2::new(-2., 0.), 0.),
}),
),
SingleChangeSet::new(
Some(BodyPose::new(
Point2::new(1.0490000007525087, 0.),
Basis2::one()
)),
Some(NextFrame {
value: Velocity::new(Vector2::new(1., 0.), 0.),
}),
)
),
set
);
}
}
|
/// Generates `sequence_id`s for requests.
pub struct IdSequence {
next: u32,
}
impl IdSequence {
pub fn next(&mut self) -> u32 {
let next = self.next;
self.next = self.next.wrapping_add(1);
next
}
}
impl Default for IdSequence {
fn default() -> Self {
Self { next: 1 }
}
}
|
pub mod io;
pub mod idt;
|
use std::io::ErrorKind;
use std::path::PathBuf;
use tracing::error;
use crate::io;
pub fn init(path: &str) -> Result<(), std::io::Error> {
let path = PathBuf::from(path);
match io::create_folder(path) {
Ok(_) => Ok(()),
Err(e) => match e.kind() {
ErrorKind::AlreadyExists => Ok(()),
_ => {
error!("Error creating folder [{:?}]", e.kind());
Err(e)
}
},
}
}
|
use crate::api::v1::ceo::auth::model::SlimUser;
use crate::errors::ServiceError;
use chrono::{Duration, Local};
use jsonwebtoken::{decode, encode, Header, Validation};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
// issuer
iss: String,
// account_id
id: String,
//role
role: String,
// expiry
exp: i64,
}
// struct to get converted to token and back
impl Claims {
fn with_user(id: &str, role: &str) -> Self {
Claims {
iss: "0.0.0.0:3000".into(),
id: id.to_owned(),
role: role.to_owned(),
exp: (Local::now() + Duration::hours(24)).timestamp(),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AuthUser {
pub id: Uuid,
pub role: String,
}
impl From<Claims> for AuthUser {
fn from(claims: Claims) -> Self {
AuthUser {
id: Uuid::parse_str(claims.id.as_str()).unwrap(),
role: claims.role,
}
}
}
pub fn create_token(data: &SlimUser) -> Result<String, ServiceError> {
let claims = Claims::with_user(data.id.simple().to_string().as_str(), data.role.as_str());
encode(&Header::default(), &claims, get_secret().as_ref())
.map_err(|_err| ServiceError::InternalServerError)
}
pub fn decode_token(token: &str) -> Result<AuthUser, ServiceError> {
decode::<Claims>(token, get_secret().as_ref(), &Validation::default())
.map(|data| Ok(data.claims.into()))
.map_err(|_err| ServiceError::Unauthorized)?
}
fn get_secret() -> String {
std::env::var("JWT_SECRET").unwrap_or_else(|_| "my secret".into())
}
|
use std;
use ws;
use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslMethod, SslStream};
use openssl::pkey::PKey;
use openssl::x509::{X509, X509Ref};
use ws::util::TcpStream;
use Pair;
use get_ws_id;
use get_ws_url;
use RoomUsersRegistry;
use UserStatusRegistry;
use RoomNB;
use std::thread;
use chrono::TimeZone;
use std::collections::HashMap;
use ws::{listen, connect, Handler, Sender, Result, Message, CloseCode};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
use std::cell::Cell;
use std::cell::RefCell;
use std::vec::Vec;
use Client::Client;
pub struct Server {
pub out: Sender,
pub count: Rc<Cell<u32>>,
pub room_count: Rc<Cell<u32>>,
pub room_counter: Rc<RefCell<HashMap<String, u8>>>,
pub room_nbs: Rc<RefCell<HashMap<String, u32>>>,
pub user_isconnected: UserStatusRegistry,
pub room_users: RoomUsersRegistry,
pub id: u32,
pub child: Option<std::thread::JoinHandle<()>>,
pub ssl: Rc<SslAcceptor>,
}
impl Handler for Server {
fn upgrade_ssl_server(&mut self, sock: TcpStream) -> ws::Result<SslStream<TcpStream>> {
self.ssl.accept(sock).map_err(From::from)
}
fn on_open(&mut self, hs: ws::Handshake) -> Result<()> {
let path = hs.request.resource();
let pathsplit: Vec<&str> = path.split("/").collect();
if pathsplit.len() < 3 {
println!("Not enough arguments");
self.out.close(CloseCode::Normal)
} else {
let broker: &str = pathsplit[1];
let pair: &str = pathsplit[2];
let interval: &str = pathsplit[3];
println!("+ User {:?}/{:?} connection : broker={} symbol={} interval={}", self.id, self.count, broker, pair, interval);
println!(" Update total count");
println!(" USER ID {}", self.id);
let url = get_ws_url(broker, pair, interval);
//update shared structures
let room_id = get_ws_id(broker, pair, interval).to_owned();
self.update_room_count(room_id);
let room_id = get_ws_id(broker, pair, interval).to_owned();
self.update_user_isconnected();
let room_id = get_ws_id(broker, pair, interval).to_owned();
println!("room {}", room_id);
let room_nb: RoomNB = self.set_room_nb(broker.to_owned(), pair.to_owned(), interval.to_owned(), room_id);
let is_room_creation = self.update_room_users(room_nb);
println!(" roomcreation? {}", is_room_creation);
let id = Some(get_ws_id(broker, pair, interval).to_owned());
let w = self.user_isconnected.clone();
let ww = self.room_users.clone();
let b = broker.clone().to_owned();
let p = pair.clone().to_owned();
if !is_room_creation {} else {
println!(" Try connect to exchange {}", url);
self.child = Some(thread::spawn(move || {
println!(" New thread {} ", url);
connect(url, |out2| Client {
out: out2,
broker: b.clone(),
pair: p.clone(),
room_id: id.clone(),
oldp: "".to_string(),
oldv: "".to_string(),
room_users: ww.clone(),
room_nb: room_nb.clone(),
user_isconnected: w.clone(),
}).unwrap();
println!(" New thread done ");
}));
}
self.count.set(self.count.get() + 1);
self.out.send("{\"wsConnected\":\"true\"}")
}
}
fn on_message(&mut self, msg: Message) -> Result<()> {
println!("msg {}", msg);
self.out.send(format!("You are user {} on {:?}", self.id, self.count))
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
match code {
CloseCode::Normal => println!("The client is done with the connection."),
CloseCode::Away => {
println!("The client is leaving the site. Update room count");
self.update_user_setnotconnected();
self.out.close(CloseCode::Normal).unwrap();
}
CloseCode::Abnormal => println!("Closing handshake failed! Unable to obtain closing status from client."),
CloseCode::Protocol => println!("protocol"),
CloseCode::Unsupported => println!("Unsupported"),
CloseCode::Status => {
println!("Status");
self.update_user_setnotconnected();
self.out.close(CloseCode::Normal).unwrap();
}
CloseCode::Abnormal => println!("Abnormal"),
CloseCode::Invalid => println!("Invalid"),
CloseCode::Protocol => println!("protocol"),
CloseCode::Policy => println!("Policy"),
CloseCode::Size => println!("Size"),
CloseCode::Extension => println!("Extension"),
CloseCode::Protocol => println!("protocol"),
CloseCode::Restart => println!("Restart"),
CloseCode::Again => println!("Again"),
_ => println!("CLOSE The client encountered an error: {}", reason),
}
}
fn on_error(&mut self, err: ws::Error) {
println!("The server encountered an error: {:?}", err);
}
}
impl Server {
fn update_room_count(&mut self, room_id: String) {
println!(" * Update room count");
let mut a = self.room_counter.borrow_mut();
let mut co = 0;
if let Some(rc) = a.get(&room_id) {
println!("Room has a count {}", rc);
co = *rc;
} else {
println!("Room has no count");
}
a.insert(room_id, co);
}
fn get_room_nb_by_id(&mut self, room_id: String) -> Option<u32> {
println!(" * Get room nb by id");
let a = self.room_nbs.borrow_mut();
if let Some(rc) = a.get(&room_id) {
println!("Room nb for {} is {}", room_id, *rc);
Some(*rc)
} else {
println!("Room has no id");
None
}
}
fn set_room_nb_by_id(&mut self, room_id: String, room_nb: u32) {
println!(" * Set room nb ");
let mut a = self.room_nbs.borrow_mut();
a.insert(room_id, room_nb);
}
fn update_user_isconnected(&mut self) {
//update user room
println!(" * Update user isconnected SET {} TRUE", self.id);
let mut aa = self.user_isconnected.lock().unwrap();
aa.insert(self.id, true);
}
fn update_user_setnotconnected(&mut self) {
println!(" * Update user isconnected");
let mut aa = self.user_isconnected.lock().unwrap();
let mut exists = false;
if let Some(_aaa) = aa.get(&self.id) {
exists = true;
} else {}
if exists {
aa.insert(self.id, false);
}
}
fn update_room_users(&mut self, room_nb: RoomNB) -> bool {
let mut room_user_in = self.room_users.lock().unwrap();
let mut exists = false;
if let Some(ref mut q) = *room_user_in {
if let Some(_qq) = q.get_mut(&room_nb) {
exists = true
} else {
exists = false;
}
if exists {
let qq = q.get_mut(&room_nb).unwrap();
let p = Pair { id: self.id, out: self.out.clone() };
println!(" add user {} to room {}", self.id, room_nb);
qq.push(p);
} else {
let p = Pair { id: self.id, out: self.out.clone() };
println!(" create add user {} to room {}", self.id, room_nb);
q.insert(room_nb, vec!(p));
}
} else {}
!exists
}
fn set_room_nb(&mut self, broker: String, pair: String, interval: String, room_id: String) -> RoomNB {
let room_nb_opt = self.get_room_nb_by_id(room_id);
let room_nb: RoomNB;
if let Some(room_nb_) = room_nb_opt {
room_nb = room_nb_;
} else {
self.room_count.set(self.room_count.get() + 1);
room_nb = self.room_count.get();
let room_id = get_ws_id(&broker, &pair, &interval).to_owned();
self.set_room_nb_by_id(room_id, room_nb);
}
room_nb
}
}
|
use crate::{Error, mock::*};
use frame_support::{assert_ok, assert_noop};
use super::*;
//test标签表示是一个测试用例
#[test]
fn create_claim_work() {
new_test_ext().execute_with(|| {
let claim = vec![0,1];
assert_ok!(PoeModule::create_claim(Origin::signed(1), claim.clone()));
assert_eq!(
Proofs::<Test>::get(&claim),
Some((1,frame_system::Pallet::<Test>::block_number()))
);
})
}
#[test]
fn create_claim_failed_when_claim_already_exist() {
new_test_ext().execute_with(|| {
let claim = vec![0,1];
let _ = PoeModule::create_claim(Origin::signed(1), claim.clone());
assert_noop!(
PoeModule::create_claim(Origin::signed(1), claim.clone()),
Error::<Test>::ProofAlreadyExist
);
})
}
//作业2,存证长度限制测试
#[test]
fn create_claim_failed_when_claim_too_large() {
new_test_ext().execute_with(|| {
let claim = vec![0;257];
assert_noop!(
PoeModule::create_claim(Origin::signed(1), claim.clone()),
Error::<Test>::ClaimToolarge
);
})
}
#[test]
fn revoke_claim_works() {
new_test_ext().execute_with(|| {
let claim = vec![0,1];
let _ = PoeModule::create_claim(Origin::signed(1), claim.clone());
//作业1 非拥有人revoke,错误 NotClaimOwner
assert_noop!(
PoeModule::revoke_claim(Origin::signed(2), claim.clone()),
Error::<Test>::NotClaimOwner
);
assert_ok!(PoeModule::revoke_claim(Origin::signed(1), claim.clone()));
assert_eq!(Proofs::<Test>::get(&claim),None);
})
}
//作业转移存证
#[test]
fn transfer_claim_works() {
new_test_ext().execute_with(|| {
let claim = vec![0,1];
let _ = PoeModule::create_claim(Origin::signed(1), claim.clone());
//非拥有人转移,错误 NotClaimOwner
assert_noop!(
PoeModule::transfer_accountid_claim(
Origin::signed(2),
claim.clone(),
3
),
Error::<Test>::NotClaimOwner
);
//成功转移
assert_ok!(PoeModule::transfer_accountid_claim(
Origin::signed(1),
claim.clone(),
2
));
//验证
assert_eq!(Proofs::<Test>::get(&claim).unwrap().0,2);
})
}
// #[test]
// fn it_works_for_default_value() {
// new_test_ext().execute_with(|| {
// // Dispatch a signed extrinsic.
// assert_ok!(TemplateModule::do_something(Origin::signed(1), 42));
// // Read pallet storage and assert an expected result.
// assert_eq!(TemplateModule::something(), Some(42));
// });
// }
//
// #[test]
// fn correct_error_for_none_value() {
// new_test_ext().execute_with(|| {
// // Ensure the expected error is thrown when no value is present.
// assert_noop!(
// TemplateModule::cause_error(Origin::signed(1)),
// Error::<Test>::NoneValue
// );
// });
// }
|
use crate::bucket::initialize_buckets;
use crate::data::{import_location_data, match_data_point};
use crate::hotspotmap::HotSpots;
use crate::msg::{HandleMsg, InitMsg, QueryAnswer, QueryMsg};
use crate::state::{config, config_read, State};
use crate::time::{new_day, query_dates};
use cosmwasm_std::{
to_binary, Api, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, QueryResult,
StdError, StdResult, Storage,
};
/// Initialize the contract with the start time, and the contract administrator
pub fn init<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
msg: InitMsg,
) -> StdResult<InitResponse> {
let state = State {
admin: vec![env.message.sender],
};
config(&mut deps.storage).save(&state)?;
// initialize data buckets
initialize_buckets(&mut deps.storage, msg.start_time)?;
Ok(InitResponse::default())
}
pub fn handle<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
msg: HandleMsg,
) -> StdResult<HandleResponse> {
let state = config_read(&deps.storage).load()?;
if !state.admin.contains(&env.message.sender) {
return Err(StdError::generic_err(
"You cannot functions from non-admin address".to_string(),
));
}
// see msg.rs for more details
match msg {
// add an admin
HandleMsg::AddAdmin { address } => add_admin(deps, env, address),
// remove an admin
HandleMsg::RemoveAdmin { address } => remove_admin(deps, env, address),
// signal that a day has passed
HandleMsg::ChangeDay {} => new_day(deps, env),
// import new geolocation data
HandleMsg::ImportGoogleLocations { data } => import_location_data(deps, env, data),
}
}
pub fn query<S: Storage, A: Api, Q: Querier>(deps: &Extern<S, A, Q>, msg: QueryMsg) -> QueryResult {
match msg {
QueryMsg::MatchDataPoints { data_points } => match_data_point(deps, data_points),
QueryMsg::HotSpot { accuracy, zones } => hotspots(deps, accuracy, zones),
QueryMsg::TimeRange {} => query_dates(deps),
}
}
pub fn hotspots<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
_accuracy: Option<u32>,
_zones: Option<u32>,
) -> QueryResult {
let res = HotSpots::load(&deps.storage)?;
return to_binary(&QueryAnswer::HotSpotResponse { hot_spots: res.0 });
}
pub fn add_admin<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
_env: Env,
address: HumanAddr,
) -> StdResult<HandleResponse> {
let mut state = config(&mut deps.storage).load()?;
if !state.admin.contains(&address) {
state.admin.push(address);
config(&mut deps.storage).save(&state)?;
}
Ok(HandleResponse::default())
}
pub fn remove_admin<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
_env: Env,
address: HumanAddr,
) -> StdResult<HandleResponse> {
let mut state = config(&mut deps.storage).load()?;
if let Some(index) = state.admin.iter().position(|a| a == &address) {
state.admin.remove(index);
config(&mut deps.storage).save(&state)?;
}
Ok(HandleResponse::default())
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Read;
use std::time::{Duration, Instant};
use cosmwasm_std::testing::{mock_dependencies, mock_env, MockApi, MockQuerier, MockStorage};
use cosmwasm_std::{Coin, Env, Extern, HumanAddr, InitResponse, MemoryStorage, StdResult};
use serde::{Deserialize, Serialize};
use serde_json;
use crate::contract::init;
use crate::data::import_location_data;
use crate::msg::HandleMsg::ImportGoogleLocations;
use crate::msg::InitMsg;
pub const MOCK_CONTRACT_ADDR: &str = "cosmos2contract";
pub fn init_deps(
canonical_length: usize,
contract_balance: &[Coin],
) -> Extern<MockStorage, MockApi, MockQuerier> {
let contract_addr = HumanAddr::from(MOCK_CONTRACT_ADDR);
Extern {
storage: MemoryStorage::default(),
api: MockApi::new(canonical_length),
querier: MockQuerier::new(&[(&contract_addr, contract_balance)]),
}
}
fn init_helper() -> (
StdResult<InitResponse>,
Extern<MockStorage, MockApi, MockQuerier>,
Env,
) {
let mut deps = init_deps(20, &[]);
let env = mock_env("instantiator", &[]);
let init_msg = InitMsg {
start_time: 1600129528955,
};
(init(&mut deps, env.clone(), init_msg), deps, env)
}
fn load_google_data() -> Vec<u8> {
let mut cert = vec![];
let mut f = File::open("tests/data/datamsg2.json").unwrap();
f.read_to_end(&mut cert).unwrap();
cert
}
#[test]
pub fn test_add_google_data() {
let data_msg: crate::msg::HandleMsg = serde_json::from_slice(&load_google_data()).unwrap();
let (res, mut deps, env) = init_helper();
let now = Instant::now();
crate::contract::handle(&mut deps, env, data_msg);
println!("elapsed: {}", now.elapsed().as_millis());
}
}
|
use serde::de::{SeqAccess, Visitor};
use std::marker::PhantomData;
pub trait EDNVisitor<'de>: Sized + Visitor<'de> {
type EDNValue;
fn visit_list<A>(self, seq: A) -> Result<<Self as Visitor<'de>>::Value, A::Error>
where
A: EDNSeqAccess<'de>,
{
let _ = seq;
unimplemented!()
// Err(Error::invalid_type(Unexpected::Seq, &self))
}
fn visit_vector<A>(self, seq: A) -> Result<<Self as Visitor<'de>>::Value, A::Error>
where
A: EDNSeqAccess<'de>,
{
let _ = seq;
unimplemented!()
// Err(Error::invalid_type(Unexpected::Seq, &self))
}
fn visit_set<A>(self, seq: A) -> Result<<Self as Visitor<'de>>::Value, A::Error>
where
A: EDNSeqAccess<'de>,
{
let _ = seq;
unimplemented!()
// Err(Error::invalid_type(Unexpected::Seq, &self))
}
// note: not borrowed so lifetime implicitly 'a (not 'de)
fn visit_symbol<E>(self, s: &str) -> Result<<Self as Visitor<'de>>::Value, E>;
fn visit_borrowed_symbol<E>(self, s: &'de str) -> Result<<Self as Visitor<'de>>::Value, E>;
fn visit_keyword<E>(self, s: &str) -> Result<<Self as Visitor<'de>>::Value, E>
where E: serde::de::Error;
fn visit_borrowed_keyword<E>(self, s: &'de str) -> Result<<Self as Visitor<'de>>::Value, E>
where E: serde::de::Error;
fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
where
A: EDNMapAccess<'de>,
{
let _ = map;
// Err(Error::invalid_type(Unexpected::Map, &self))
unimplemented!()
}
}
pub trait EDNDeserializer<'de>: Sized {
type Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: EDNVisitor<'de>;
fn deserialize_list<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: EDNVisitor<'de>;
}
pub trait EDNDeserialize<'de>: Sized {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, <D as EDNDeserializer<'de>>::Error>
where
D: EDNDeserializer<'de>;
}
pub trait EDNDeserializeOwned: for<'de> EDNDeserialize<'de> {}
impl<T> EDNDeserializeOwned for T where T: for<'de> EDNDeserialize<'de> {}
pub trait EDNDeserializeSeed<'de>: Sized
{
type Value;
fn deserialize<D>(self, deserializer: D) -> Result<<Self as EDNDeserializeSeed<'de>>::Value, <D as EDNDeserializer<'de>>::Error>
where
D: EDNDeserializer<'de>;
}
impl<'de, T> EDNDeserializeSeed<'de> for PhantomData<T>
where
T: EDNDeserialize<'de>,
{
type Value = T;
#[inline]
fn deserialize<D>(self, deserializer: D) -> Result<T, <D as EDNDeserializer<'de>>::Error>
where D: EDNDeserializer<'de>,
{
EDNDeserialize::deserialize(deserializer)
}
}
pub trait EDNSeqAccess<'de> {
type Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<<T as EDNDeserializeSeed<'de>>::Value>, Self::Error>
where
T: EDNDeserializeSeed<'de>;
#[inline]
fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
where
T: EDNDeserialize<'de>,
{
self.next_element_seed(PhantomData)
}
#[inline]
fn size_hint(&self) -> Option<usize> {
None
}
}
impl<'de, 'a, A> EDNSeqAccess<'de> for &'a mut A
where
A: EDNSeqAccess<'de>,
{
type Error = A::Error;
#[inline]
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<<T as EDNDeserializeSeed<'de>>::Value>, Self::Error>
where
T: EDNDeserializeSeed<'de>,
{
(**self).next_element_seed(seed)
}
#[inline]
fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
where
T: EDNDeserialize<'de>,
{
(**self).next_element()
}
#[inline]
fn size_hint(&self) -> Option<usize> {
(**self).size_hint()
}
}
pub trait EDNMapAccess<'de> {
type Error: serde::de::Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: EDNDeserializeSeed<'de>;
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: EDNDeserializeSeed<'de>;
#[inline]
fn next_entry_seed<K, V>(
&mut self,
kseed: K,
vseed: V,
) -> Result<Option<(K::Value, V::Value)>, Self::Error>
where
K: EDNDeserializeSeed<'de>,
V: EDNDeserializeSeed<'de>,
{
match try!(self.next_key_seed(kseed)) {
Some(key) => {
let value = try!(self.next_value_seed(vseed));
Ok(Some((key, value)))
}
None => Ok(None),
}
}
#[inline]
fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
where
K: EDNDeserialize<'de>,
{
self.next_key_seed(PhantomData)
}
#[inline]
fn next_value<V>(&mut self) -> Result<V, Self::Error>
where
V: EDNDeserialize<'de>,
{
self.next_value_seed(PhantomData)
}
#[inline]
fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
where
K: EDNDeserialize<'de>,
V: EDNDeserialize<'de>,
{
self.next_entry_seed(PhantomData, PhantomData)
}
#[inline]
fn size_hint(&self) -> Option<usize> {
None
}
}
impl<'de, 'a, A> EDNMapAccess<'de> for &'a mut A
where
A: EDNMapAccess<'de>,
{
type Error = A::Error;
#[inline]
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: EDNDeserializeSeed<'de>,
{
(**self).next_key_seed(seed)
}
#[inline]
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: EDNDeserializeSeed<'de>,
{
(**self).next_value_seed(seed)
}
#[inline]
fn next_entry_seed<K, V>(
&mut self,
kseed: K,
vseed: V,
) -> Result<Option<(K::Value, V::Value)>, Self::Error>
where
K: EDNDeserializeSeed<'de>,
V: EDNDeserializeSeed<'de>,
{
(**self).next_entry_seed(kseed, vseed)
}
#[inline]
fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
where
K: EDNDeserialize<'de>,
V: EDNDeserialize<'de>,
{
(**self).next_entry()
}
#[inline]
fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
where
K: EDNDeserialize<'de>,
{
(**self).next_key()
}
#[inline]
fn next_value<V>(&mut self) -> Result<V, Self::Error>
where
V: EDNDeserialize<'de>,
{
(**self).next_value()
}
#[inline]
fn size_hint(&self) -> Option<usize> {
(**self).size_hint()
}
}
pub trait EDNVariantAccess<'de>: Sized {
type Error: serde::de::Error;
fn unit_variant(self) -> Result<(), Self::Error>;
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
where
T: EDNDeserializeSeed<'de>;
#[inline]
fn newtype_variant<T>(self) -> Result<T, Self::Error>
where
T: EDNDeserialize<'de>,
{
self.newtype_variant_seed(PhantomData)
}
fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: EDNVisitor<'de>;
fn struct_variant<V>(
self,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: EDNVisitor<'de>;
}
|
use std::borrow::{Borrow, Cow};
use std::ffi::{c_void, CStr, CString, OsStr};
use std::fmt::{self, Debug, Display};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use firefly_intern::Symbol;
/// OwnedStringRef's represent a null-terminated string allocated by LLVM
/// over which ownership is our responsibility. In all respects these behave
/// like a regular StringRef, with the exception that they are always null
/// terminated.
#[repr(transparent)]
pub struct OwnedStringRef(StringRef);
impl OwnedStringRef {
/// Converts this to a CStr reference
pub fn as_cstr<'a>(&'a self) -> &'a CStr {
assert!(!self.data.is_null());
unsafe { CStr::from_ptr(self.0.data as *const std::os::raw::c_char) }
}
/// Converts a pointer to a null-terminated C string into an OwnedStringRef
///
/// This is highly unsafe, and should be used with APIs that return `const char*` with no length
pub unsafe fn from_ptr(ptr: *const std::os::raw::c_char) -> Self {
if ptr.is_null() {
return Self(StringRef::default());
}
let c_str = CStr::from_ptr(ptr);
Self(c_str.into())
}
}
impl From<String> for OwnedStringRef {
fn from(s: String) -> Self {
extern "C" {
fn LLVMCreateMessage(ptr: *const std::os::raw::c_char) -> *const std::os::raw::c_char;
}
let c_str = CString::new(s).unwrap();
unsafe { Self::from_ptr(LLVMCreateMessage(c_str.as_ptr())) }
}
}
impl Into<String> for OwnedStringRef {
fn into(self) -> String {
self.0.into()
}
}
impl Borrow<StringRef> for OwnedStringRef {
fn borrow(&self) -> &StringRef {
&self.0
}
}
impl Deref for OwnedStringRef {
type Target = StringRef;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Drop for OwnedStringRef {
fn drop(&mut self) {
extern "C" {
fn LLVMDisposeMessage(message: *const u8);
}
if self.0.is_null() {
return;
}
unsafe { LLVMDisposeMessage(self.0.data) }
}
}
impl Debug for OwnedStringRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl Display for OwnedStringRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// Corresponds to `llvm::StringRef`, which as you'd guess, is a
/// string reference - a pointer to a byte vector with a length.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct StringRef {
pub data: *const u8,
pub len: usize,
}
impl StringRef {
/// Returns true if this string ref has a null data pointer
#[inline]
pub fn is_null(&self) -> bool {
self.data.is_null()
}
/// Returns true if this string ref has no data
#[inline]
pub fn empty(&self) -> bool {
self.data.is_null() || self.len == 0
}
/// You should prefer to use `From`/`Into` or `TryFrom`/`TryInto` instead of this
pub unsafe fn from_raw_parts(data: *const u8, len: usize) -> Self {
Self { data, len }
}
/// This function is used to construct a StringRef from a null-terminated C-style string
///
/// This is equivalent to `CStr::from_ptr`, but allows you to avoid the extra song and dance
/// in places where you are frequently working with these types of strings.
///
/// NOTE: This is entirely unsafe, if you pass a pointer to a string that is not null-terminated,
/// it _will_ go wrong, so make sure you know what you're doing.
pub unsafe fn from_ptr(s: *const std::os::raw::c_char) -> Self {
CStr::from_ptr(s).into()
}
/// Returns true if this string is null terminated
///
/// NOTE: This is linear in the size of the underlying memory, you
/// should only use this when it is important to distinguish whether
/// or not null termination is required for the string
pub fn is_null_terminated(&self) -> bool {
assert!(!self.data.is_null());
let bytes = self.as_bytes();
bytes.iter().copied().any(|b| b == 0)
}
/// Return the underlying data as a byte slice
#[inline]
pub fn as_bytes(&self) -> &[u8] {
use core::slice;
unsafe { slice::from_raw_parts(self.data, self.len) }
}
/// Converts this stringref to a CStr/CString depending on whether it is null-terminated or not
pub fn to_cstr(&self) -> Cow<'_, CStr> {
if self.is_null_terminated() {
Cow::Borrowed(unsafe { CStr::from_ptr(self.data as *const std::os::raw::c_char) })
} else {
Cow::Owned(CString::new(self.as_bytes()).unwrap())
}
}
/// Converts this stringref to a Path/PathBuf depending on whether it is a lossy conversion
pub fn to_path_lossy(&self) -> Cow<'_, Path> {
match String::from_utf8_lossy(self.as_bytes()) {
Cow::Owned(s) => Cow::Owned(PathBuf::from(s)),
Cow::Borrowed(s) => Cow::Borrowed(Path::new(s)),
}
}
}
impl Default for StringRef {
fn default() -> StringRef {
Self {
data: core::ptr::null(),
len: 0,
}
}
}
impl From<Symbol> for StringRef {
#[inline]
fn from(s: Symbol) -> Self {
let bytes = s.as_str().get().as_bytes();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
}
impl From<&str> for StringRef {
#[inline]
fn from(s: &str) -> Self {
let bytes = s.as_bytes();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
}
impl From<&CStr> for StringRef {
fn from(s: &CStr) -> Self {
let bytes = s.to_bytes_with_nul();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
}
impl From<&CString> for StringRef {
fn from(s: &CString) -> Self {
let bytes = s.to_bytes_with_nul();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
}
impl From<&OsStr> for StringRef {
#[cfg(all(unix, target_env = "wasi"))]
fn from(s: &OsStr) -> Self {
use std::os::wasi::ffi::OsStrExt;
let bytes = s.as_bytes();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
#[cfg(all(unix, not(target_env = "wasi")))]
fn from(s: &OsStr) -> Self {
use std::os::unix::ffi::OsStrExt;
let bytes = s.as_bytes();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
#[cfg(windows)]
fn from(s: &OsStr) -> Self {
use std::os::windows::ffi::OsStrExt;
s.to_str().into()
}
}
impl From<&String> for StringRef {
#[inline]
fn from(s: &String) -> Self {
let bytes = s.as_bytes();
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
}
impl From<&[u8]> for StringRef {
#[inline(always)]
fn from(bytes: &[u8]) -> Self {
Self {
data: bytes.as_ptr(),
len: bytes.len(),
}
}
}
impl From<&Path> for StringRef {
#[inline]
#[cfg(all(target_arch = "wasm32", target_os = "wasi"))]
fn from(path: &Path) -> Self {
use std::os::wasi::ffi::OsStrExt;
path.as_os_str().as_bytes().into()
}
#[cfg(all(unix, not(target_os = "wasi")))]
fn from(path: &Path) -> Self {
use std::os::unix::ffi::OsStrExt;
path.as_os_str().as_bytes().into()
}
#[cfg(windows)]
fn from(path: &Path) -> Self {
path.to_str().unwrap().as_bytes().into()
}
}
impl<'a> TryInto<&'a str> for StringRef {
type Error = core::str::Utf8Error;
#[inline]
fn try_into(self) -> Result<&'a str, Self::Error> {
use core::slice;
let bytes = unsafe { slice::from_raw_parts(self.data, self.len) };
std::str::from_utf8(&bytes)
}
}
impl<'a> TryInto<&'a Path> for StringRef {
type Error = core::str::Utf8Error;
#[inline]
fn try_into(self) -> Result<&'a Path, Self::Error> {
use core::slice;
let bytes = unsafe { slice::from_raw_parts(self.data, self.len) };
std::str::from_utf8(&bytes).map(|s| Path::new(s))
}
}
impl<'a> Into<&'a [u8]> for StringRef {
#[inline]
fn into(self) -> &'a [u8] {
use core::slice;
unsafe { slice::from_raw_parts(self.data, self.len) }
}
}
impl Into<Vec<u8>> for StringRef {
#[inline]
fn into(self) -> Vec<u8> {
self.as_bytes().to_vec()
}
}
impl Into<String> for StringRef {
#[inline]
fn into(self) -> String {
use core::slice;
let bytes = unsafe { slice::from_raw_parts(self.data, self.len) };
String::from_utf8_lossy(&bytes).into_owned()
}
}
impl Eq for StringRef {}
impl PartialEq for StringRef {
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<str> for StringRef {
fn eq(&self, other: &str) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<String> for StringRef {
fn eq(&self, other: &String) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<[u8]> for StringRef {
fn eq(&self, other: &[u8]) -> bool {
self.as_bytes() == other
}
}
impl Debug for StringRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "StringRef({})", self)
}
}
impl Display for StringRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use core::slice;
if self.data.is_null() {
return f.write_str("");
}
let bytes = unsafe { slice::from_raw_parts(self.data, self.len) };
let s = match bytes.strip_suffix(&[0]) {
None => String::from_utf8_lossy(&bytes),
Some(stripped) => String::from_utf8_lossy(stripped),
};
write!(f, "{}", &s)
}
}
/// A callback for returning string references.
///
/// This function is called back by the functions that need to return a reference to
/// the portion of the string.
///
/// The final parameter is a pointer to user data forwarded from the printing call.
pub type MlirStringCallback = extern "C" fn(data: StringRef, userdata: *mut c_void);
pub extern "C" fn write_to_formatter(data: StringRef, result: *mut c_void) {
let f = unsafe { &mut *(result as *mut fmt::Formatter) };
write!(f, "{}", &data).unwrap();
}
|
use minidom::{Element, NSChoice};
use crate::error::Error;
pub trait ElementExt {
fn get_attr(&self, k: &'static str) -> Result<&str, Error>;
fn get_element(&self, k: &'static str) -> Result<&Element, Error>;
}
impl ElementExt for Element {
fn get_attr(&self, k: &'static str) -> Result<&str, Error> {
self.attr(k).ok_or_else(|| Error::MissingAttribute(k))
}
fn get_element(&self, k: &'static str) -> Result<&Element, Error> {
self.get_child(k, NSChoice::None)
.ok_or_else(|| Error::MissingElement(k))
}
}
|
use crate::url::Url;
use std::marker::PhantomData;
use std::str::FromStr;
pub trait Parse: Sized {
type Output;
fn parse(&self, url: &Url, index: usize) -> Option<(Self::Output, usize)>;
fn optional(self) -> Optional<Self> {
Optional(self)
}
}
impl<'a> Parse for &'a str {
type Output = ();
fn parse(&self, url: &Url, index: usize) -> Option<(Self::Output, usize)> {
if url.path.get(index).map_or(false, |string| string == self) {
Some(((), index + 1))
} else {
None
}
}
}
#[derive(Debug)]
pub struct Param<T: FromStr>(PhantomData<T>);
pub fn param<T: FromStr>() -> Param<T> {
Param(PhantomData)
}
impl<T: FromStr> Parse for Param<T> {
type Output = T;
fn parse(&self, url: &Url, index: usize) -> Option<(Self::Output, usize)> {
if let Some(param) = url.path.get(index) {
if let Ok(ok) = param.parse() {
return Some((ok, index + 1));
}
}
None
}
}
#[derive(Debug)]
pub struct Query<'a, T: FromStr>(&'a str, PhantomData<T>);
pub fn query<T: FromStr>(name: &str) -> Query<T> {
Query(name, PhantomData)
}
impl<'a, T: FromStr> Parse for Query<'a, T> {
type Output = T;
fn parse(&self, url: &Url, index: usize) -> Option<(Self::Output, usize)> {
if let Some(value) = url.query.iter().find(|(k, _)| k == self.0).map(|(_, v)| v) {
if let Ok(ok) = value.parse() {
return Some((ok, index));
}
}
None
}
}
#[derive(Debug)]
pub struct Hash<T: FromStr>(PhantomData<T>);
pub fn hash<T: FromStr>() -> Hash<T> {
Hash(PhantomData)
}
impl<T: FromStr> Parse for Hash<T> {
type Output = T;
fn parse(&self, url: &Url, index: usize) -> Option<(Self::Output, usize)> {
if let Some(ref hash) = url.hash {
if let Ok(ok) = hash.parse() {
return Some((ok, index));
}
}
None
}
}
impl Parse for () {
type Output = ();
fn parse(&self, _url: &Url, index: usize) -> Option<(Self::Output, usize)> {
Some(((), index))
}
}
macro_rules! go {
($($($ident:ident)+,)+) => {
$(
impl<$($ident: Parse,)+> Parse for ($($ident,)+) {
type Output = ($($ident::Output,)+);
fn parse(&self, url: &Url, mut index: usize) -> Option<(Self::Output, usize)> {
#[allow(non_snake_case)]
let ($($ident,)+) = self;
$(
#[allow(non_snake_case)]
let ($ident, new_index) = $ident.parse(url, index)?;
index = new_index;
)*
Some((($($ident,)+), index))
}
}
)+
}
}
go! {
A,
A B,
A B C,
A B C D,
A B C D E,
A B C D E F,
A B C D E F G,
A B C D E F G H,
A B C D E F G H I,
A B C D E F G H I J,
}
#[derive(Debug)]
pub struct Optional<T: Parse>(T);
impl<T: Parse> Parse for Optional<T> {
type Output = Option<T::Output>;
fn parse(&self, url: &Url, index: usize) -> Option<(Self::Output, usize)> {
if let Some((t, index)) = self.0.parse(url, index) {
Some((Some(t), index))
} else {
Some((None, index))
}
}
}
#[derive(Debug)]
pub struct Parser<'a, T> {
url: &'a Url,
value: Option<T>,
}
impl<'a, T> Parser<'a, T> {
pub fn new(url: &'a Url) -> Self {
Parser { url, value: None }
}
pub fn when<P: Parse>(mut self, p: P, f: impl Fn(P::Output) -> T) -> Self {
if self.value.is_none() {
if let Some((route, index)) = p.parse(self.url, 0) {
if index == self.url.path.len() {
self.value = Some(f(route));
return self;
}
}
}
self
}
pub fn finish(self) -> Option<T> {
self.value
}
}
pub fn parse<T>(url: &Url) -> Parser<T> {
Parser::new(url)
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct Battery(pub ::windows::core::IInspectable);
impl Battery {
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn GetReport(&self) -> ::windows::core::Result<BatteryReport> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BatteryReport>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportUpdated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<Battery, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveReportUpdated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
pub fn AggregateBattery() -> ::windows::core::Result<Battery> {
Self::IBatteryStatics(|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::<Battery>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<Battery>> {
Self::IBatteryStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<Battery>>(result__)
})
}
pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IBatteryStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IBatteryStatics<R, F: FnOnce(&IBatteryStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Battery, IBatteryStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for Battery {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Power.Battery;{bc894fc6-0072-47c8-8b5d-614aaa7a437e})");
}
unsafe impl ::windows::core::Interface for Battery {
type Vtable = IBattery_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc894fc6_0072_47c8_8b5d_614aaa7a437e);
}
impl ::windows::core::RuntimeName for Battery {
const NAME: &'static str = "Windows.Devices.Power.Battery";
}
impl ::core::convert::From<Battery> for ::windows::core::IUnknown {
fn from(value: Battery) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&Battery> for ::windows::core::IUnknown {
fn from(value: &Battery) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for Battery {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a Battery {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<Battery> for ::windows::core::IInspectable {
fn from(value: Battery) -> Self {
value.0
}
}
impl ::core::convert::From<&Battery> for ::windows::core::IInspectable {
fn from(value: &Battery) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for Battery {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a Battery {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for Battery {}
unsafe impl ::core::marker::Sync for Battery {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct BatteryReport(pub ::windows::core::IInspectable);
impl BatteryReport {
#[cfg(feature = "Foundation")]
pub fn ChargeRateInMilliwatts(&self) -> ::windows::core::Result<super::super::Foundation::IReference<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<i32>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn DesignCapacityInMilliwattHours(&self) -> ::windows::core::Result<super::super::Foundation::IReference<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<i32>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn FullChargeCapacityInMilliwattHours(&self) -> ::windows::core::Result<super::super::Foundation::IReference<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<i32>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemainingCapacityInMilliwattHours(&self) -> ::windows::core::Result<super::super::Foundation::IReference<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<i32>>(result__)
}
}
#[cfg(feature = "System_Power")]
pub fn Status(&self) -> ::windows::core::Result<super::super::System::Power::BatteryStatus> {
let this = self;
unsafe {
let mut result__: super::super::System::Power::BatteryStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::System::Power::BatteryStatus>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for BatteryReport {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Power.BatteryReport;{c9858c3a-4e13-420a-a8d0-24f18f395401})");
}
unsafe impl ::windows::core::Interface for BatteryReport {
type Vtable = IBatteryReport_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc9858c3a_4e13_420a_a8d0_24f18f395401);
}
impl ::windows::core::RuntimeName for BatteryReport {
const NAME: &'static str = "Windows.Devices.Power.BatteryReport";
}
impl ::core::convert::From<BatteryReport> for ::windows::core::IUnknown {
fn from(value: BatteryReport) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&BatteryReport> for ::windows::core::IUnknown {
fn from(value: &BatteryReport) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BatteryReport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BatteryReport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<BatteryReport> for ::windows::core::IInspectable {
fn from(value: BatteryReport) -> Self {
value.0
}
}
impl ::core::convert::From<&BatteryReport> for ::windows::core::IInspectable {
fn from(value: &BatteryReport) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BatteryReport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BatteryReport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for BatteryReport {}
unsafe impl ::core::marker::Sync for BatteryReport {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IBattery(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IBattery {
type Vtable = IBattery_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc894fc6_0072_47c8_8b5d_614aaa7a437e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBattery_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IBatteryReport(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IBatteryReport {
type Vtable = IBatteryReport_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc9858c3a_4e13_420a_a8d0_24f18f395401);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBatteryReport_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "System_Power")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::System::Power::BatteryStatus) -> ::windows::core::HRESULT,
#[cfg(not(feature = "System_Power"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IBatteryStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IBatteryStatics {
type Vtable = IBatteryStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79cd72b6_9e5e_4452_bea6_dfcd541e597f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBatteryStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
|
fn add_em_up(n1: i32, n2: i32) -> i32 {
n1 + n2
}
fn main() {
let x = 1;
let y = 2;
let (a, b) = (10, 20);
println!("greetings, x={} and y={}", x, y);
let answer: i32 = add_em_up(a, x);
println!("addem: {}", answer);
}
|
#![allow(clippy::print_literal)]
use abi_stable::library::{
development_utils::compute_library_path, LibraryError, RootModule, RootModuleError,
};
use testing_interface_1::{
get_env_vars, NonAbiStableLib_Ref, ReturnWhat, TestingMod_Ref, WithIncompatibleLayout_Ref,
};
use std::fmt;
fn main() {
let target: &std::path::Path = "../../../target/".as_ref();
let envars = get_env_vars();
println!("app: {:?}", envars);
{
let err = WithIncompatibleLayout_Ref::load_from_directory("foo/bar/bar".as_ref())
.err()
.unwrap();
assert!(matches!(err, LibraryError::OpenError { .. }), "{:?}", err,);
}
{
let library_path = compute_library_path::<WithIncompatibleLayout_Ref>(target).unwrap();
let err = NonAbiStableLib_Ref::load_from_directory(&library_path)
.err()
.unwrap();
assert!(
matches!(err, LibraryError::GetSymbolError { .. }),
"{:?}",
err,
);
}
{
let library_path = compute_library_path::<WithIncompatibleLayout_Ref>(target).unwrap();
let err = WithIncompatibleLayout_Ref::load_from_directory(&library_path)
.err()
.unwrap();
assert!(matches!(err, LibraryError::AbiInstability(_)), "{:#}", err,);
// Doing this to make sure that the error formatting is not optimized out.
let formatted = format!("{0} {0:?}", err);
println!(
"sum of bytes in the error: {}",
formatted.bytes().map(|x| x as u64).sum::<u64>()
);
}
{
let library_path = compute_library_path::<TestingMod_Ref>(target).unwrap();
let res = TestingMod_Ref::load_from_directory(&library_path);
match envars.return_what {
ReturnWhat::Ok => {
let module = res.unwrap();
assert_eq!(module.a(), 5);
assert_eq!(module.b(), 8);
assert_eq!(module.c(), 13);
}
ReturnWhat::Error | ReturnWhat::Panic => {
let err = res.err().expect("Expected the library to return an error");
if let LibraryError::RootModule { err: rm_err, .. } = &err {
assert!(
matches!((&envars.return_what, rm_err), |(
ReturnWhat::Error,
RootModuleError::Returned { .. },
)| (
ReturnWhat::Panic,
RootModuleError::Unwound { .. }
)),
"return_what: {:?}\nerror: {:?}",
envars.return_what,
rm_err,
);
print_error_sum(line!(), rm_err);
} else {
panic!(
"Expected a LibraryError::RootModule, found this instead:\n{:#?}",
err,
);
}
print_error_sum(line!(), err);
}
}
println!(
"\n{S}{S}\n\nFinished successfully\n\n{S}{S}\n",
S = "----------------------------------------",
);
}
}
fn print_error_sum<E: fmt::Debug + fmt::Display>(line: u32, e: E) {
let formatted = format!("{0} {0:?}", e);
let sum = formatted.bytes().map(|x| x as u64).sum::<u64>();
println!("{}: sum of bytes in the error: {}", line, sum);
}
|
//! Field of view calculation.
//!
//! A position is considered to be in field of view from an origin
//! if and only if the position is on a line with an endpoint at the
//! origin not blocked by any wall.
use grid::{Pos, DIRECTIONS};
use num::rational::Ratio;
use num::traits::identities::{One, Zero};
/// Calculates field of view.
///
/// All this does is call scan on each of the six sextants.
pub fn calc_fov<F, G>(center: Pos, transparent: F, mut reveal: G)
where
F: Fn(Pos) -> bool,
G: FnMut(Pos),
{
reveal(center);
for &dy in &DIRECTIONS {
let dx = dy.rotate(2);
let f = |x, y| transparent(center + dx * x + dy * y);
let mut g = |x, y| reveal(center + dx * x + dy * y);
scan(1, Ratio::zero(), Ratio::one(), &f, &mut g);
}
}
/// Scan a sextant using recursive shadowcasting.
///
/// y represents the distance from the center.
/// Within this function, x represents the distance from the y-axis, and
/// the x-axis is rotated 120 degrees from the y-axis when using hex coordinates.
/// However, nothing in this function is specific to hex coordinates.
/// start and end give the slopes (x/y, not y/x) that bound the current scan.
/// They range from 0 to 1. There is no check that start <= end, but it is always the case.
/// The transparent and reveal closures abstract away the grid system.
/// Passing in different closures will let you operate over different sextants.
fn scan<F, G>(y: u32, start: Ratio<u32>, end: Ratio<u32>, transparent: &F, reveal: &mut G)
where
F: Fn(u32, u32) -> bool,
G: FnMut(u32, u32),
{
// Define the range of x-coordinates.
// We break ties inward because ties represent diagonal moves, and
// when the start and and end slopes are restricted by walls, they
// pick the inner diagonal tiebreaker to avoid going through walls.
let min_x = round_tie_high(start * y);
let max_x = round_tie_low(end * y);
// We process min_x outside of the loop in order to define start well.
// This avoids checking for edge cases within the loop
// had we initialized start to Some(start) unconditionally.
reveal(min_x, y);
// We rebind start to avoid accidentally using an old, invalid start slope.
// Some(slope) corresponds to the case where we are scanning an open segment.
// None corresponds to the case where we are scanning through a wall.
let mut start = if transparent(min_x, y) {
Some(start)
} else {
None
};
for x in min_x + 1..=max_x {
reveal(x, y);
if transparent(x, y) {
if start.is_none() {
start = Some(slope(x, y));
}
} else {
if let Some(start_slope) = start {
scan(y + 1, start_slope, slope(x, y), transparent, reveal);
start = None;
}
}
}
if let Some(start) = start {
scan(y + 1, start, end, transparent, reveal);
}
}
/// Returns the slope of the ray flush with the left side of (x, y).
/// Here left means the side of (x, y) on the x-axis with the smaller x-value.
///
/// When (x, y) corresponds to a wall, the result represents the largest possible end slope.
/// When it corresponds to a floor, the result represents the smallest possible start slope.
fn slope(x: u32, y: u32) -> Ratio<u32> {
Ratio::new_raw(2 * x - 1, 2 * y)
}
/// Rounds a ratio. Ties are rounded up.
fn round_tie_high(x: Ratio<u32>) -> u32 {
x.round().to_integer()
}
/// Rounds a ratio. Ties are rounded down.
fn round_tie_low(x: Ratio<u32>) -> u32 {
(x - Ratio::new_raw(1, 2)).ceil().to_integer()
}
|
use crossbeam::channel::Sender;
use crate::compress;
pub struct Match
{
pub position: usize,
pub length: u16,
pub distance: u16
}
pub fn find( input: &[u8], output: Sender<Match>, opts: &compress::Options )
{
let len = input.len();
if len > MIN_MATCH
{
let mut m = Matcher::new( len, opts );
m.find( input, output );
}
}
// RFC 1951 match ( LZ77 ) limits.
const MIN_MATCH : usize = 3; // The smallest match eligible for LZ77 encoding.
const MAX_MATCH : usize = 258; // The largest match eligible for LZ77 encoding.
const MAX_DISTANCE : usize = 0x8000; // The largest distance backwards in input from current position that can be encoded.
const ENCODE_POSITION : usize = MAX_DISTANCE + 1;
struct Matcher
{
hash_shift: usize,
hash_mask: usize,
hash_table: Vec<usize>,
probe_max: usize,
lazy_match: bool
}
impl Matcher
{
fn new( len: usize, opts: &compress::Options ) -> Matcher
{
let hash_shift = calc_hash_shift( len * 2 );
let hash_mask = ( 1 << ( MIN_MATCH * hash_shift ) ) - 1;
Matcher{
hash_shift,
hash_mask,
hash_table: vec![ 0; hash_mask + 1 ],
probe_max: opts.probe_max,
lazy_match: opts.lazy_match
}
}
fn find( &mut self, input: &[u8], output: Sender<Match> ) // LZ77 compression.
{
let limit = input.len() - 2;
let mut link : Vec<usize> = vec!(0; limit);
let mut position = 0; // position in input.
// hash will be hash of three bytes starting at position.
let mut hash = ( ( input[ 0 ] as usize ) << self.hash_shift ) + input[ 1 ] as usize;
while position < limit
{
hash = ( ( hash << self.hash_shift ) + input[ position + 2 ] as usize ) & self.hash_mask;
let mut hash_entry = self.hash_table[ hash ];
self.hash_table[ hash ] = position + ENCODE_POSITION;
if position >= hash_entry // Equivalent to position - ( hash_entry - ENCODE_POSITION ) > MAX_DISTANCE.
{
position += 1;
continue;
}
link[ position ] = hash_entry;
let ( mut match1, mut distance1 ) = self.best_match( input, position, hash_entry - ENCODE_POSITION, &mut link );
position += 1;
if match1 < MIN_MATCH { continue; }
// "Lazy matching" RFC 1951 p.15 : if there are overlapping matches, there is a choice over which of the match to use.
// Example: "abc012bc345.... abc345". Here abc345 can be encoded as either [abc][345] or as a[bc345].
// Since a range typically needs more bits to encode than a single literal, choose the latter.
while position < limit
{
hash = ( ( hash << self.hash_shift ) + input[ position + 2 ] as usize ) & self.hash_mask;
hash_entry = self.hash_table[ hash ];
self.hash_table[ hash ] = position + ENCODE_POSITION;
if position >= hash_entry { break; }
link[ position ] = hash_entry;
if !self.lazy_match { break; }
let ( match2, distance2 ) = self.best_match( input, position, hash_entry - ENCODE_POSITION, &mut link );
if match2 > match1 || match2 == match1 && distance2 < distance1
{
match1 = match2;
distance1 = distance2;
position += 1;
}
else { break; }
}
output.send( Match{ position:position-1, length:match1 as u16, distance:distance1 as u16 } ).unwrap();
let mut copy_end = position - 1 + match1;
if copy_end > limit { copy_end = limit; }
position += 1;
// Advance to end of copied section.
while position < copy_end
{
hash = ( ( hash << self.hash_shift ) + input[ position + 2 ] as usize ) & self.hash_mask;
link[ position ] = self.hash_table[ hash ];
self.hash_table[ hash ] = position + ENCODE_POSITION;
position += 1;
}
}
}
// best_match finds the best match starting at position.
// old_position is from hash table, link [] is linked list of older positions.
fn best_match( &mut self, input: &[u8], position: usize, mut old_position: usize, link: &mut Vec<usize> ) -> ( usize, usize )
{
let mut avail = input.len() - position;
if avail > MAX_MATCH { avail = MAX_MATCH; }
let mut best_match = 0; let mut best_distance = 0;
let mut key_byte = input[ position + best_match ];
let mut probe_max: usize = self.probe_max;
while probe_max > 0
{
if input[ old_position + best_match ] == key_byte
{
let mut mat = 0;
while mat < avail && input[ position + mat ] == input[ old_position + mat ]
{
mat += 1;
}
if mat > best_match
{
best_match = mat;
best_distance = position - old_position;
if best_match == avail || ! self.match_possible( input, position, best_match ) { break; }
key_byte = input[ position + best_match ];
}
}
old_position = link[ old_position ];
if old_position <= position { break; }
old_position -= ENCODE_POSITION;
probe_max -= 1;
}
( best_match, best_distance )
}
// match_possible is used to try and shorten the best_match search by checking whether
// there is a hash entry for the last 3 bytes of the next longest possible match.
fn match_possible( &mut self, input: &[u8], mut position: usize, best_match: usize ) -> bool
{
position = ( position + best_match ) - 2;
let mut hash = ( ( input[ position ] as usize ) << self.hash_shift ) + input[ position + 1 ] as usize;
hash = ( ( hash << self.hash_shift ) + input[ position + 2 ] as usize ) & self.hash_mask;
position < self.hash_table[ hash ]
}
} // end impl Matcher
fn calc_hash_shift( n: usize ) -> usize
{
let mut p = 1;
let mut result = 0;
while n > p
{
p <<= MIN_MATCH;
result += 1;
if result == 6 { break; }
}
result
}
|
use bit_vec::BitVec;
pub fn bitvec_from_u32(value: u32) -> BitVec<u32> {
let mut bv = BitVec::from_elem(32, false);
for i in 0..32 {
if value & (1 << i) != 0 {
bv.set(i, true);
}
}
bv
}
pub fn u32_from_bitvec(bv: &BitVec<u32>) -> u32 {
let mut val = 0;
let mut index = 0;
for bit in bv {
if bit == true {
val |= 1 << index;
}
index += 1;
}
val
}
|
mod with_atom_left;
mod with_big_integer_left;
mod with_empty_list_left;
mod with_external_pid_left;
mod with_float_left;
mod with_function_left;
mod with_heap_binary_left;
mod with_list_left;
mod with_local_pid_left;
mod with_local_reference_left;
mod with_map_left;
mod with_small_integer_left;
mod with_subbinary_left;
mod with_tuple_left;
use std::convert::TryInto;
use std::ptr::NonNull;
use proptest::arbitrary::any;
use proptest::prop_assert_eq;
use proptest::strategy::{Just, Strategy};
use proptest::test_runner::{Config, TestRunner};
use liblumen_alloc::erts::process::alloc::TermAlloc;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::are_equal_after_conversion_2::result;
use crate::test::strategy;
use crate::test::with_process_arc;
#[test]
fn without_numbers_are_not_equal_after_conversion_if_not_equal_before_conversion() {
run!(
|arc_process| {
(
strategy::term::is_not_number(arc_process.clone()),
strategy::term::is_not_number(arc_process),
)
.prop_filter(
"Left must not equal right before conversion",
|(left, right)| left != right,
)
},
|(left, right)| {
prop_assert_eq!(result(left, right), false.into());
Ok(())
},
);
}
|
use bytes::Bytes;
use model::command::*;
use model::controll::*;
use model::response::SmtpReply;
use std::collections::VecDeque;
use std::net::SocketAddr;
#[derive(Clone)]
pub struct Session {
state: State,
name: String,
peer: Option<SocketAddr>,
local: Option<SocketAddr>,
helo: Option<SmtpHelo>,
mail: Option<SmtpMail>,
rcpts: Vec<SmtpPath>,
answers: VecDeque<ClientControll>,
}
#[derive(Clone, PartialEq, Eq)]
enum State {
New,
Start,
Helo,
Mail,
Rcpt,
Data,
}
impl Session {
pub fn new() -> Self {
Self {
state: State::New,
name: "Samotop".into(),
peer: None,
local: None,
helo: None,
mail: None,
rcpts: vec![],
answers: vec![].into(),
}
}
pub fn set_name(&mut self, name: impl ToString) {
self.name = name.to_string();
}
pub fn answer(&mut self) -> Option<ClientControll> {
self.answers.pop_front()
}
pub fn controll(&mut self, ctrl: ServerControll) -> &mut Self {
use model::controll::ServerControll::*;
match ctrl {
PeerConnected(peer) => self.conn(peer),
PeerShutdown(peer) => self.shut(peer),
Invalid(_) => self.say_syntax_error(),
Command(cmd) => self.cmd(cmd),
DataChunk(data) => self.data(data),
EscapeDot(_data) => self,
FinalDot(_data) => self.data_end(),
}
}
pub fn data_end(&mut self) -> &mut Self {
trace!("watching data finishing up!");
self
}
pub fn data(&mut self, data: Bytes) -> &mut Self {
trace!("watching data pass by!");
self
}
pub fn conn(&mut self, peer: Option<SocketAddr>) -> &mut Self {
self.state = State::New;
self.peer = peer;
self.rcpts.clear();
self.mail = None;
self.helo = None;
self.say_ready()
}
pub fn shut(&mut self, _peer: Option<SocketAddr>) -> &mut Self {
self.state = State::New;
self.peer = None;
self.rcpts.clear();
self.mail = None;
self.helo = None;
self.say_shutdown()
}
pub fn cmd(&mut self, cmd: SmtpCommand) -> &mut Self {
use model::command::SmtpCommand::*;
match cmd {
Helo(from) => self.cmd_helo(from),
Mail(mail) => self.cmd_mail(mail),
Rcpt(path) => self.cmd_rcpt(path),
Data => self.cmd_data(),
Quit => self.cmd_quit(),
Rset => self.cmd_rset(),
Noop(_) => self.cmd_noop(),
_ => self.say_not_implemented(),
}
}
pub fn cmd_quit(&mut self) -> &mut Self {
self.state = State::New;
self.helo = None;
self.mail = None;
self.rcpts.clear();
let name = self.name().into();
self.say_reply(SmtpReply::ClosingConnectionInfo(name))
.say_shutdown()
}
pub fn cmd_data(&mut self) -> &mut Self {
if self.helo == None || self.mail == None || self.rcpts.len() == 0 {
self.say_command_sequence_fail()
} else {
self.state = State::Data;
self.say(ClientControll::AcceptData)
.say_reply(SmtpReply::StartMailInputChallenge)
}
}
pub fn cmd_rcpt(&mut self, path: SmtpPath) -> &mut Self {
if (self.state != State::Mail && self.state != State::Rcpt)
|| self.helo == None
|| self.mail == None
{
self.say_command_sequence_fail()
} else {
self.state = State::Rcpt;
self.rcpts.push(path);
self.say_ok()
}
}
pub fn cmd_mail(&mut self, mail: SmtpMail) -> &mut Self {
if self.state != State::Helo || self.helo == None {
self.say_command_sequence_fail()
} else {
self.state = State::Mail;
self.mail = Some(mail);
self.say_ok()
}
}
pub fn cmd_helo(&mut self, helo: SmtpHelo) -> &mut Self {
// reset bufers
self.rcpts.clear();
self.mail = None;
//set new state
self.state = State::Helo;
let remote = helo.name();
self.helo = Some(helo);
self.say_hi(remote)
}
pub fn cmd_rset(&mut self) -> &mut Self {
// reset bufers
self.rcpts.clear();
self.mail = None;
//set new state
self.state = State::Helo;
self.say_ok()
}
pub fn cmd_noop(&mut self) -> &mut Self {
self.say_ok()
}
pub fn name(&self) -> &str {
&self.name
}
pub fn helo(&self) -> Option<&SmtpHelo> {
self.helo.as_ref()
}
pub fn mail(&self) -> Option<&SmtpMail> {
self.mail.as_ref()
}
pub fn peer(&self) -> Option<&SocketAddr> {
self.peer.as_ref()
}
pub fn rcpts(&self) -> impl Iterator<Item = &SmtpPath> {
self.rcpts.iter()
}
pub fn say(&mut self, c: ClientControll) -> &mut Self {
self.answers.push_back(c);
self
}
pub fn say_reply(&mut self, c: SmtpReply) -> &mut Self {
self.say(ClientControll::Reply(c))
}
pub fn say_shutdown(&mut self) -> &mut Self {
self.say(ClientControll::Shutdown)
}
pub fn say_ready(&mut self) -> &mut Self {
let name = self.name().into();
self.say_reply(SmtpReply::ServiceReadyInfo(name))
}
pub fn say_ok(&mut self) -> &mut Self {
self.say_reply(SmtpReply::OkInfo)
}
pub fn say_hi(&mut self, remote: String) -> &mut Self {
let local = self.name.clone();
self.say_reply(SmtpReply::OkHeloInfo { local, remote })
}
pub fn say_command_sequence_fail(&mut self) -> &mut Self {
self.say_reply(SmtpReply::CommandSequenceFailure)
}
pub fn say_syntax_error(&mut self) -> &mut Self {
self.say_reply(SmtpReply::CommandSyntaxFailure)
}
pub fn say_not_implemented(&mut self) -> &mut Self {
self.say_reply(SmtpReply::CommandNotImplementedFailure)
}
}
|
pub struct Rect {
pub x1: i32,
pub x2: i32,
pub y1: i32,
pub y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32) -> Rect {
//x y here are the coordinates of the rectangle start
//so all we need is sort of this L to define the rectangle
//x1 y1 are the coordinates for the first pixel
//y0 is the first row of characters starting from the top
//x0 is the first character to the left
Rect {
x1: x,
y1: y,
x2: x + w,
y2: y + h,
}
}
//this is a pure function i see because we pass in parameters but it can't modify anything
//as everything that is passed as parameter is immutable
pub fn intersect(&self, other: &Rect) -> bool {
self.x1 <= other.x2 && self.x2 >= other.x1 && self.y1 <= other.y2 && self.y2 >= other.y1
}
pub fn center(&self) -> (i32, i32) {
((self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2)
}
}
|
#![allow(dead_code)]
use crate::{regex, utils};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use utils::{AOCResult};
lazy_static! {
static ref MEM_REGEX: Regex = regex!(r"^mem\[([0-9]+)\] = ([0-9]+)$");
static ref MASK_REGEX: Regex = regex!(r"^mask = ([X01]+)$");
}
type Mask = (u64, u64, u64);
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Instruction {
Memory { address: u64, value: u64},
Mask(Mask),
}
pub struct Program {
instructions: Vec<Instruction>,
}
impl Program {
pub fn load(filename: &str) -> AOCResult<Self> {
let input = utils::get_input(filename);
let mut instructions = Vec::new();
for line in input {
let instruction = if let Some(capture) = MASK_REGEX.captures_iter(&line).next() {
Instruction::Mask(Program::mask_instruction(&capture[1]))
} else {
let mem_capture = MEM_REGEX.captures_iter(&line).next()?;
Instruction::Memory{
address: mem_capture[1].parse::<u64>()?,
value: mem_capture[2].parse::<u64>()?,
}
};
instructions.push(instruction);
}
Ok(Program {
instructions,
})
}
fn mask_instruction(mask_capture: &str) -> Mask {
let mut mask_1 = 0;
let mut mask_0 = 0;
let mut mask_x = 0;
for bit in mask_capture.chars() {
mask_1 <<= 1;
mask_0 <<= 1;
mask_x <<= 1;
if bit == '1' {
mask_1 += 1;
}
if bit != '0' {
mask_0 += 1;
}
if bit == 'X' {
mask_x += 1;
}
}
(mask_0, mask_1, mask_x)
}
fn all_masks(_mask_0: u64, mask_1: u64, mask_x: u64) -> Vec<(u64, u64)> {
// APPARENTLY 0 masks by default means "don't do anything"
// but we'll leverage it later to force overwritting some values to 0
let mut masks: Vec<(u64, u64)> = vec![(!0, mask_1)];
if mask_x != 0 {
for x in 0..36 {
let candidate = 1 << x;
if mask_x & candidate != 0 {
for mask in masks.iter_mut() {
mask.1 += candidate;
}
masks.extend(
masks.iter().map(|mask| (
mask.0 - candidate,
mask.1 - candidate,
)).collect::<Vec<(u64, u64)>>());
}
}
}
masks
}
fn apply_mask(mask_0: u64, mask_1: u64, value: u64) -> u64 {
(value & mask_0) | mask_1
}
pub fn part_1(&self) -> u64 {
let mut memory = HashMap::new();
let mut mask_0 = 0;
let mut mask_1 = 1;
for instruction in self.instructions.iter() {
match instruction {
Instruction::Mask((m0, m1, _)) => {
mask_0 = *m0;
mask_1 = *m1;
},
Instruction::Memory{ address, value } => {
memory.insert(*address, Program::apply_mask(mask_0, mask_1, *value));
}
}
}
memory.iter().fold(0, |a, (_k, v)| a + v)
}
pub fn part_2(&self) -> u64 {
let mut memory = HashMap::new();
let mut masks = Vec::new();
for instruction in self.instructions.iter() {
match instruction {
Instruction::Mask((m0, m1, mx)) => {
masks = Program::all_masks(*m0, *m1, *mx)
},
Instruction::Memory{ address, value } => {
for mask in masks.iter() {
memory.insert( Program::apply_mask(mask.0, mask.1, *address), *value);
}
}
}
}
memory.iter().fold(0, |a, (_k, v)| a + v)
}
}
pub fn day14() {
let program = Program::load("day14").unwrap();
println!("docking_data part 1: {}", program.part_1());
println!("docking_data part 2: {}", program.part_2());
}
#[test]
pub fn test_day14() {
//let program = Program::load("test_day14").unwrap();
//assert_eq!(program.part_1(), 165);
let program = Program::load("test_day14_2").unwrap();
assert_eq!(program.part_2(), 208)
}
#[test]
pub fn test_day14_apply() {
let mask = Program::mask_instruction("000000000000000000000000000000X1001X");
let all_masks = Program::all_masks(mask.0, mask.1, mask.2);
assert_eq!(
all_masks.iter().map(|(m0, m1)| Program::apply_mask(*m0, *m1, 42)).collect::<Vec<u64>>(),
vec![
59, 58, 27, 26
]
);
}
|
use std::convert::TryInto;
use anyhow::*;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::context::{r#type, term_is_not_type};
pub fn element_not_a_binary_context(iolist_or_binary: Term, element: Term) -> String {
format!(
"iolist_or_binary ({}) element ({}) is a bitstring, but not a binary",
iolist_or_binary, element
)
}
pub fn element_type_context(iolist_or_binary: Term, element: Term) -> String {
format!(
"iolist_or_binary ({}) element ({}) is not a byte, binary, or nested iolist ({})",
iolist_or_binary,
element,
r#type::IOLIST
)
}
pub fn result(
process: &Process,
iolist_or_binary: Term,
try_into: fn(&Process, Term) -> exception::Result<Term>,
) -> exception::Result<Term> {
match iolist_or_binary.decode()? {
TypedTerm::Nil
| TypedTerm::List(_)
| TypedTerm::BinaryLiteral(_)
| TypedTerm::HeapBinary(_)
| TypedTerm::MatchContext(_)
| TypedTerm::ProcBin(_)
| TypedTerm::SubBinary(_) => try_into(process, iolist_or_binary),
_ => Err(TypeError)
.context(term_is_not_type(
"iolist_or_binary",
iolist_or_binary,
&format!("an iolist ({}) or binary", r#type::IOLIST),
))
.map_err(From::from),
}
}
pub fn to_binary(process: &Process, name: &'static str, value: Term) -> exception::Result<Term> {
let mut byte_vec: Vec<u8> = Vec::new();
let mut stack: Vec<Term> = vec![value];
while let Some(top) = stack.pop() {
match top.decode()? {
TypedTerm::SmallInteger(small_integer) => {
let top_byte = small_integer
.try_into()
.with_context(|| element_context(name, value, top))?;
byte_vec.push(top_byte);
}
TypedTerm::Nil => (),
TypedTerm::List(boxed_cons) => {
// @type iolist :: maybe_improper_list(byte() | binary() | iolist(),
// binary() | []) means that `byte()` isn't allowed
// for `tail`s unlike `head`.
let tail = boxed_cons.tail;
let result_u8: Result<u8, _> = tail.try_into();
match result_u8 {
Ok(_) => {
return Err(TypeError)
.context(format!(
"{} ({}) tail ({}) cannot be a byte",
name, value, tail
))
.map_err(From::from)
}
Err(_) => stack.push(tail),
};
stack.push(boxed_cons.head);
}
TypedTerm::HeapBinary(heap_binary) => {
byte_vec.extend_from_slice(heap_binary.as_bytes());
}
TypedTerm::SubBinary(subbinary) => {
if subbinary.is_binary() {
if subbinary.is_aligned() {
byte_vec.extend(unsafe { subbinary.as_bytes_unchecked() });
} else {
byte_vec.extend(subbinary.full_byte_iter());
}
} else {
return Err(NotABinary)
.context(element_context(name, value, top))
.map_err(From::from);
}
}
TypedTerm::ProcBin(procbin) => {
byte_vec.extend_from_slice(procbin.as_bytes());
}
_ => {
return Err(TypeError)
.context(element_context(name, value, top))
.map_err(From::from)
}
}
}
Ok(process.binary_from_bytes(byte_vec.as_slice()))
}
fn element_context(name: &'static str, value: Term, element: Term) -> String {
format!(
"{} ({}) element ({}) is not a byte, binary, or nested iolist",
name, value, element
)
}
|
#[derive(Clone)]
struct Moon {
pos: [i64; 3],
vel: [i64; 3],
}
impl Moon {
fn new(x: i64, y: i64, z: i64) -> Moon {
Moon { pos: [x, y, z], vel: [0, 0, 0] }
}
fn _print(&self) {
println!(
"pos=<x={}, y={}, z={}>, vel=<x={}, y={}, z={}>",
self.pos[0], self.pos[1], self.pos[2], self.vel[0], self.vel[1], self.vel[2]
);
}
fn adjust_vel(&mut self, om: &Moon) {
for i in 0..3 {
if self.pos[i] != om.pos[i] {
if self.pos[i] > om.pos[i] {
self.vel[i] -= 1;
} else {
self.vel[i] += 1;
}
}
}
}
fn adjust_pos(&mut self) {
for i in 0..3 {
self.pos[i] += self.vel[i];
}
}
fn energy(&self) -> i64 {
let pos_energy: i64 = self.pos.iter().map(|v| if *v < 0 { -*v } else { *v }).sum();
let vel_energy: i64 = self.vel.iter().map(|v| if *v < 0 { -*v } else { *v }).sum();
pos_energy * vel_energy
}
}
pub fn run_puzzle() {
let mut moons = Vec::new();
moons.push(Moon::new(-3, 15, -11));
moons.push(Moon::new(3, 13, -19));
moons.push(Moon::new(-13, 18, -2));
moons.push(Moon::new(6, 0, -1));
for _ in 0..1000 {
// moons.iter().for_each(|m| m.print());
let old_moons = moons.clone();
for m in &mut moons {
for om in &old_moons {
m.adjust_vel(om);
}
}
moons.iter_mut().for_each(|m| m.adjust_pos());
}
let total_energy: i64 = moons.iter().map(|m| m.energy()).sum();
println!("Total energy: {}", total_energy);
}
|
pub use crate::{
object::{
AsObject, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult,
PyWeakRef,
},
vm::{Context, Interpreter, Settings, VirtualMachine},
};
|
#![comment = "Javascript parsing and execution command line tool"]
#![license = "MIT"]
#![crate_type = "bin"]
#![doc(
html_favicon_url = "http://tombebbington.github.io/favicon.png",
html_root_url = "http://tombebbington.github.io/js.rs/"
)]
#![deny(non_uppercase_statics, missing_doc, unnecessary_parens, unrecognized_lint, unreachable_code, unnecessary_allocation, unnecessary_typecast, unnecessary_allocation, uppercase_variables, non_camel_case_types, unused_must_use)]
#![feature(phase)]
//! A Javascript execution command line tool
extern crate js;
extern crate getopts;
extern crate percent_encoding;
//extern crate jit;
extern crate llvm_rs;
#[phase(plugin, link)]
extern crate log;
/// Interactive mode
pub use interactive::Interactive;
/// Unit test mode
pub use tests::Tests;
/// Script runner mode
pub use runner::Runner;
mod interactive;
mod tests;
mod runner;
/// The main function
pub fn main() {
let opts = [
getopts::optflag("h", "help", "Show this message"),
getopts::optflag("t", "tests", "Run tests"),
getopts::optflag("i", "interactive", "Run in interactive mode"),
getopts::optopt("s", "source-code", "Run some Javascript code", "The path to the source code")
];
let m = getopts::getopts(std::os::args().as_slice(), opts).ok().expect("Could not parse arguments");
match m.opt_str("s") {
Some(path) => {
Runner::new(path).run()
},
None if m.opt_present("h") => {
println!("{}", getopts::usage("Usage: js.rs [OPTIONS] [INPUT]", opts));
},
None if m.opt_present("t") || (m.free.len() >= 2 && m.free[1].as_slice() == "test") => {
Tests::new().run();
},
None if m.opt_present("i") || (m.free.len() >= 2 && m.free[1].as_slice() == "interactive") => {
Interactive::new().run();
},
None if m.free.len() >= 2 => {
Runner::new(m.free[1].clone()).run();
},
None => {
println!("{}", getopts::short_usage("Usage: js.rs [OPTIONS] [INPUT]", opts));
}
}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Parser<'a, I, O> {
parse: Box<FnMut(I) -> Result<O, String> + 'a>
}
impl<'a, I: 'a, O: 'a> Parser<'a, I, O> {
fn compose<K: 'a>(mut self, mut rhs: Parser<'a, O, K>) -> Parser<'a, I, K> {
Parser {
parse: Box::new(move |x: I| {
match (self.parse)(x) {
Ok(r) => (rhs.parse)(r),
Err(e) => Err(e)
}
})
}
}
}
fn main() {}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "UI_WindowManagement_Preview")]
pub mod Preview;
#[link(name = "windows")]
extern "system" {}
pub type AppWindow = *mut ::core::ffi::c_void;
pub type AppWindowChangedEventArgs = *mut ::core::ffi::c_void;
pub type AppWindowCloseRequestedEventArgs = *mut ::core::ffi::c_void;
pub type AppWindowClosedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppWindowClosedReason(pub i32);
impl AppWindowClosedReason {
pub const Other: Self = Self(0i32);
pub const AppInitiated: Self = Self(1i32);
pub const UserInitiated: Self = Self(2i32);
}
impl ::core::marker::Copy for AppWindowClosedReason {}
impl ::core::clone::Clone for AppWindowClosedReason {
fn clone(&self) -> Self {
*self
}
}
pub type AppWindowFrame = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppWindowFrameStyle(pub i32);
impl AppWindowFrameStyle {
pub const Default: Self = Self(0i32);
pub const NoFrame: Self = Self(1i32);
}
impl ::core::marker::Copy for AppWindowFrameStyle {}
impl ::core::clone::Clone for AppWindowFrameStyle {
fn clone(&self) -> Self {
*self
}
}
pub type AppWindowPlacement = *mut ::core::ffi::c_void;
pub type AppWindowPresentationConfiguration = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppWindowPresentationKind(pub i32);
impl AppWindowPresentationKind {
pub const Default: Self = Self(0i32);
pub const CompactOverlay: Self = Self(1i32);
pub const FullScreen: Self = Self(2i32);
}
impl ::core::marker::Copy for AppWindowPresentationKind {}
impl ::core::clone::Clone for AppWindowPresentationKind {
fn clone(&self) -> Self {
*self
}
}
pub type AppWindowPresenter = *mut ::core::ffi::c_void;
pub type AppWindowTitleBar = *mut ::core::ffi::c_void;
pub type AppWindowTitleBarOcclusion = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppWindowTitleBarVisibility(pub i32);
impl AppWindowTitleBarVisibility {
pub const Default: Self = Self(0i32);
pub const AlwaysHidden: Self = Self(1i32);
}
impl ::core::marker::Copy for AppWindowTitleBarVisibility {}
impl ::core::clone::Clone for AppWindowTitleBarVisibility {
fn clone(&self) -> Self {
*self
}
}
pub type CompactOverlayPresentationConfiguration = *mut ::core::ffi::c_void;
pub type DefaultPresentationConfiguration = *mut ::core::ffi::c_void;
pub type DisplayRegion = *mut ::core::ffi::c_void;
pub type FullScreenPresentationConfiguration = *mut ::core::ffi::c_void;
pub type WindowingEnvironment = *mut ::core::ffi::c_void;
pub type WindowingEnvironmentAddedEventArgs = *mut ::core::ffi::c_void;
pub type WindowingEnvironmentChangedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct WindowingEnvironmentKind(pub i32);
impl WindowingEnvironmentKind {
pub const Unknown: Self = Self(0i32);
pub const Overlapped: Self = Self(1i32);
pub const Tiled: Self = Self(2i32);
}
impl ::core::marker::Copy for WindowingEnvironmentKind {}
impl ::core::clone::Clone for WindowingEnvironmentKind {
fn clone(&self) -> Self {
*self
}
}
pub type WindowingEnvironmentRemovedEventArgs = *mut ::core::ffi::c_void;
|
use std::io::fs::{mod, PathExtensions};
use std::io;
use std::os;
use std::str;
use cargo::util::process;
use support::paths;
use support::{project, cargo_dir, mkdir_recursive, ProjectBuilder, ResultTest};
fn setup() {
}
/// Add an empty file with executable flags (and platform-dependent suffix).
/// TODO: move this to `ProjectBuilder` if other cases using this emerge.
fn fake_executable(proj: ProjectBuilder, dir: &Path, name: &str) -> ProjectBuilder {
let path = proj.root().join(dir).join(format!("{}{}", name, os::consts::EXE_SUFFIX));
mkdir_recursive(&Path::new(path.dirname())).assert();
fs::File::create(&path).assert();
let io::FileStat{perm, ..} = fs::stat(&path).assert();
fs::chmod(&path, io::OtherExecute | perm).assert();
proj
}
// We can't entirely obliterate PATH because windows needs it for paths to
// things like libgcc, but we want to filter out everything which has a `cargo`
// installation as we don't want it to muck with the --list tests
fn new_path() -> Vec<Path> {
let path = os::getenv_as_bytes("PATH").unwrap_or(Vec::new());
os::split_paths(path).move_iter().filter(|p| {
!p.join(format!("cargo{}", os::consts::EXE_SUFFIX)).exists()
}).collect()
}
test!(list_commands_looks_at_path {
let proj = project("list-non-overlapping");
let proj = fake_executable(proj, &Path::new("path-test"), "cargo-1");
let pr = process(cargo_dir().join("cargo")).cwd(proj.root())
.env("HOME", Some(paths::home()));
let mut path = new_path();
path.push(proj.root().join("path-test"));
let path = os::join_paths(path.as_slice()).unwrap();
let output = pr.arg("-v").arg("--list").env("PATH", Some(path.as_slice()));
let output = output.exec_with_output().assert();
let output = str::from_utf8(output.output.as_slice()).assert();
assert!(output.contains("\n 1\n"), "missing 1: {}", output);
})
|
// Authors: Matthew Bartlett & Arron Harman
// Major: (Software Development & Math) & (Software Development)
// Creation Date: October 27, 2020
// Due Date: November 24, 2020
// Course: CSC328
// Professor Name: Dr. Frye
// Assignment: Chat Server
// Filename: main.rs
// Purpose: Use commands documented in lib.rs to make a chat server
mod lib;
use std::net::*;
use std::sync::*;
use crate::lib::*;
use std::time::Duration;
fn main() {
// Manage the command line args
const USAGE : &str = "cargo run [port number]";
let portnumber = std::env::args().nth(1).unwrap_or("1337".to_string()).parse::<u32>().expect(USAGE); //1337,8008,42069
// start listening for connections
let listener = TcpListener::bind(format!("0.0.0.0:{}",portnumber)).expect("Could not bind to desired port number");
let connections : Arc<Mutex<Vec<(TcpStream,String)>>> = Arc::new(Mutex::new(Vec::new()));
log(&"Server starts".to_string());
// set up signal handler for ^C
{
let connections = connections.clone();
ctrlc::set_handler( move || {
match connections.lock() {
Ok(x) => {
lib::disconnect_all_connections(&x);
}
Err(_) => {}
}
log(&"Server shuting down".to_string());
std::process::exit(0);
}).expect("Error seting Ctrl-C handler");
}
// set up thread to clean mutex every so often
{
let connections = connections.clone();
const SLEEP_CLEAN_TIME : Duration = Duration::from_secs(60); // 1 minute
std::thread::spawn(move || {
std::thread::sleep(SLEEP_CLEAN_TIME);
remove_dead_connections(&connections.lock().unwrap());
});
}
for stream in listener.incoming() {
let stream = Box::new(stream);
let connections = connections.clone();
// spin up thread to handle each client
std::thread::spawn( move || {
//Start
let mut stream = (*stream).unwrap();
let conn_name = match stream.peer_addr().ok() {
Some(x) => {format!("{:?}",x)},
None => "Err_get_addr".to_string()
};
// add stream to mutex
connections.lock().unwrap().push((stream.try_clone().unwrap(),"".to_string()));
// Send HELLO Message
send_message(&mut stream,Message::HELLO, None);
log(&format!("Start connection with {}",conn_name));
// Handle Nick Message
let nick : String = match get_nickname(&mut stream,&connections) {
Some(s) => s,
None => {
// None means that the client wants to disconnect
log(&format!("Ending connection with {}",conn_name));
remove_connection(&mut connections.lock().unwrap(),&stream);
stream.shutdown(Shutdown::Both).expect("Could not shutdown connection");
return ();
}
};
log(&format!("{} has the nickname `{}`",conn_name,nick));
// Wait for messages
while match rcv_message(&mut stream) {
// On CHAT blast it out to all connected users
Some(Message::CHAT(x)) => {
let x = x.trim().to_string().replace('\r',"");
log(&format!("Blast out {}@{}:`{}`",nick,conn_name,x));
blast_out(&connections.lock().unwrap(),&stream.peer_addr().unwrap(),&nick,&x);
true
}
// on BYE exit loop
Some(Message::BYE) => false,
// on Error exit loop
None => false,
// Do not process any other messages, but do loop back
_ => true,
} {}
//End
log(&format!("Ending connection with {}@{}",nick,conn_name));
//remove connection from list of connections in use
remove_connection(&mut connections.lock().unwrap(),&stream);
stream.shutdown(Shutdown::Both).expect("Could not shutdown connection");
});
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use service::Sync15Service;
use bso_record::{Payload, EncryptedBso};
use request::{NormalResponseHandler, UploadInfo};
use util::ServerTimestamp;
use error::{self, ErrorKind, Result};
use key_bundle::KeyBundle;
#[derive(Debug, Clone)]
pub struct RecordChangeset<Payload> {
pub changes: Vec<Payload>,
/// For GETs, the last sync timestamp that should be persisted after
/// applying the records.
/// For POSTs, this is the XIUS timestamp.
pub timestamp: ServerTimestamp,
pub collection: String,
}
pub type IncomingChangeset = RecordChangeset<(Payload, ServerTimestamp)>;
pub type OutgoingChangeset = RecordChangeset<Payload>;
// TODO: use a trait to unify this with the non-json versions
impl<T> RecordChangeset<T> {
#[inline]
pub fn new(
collection: String,
timestamp: ServerTimestamp
) -> RecordChangeset<T> {
RecordChangeset {
changes: vec![],
timestamp,
collection,
}
}
}
impl OutgoingChangeset {
pub fn encrypt(self, key: &KeyBundle) -> Result<Vec<EncryptedBso>> {
let RecordChangeset { changes, collection, .. } = self;
changes.into_iter()
.map(|change| change.into_bso(collection.clone()).encrypt(key))
.collect()
}
pub fn post(self, svc: &Sync15Service, fully_atomic: bool) -> Result<UploadInfo> {
Ok(CollectionUpdate::new_from_changeset(svc, self, fully_atomic)?.upload()?)
}
}
impl IncomingChangeset {
pub fn fetch(
svc: &Sync15Service,
collection: String,
since: ServerTimestamp
) -> Result<IncomingChangeset> {
let records = svc.get_encrypted_records(&collection, since)?;
let mut result = IncomingChangeset::new(collection, svc.last_server_time());
result.changes.reserve(records.len());
let key = svc.key_for_collection(&result.collection)?;
for record in records {
// TODO: if we see a HMAC error, may need to update crypto/keys?
let decrypted = record.decrypt(&key)?;
result.changes.push(decrypted.into_timestamped_payload());
}
Ok(result)
}
}
#[derive(Debug, Clone)]
pub struct CollectionUpdate<'a> {
svc: &'a Sync15Service,
collection: String,
xius: ServerTimestamp,
to_update: Vec<EncryptedBso>,
fully_atomic: bool,
}
impl<'a> CollectionUpdate<'a> {
pub fn new(svc: &'a Sync15Service,
collection: String,
xius: ServerTimestamp,
records: Vec<EncryptedBso>,
fully_atomic: bool) -> CollectionUpdate<'a> {
CollectionUpdate {
svc,
collection,
xius,
to_update: records,
fully_atomic,
}
}
pub fn new_from_changeset(
svc: &'a Sync15Service,
changeset: OutgoingChangeset,
fully_atomic: bool
) -> Result<CollectionUpdate<'a>> {
let collection = changeset.collection.clone();
let key_bundle = svc.key_for_collection(&collection)?;
let xius = changeset.timestamp;
if xius < svc.last_modified_or_zero(&collection) {
// Not actually interrupted, but we know we'd fail the XIUS check.
return Err(ErrorKind::BatchInterrupted.into());
}
let to_update = changeset.encrypt(&key_bundle)?;
Ok(CollectionUpdate::new(svc, collection, xius, to_update, fully_atomic))
}
/// Returns a list of the IDs that failed if allowed_dropped_records is true, otherwise
/// returns an empty vec.
pub fn upload(self) -> error::Result<UploadInfo> {
let mut failed = vec![];
let mut q = self.svc.new_post_queue(&self.collection,
Some(self.xius),
NormalResponseHandler::new(!self.fully_atomic))?;
for record in self.to_update.into_iter() {
let enqueued = q.enqueue(&record)?;
if !enqueued && self.fully_atomic {
return Err(ErrorKind::RecordTooLargeError.into());
}
}
q.flush(true)?;
let mut info = q.completed_upload_info();
info.failed_ids.append(&mut failed);
if self.fully_atomic {
assert_eq!(info.failed_ids.len(), 0,
"Bug: Should have failed by now if we aren't allowing dropped records");
}
Ok(info)
}
}
|
pub mod job;
pub mod skill; |
//! GPIO wired to the LEDs of the Beaglebone
use std::fs::File;
use std::io::{Read, Write, self};
use std::path::PathBuf;
/// LED identifier
#[derive(Clone, Copy)]
pub enum Number {
/// First LED, by default is in heartbeat mode
Zero,
/// Second LED, unused and powered off by default
One,
/// Third LED, tracks CPU usage by default
Three,
/// Fourth LED, tracks disk I/O by default
Two,
}
impl Number {
fn to_str(&self) -> &'static str {
match *self {
Number::Zero => "0",
Number::One => "1",
Number::Two => "2",
Number::Three => "3",
}
}
}
/// LED trigger modes
#[derive(Clone, Copy)]
pub enum Trigger {
Heartbeat,
None,
Timer,
}
impl Trigger {
fn from_str(s: &str) -> Option<Trigger> {
match s {
"heartbeat" => Some(Trigger::Heartbeat),
"none" => Some(Trigger::None),
"timer" => Some(Trigger::Timer),
_ => None,
}
}
fn to_bytes(&self) -> &'static [u8] {
match *self {
Trigger::Heartbeat => b"heartbeat",
Trigger::None => b"none",
Trigger::Timer => b"timer",
}
}
}
/// An LED controller
pub struct Led {
root: PathBuf,
}
impl Led {
/// Create access to an LED
pub fn new(number: Number) -> Led {
// Root folder (modulo number) that contains the files that control the GPIO
const ROOT: &'static str = "/sys/class/leds/beaglebone:green:usr";
Led {
root: PathBuf::from(format!("{}{}", ROOT, number.to_str())),
}
}
/// Makes the LED blink
///
/// # Example
///
/// ``` no_run
/// use bb::led::{Led, Number};
///
/// // On for one second, off for half a second
/// Led::new(Number::Zero).blink(1000, 500);
/// ```
pub fn blink(&self, on_ms: u32, off_ms: u32) -> io::Result<()> {
try!(self.set(Trigger::Timer));
try!(try!(File::create(self.root.join("delay_on"))).write_all(on_ms.to_string().as_bytes()));
try!(File::create(self.root.join("delay_off"))).write_all(off_ms.to_string().as_bytes())
}
/// Changes the brightness of the LED
pub fn set_brightness(&self, brightness: u32) -> io::Result<()> {
try!(File::create(self.root.join("brightness"))).write_all(brightness.to_string().as_bytes())
}
/// Turns on the LED
pub fn set_high(&self) -> io::Result<()> {
try!(self.set(Trigger::None));
self.set_brightness(1)
}
/// Turns off the LED
pub fn set_low(&self) -> io::Result<()> {
try!(self.set(Trigger::None));
self.set_brightness(0)
}
/// Changes the trigger mode of the LED
///
/// # Example
///
/// ``` no_run
/// use bb::led::{Led, Number, Trigger};
///
/// Led::new(Number::Zero).set(Trigger::Heartbeat);
/// println!("I'm alive!");
/// ```
pub fn set(&self, trigger: Trigger) -> io::Result<()> {
try!(File::create(self.root.join("trigger"))).write_all(trigger.to_bytes())
}
/// Returns the current trigger mode the LED is using
pub fn trigger(&self) -> io::Result<Trigger> {
let mut string = String::with_capacity(128);
try!(try!(File::open(self.root.join("trigger"))).read_to_string(&mut string));
match string.split('[').skip(1).next().and_then(|s| s.split(']').next()) {
Some(s) => match Trigger::from_str(s) {
Some(trigger) => Ok(trigger),
None => panic!("Unknown trigger mode: {}", s),
},
None => panic!("Failed to parse: {}", string),
}
}
}
|
use std::io;
fn main(){
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("Failed read line");
let mut num:i32 = input.trim()
.parse()
.expect("Falied convert to i32");
let mut times = 0;
while num != 1 {
if num % 2 == 0 {
num /= 2;
}else{
num = (3*num + 1) / 2;
}
times += 1;
}
println!("{}", times);
} |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::sync::Arc;
use spin::Mutex;
use super::super::super::super::super::kernel::kernel::*;
use super::super::super::super::super::task::*;
use super::super::super::super::mount::*;
use super::super::super::super::inode::*;
use super::super::super::inode::*;
pub fn NewMinAddrData(task: &Task, msrc: &Arc<Mutex<MountSource>>) -> Inode {
let kernel = GetKernel();
let minaddr = format!("{}\n", kernel.platform.MinUserAddress());
return NewStaticProcInode(task,
msrc,
&Arc::new(minaddr.as_bytes().to_vec()))
} |
use proconio::input;
fn main() {
input! {
n: u64,
m: u64,
};
const M: u64 = 998244353;
let mut same = m;
let mut differ = 0;
for _ in 1..n {
let same_ = differ;
let differ_ = same * (m - 1) % M + differ * (m - 2) % M;
same = same_;
differ = differ_;
}
println!("{}", differ % M);
}
|
use petgraph_drawing::{Drawing, DrawingIndex};
pub fn aspect_ratio<N>(drawing: &Drawing<N, f32>) -> f32
where
N: DrawingIndex,
{
let n = drawing.len();
let mut cx = 0.;
let mut cy = 0.;
for i in 0..n {
let xi = drawing.coordinates[[i, 0]];
let yi = drawing.coordinates[[i, 1]];
cx += xi;
cy += yi;
}
cx /= n as f32;
cy /= n as f32;
let mut xx = 0.;
let mut xy = 0.;
let mut yy = 0.;
for i in 0..n {
let xi = drawing.coordinates[[i, 0]] - cx;
let yi = drawing.coordinates[[i, 1]] - cy;
xx += xi * xi;
xy += xi * yi;
yy += yi * yi;
}
let tr = xx + yy;
let det = xx * yy - xy * xy;
let sigma1 = ((tr + (tr * tr - 4. * det).sqrt()) / 2.).sqrt();
let sigma2 = ((tr - (tr * tr - 4. * det).sqrt()) / 2.).sqrt();
sigma2 / sigma1
}
|
pub fn frexp(x: f64) -> (f64, i32) {
let mut y = x.to_bits();
let ee = ((y >> 52) & 0x7ff) as i32;
if ee == 0 {
if x != 0.0 {
let x1p64 = f64::from_bits(0x43f0000000000000);
let (x, e) = frexp(x * x1p64);
return (x, e - 64);
}
return (x, 0);
} else if ee == 0x7ff {
return (x, 0);
}
let e = ee - 0x3fe;
y &= 0x800fffffffffffff;
y |= 0x3fe0000000000000;
return (f64::from_bits(y), e);
}
|
#[cfg(feature = "async")]
use super::{async_first_auth_request, async_second_auth_request};
#[cfg(feature = "sync")]
use super::{sync_first_auth_request, sync_second_auth_request};
use super::{Authenticator, FirstAuthResponse, ScramPbkdf2Sha256, ScramSha256};
use crate::conn::ConnectionCore;
use crate::hdb_error::{HdbError, HdbResult};
use crate::protocol::parts::DbConnectInfo;
#[must_use]
pub(crate) enum AuthenticationResult {
Ok,
Redirect(DbConnectInfo),
}
// Do the authentication.
//
// Manages a list of supported authenticators.
// So far we only support two; if more are implemented, the password might
// become optional; if then the password is not given, the pw-related
// authenticators mut not be added to the list.
#[cfg(feature = "sync")]
pub(crate) fn sync_authenticate(
conn_core: &mut ConnectionCore,
reconnect: bool,
) -> HdbResult<AuthenticationResult> {
trace!("authenticate()");
// Propose some authenticators...
let authenticators: [Box<dyn Authenticator + Send + Sync>; 2] = [
// Cookie, Gss, Saml, SapLogon, Jwt, Ldap,
ScramSha256::boxed_authenticator(),
ScramPbkdf2Sha256::boxed_authenticator(),
];
// ...with the first request.
match sync_first_auth_request(conn_core, &authenticators)? {
FirstAuthResponse::AuthenticatorAndChallenge(selected, server_challenge) => {
// Find the selected authenticator ...
let mut authenticator: Box<dyn Authenticator + Send + Sync> = authenticators
.into_iter()
.find(|authenticator| authenticator.name() == selected)
.ok_or_else(|| {
HdbError::Impl("None of the available authenticators was accepted")
})?;
// ...and use it for the second request
sync_second_auth_request(conn_core, &mut *authenticator, &server_challenge, reconnect)?;
conn_core.set_authenticated();
trace!("session_id: {}", conn_core.session_id());
Ok(AuthenticationResult::Ok)
}
FirstAuthResponse::RedirectInfo(db_connect_info) => {
Ok(AuthenticationResult::Redirect(db_connect_info))
}
}
}
#[cfg(feature = "async")]
pub(crate) async fn async_authenticate(
conn_core: &mut ConnectionCore,
reconnect: bool,
) -> HdbResult<AuthenticationResult> {
trace!("authenticate()");
// Propose some authenticators...
let authenticators: [Box<dyn Authenticator + Send + Sync>; 2] = [
// Cookie, Gss, Saml, SapLogon, Jwt, Ldap,
ScramSha256::boxed_authenticator(),
ScramPbkdf2Sha256::boxed_authenticator(),
];
// ...with the first request.
match async_first_auth_request(conn_core, &authenticators).await? {
FirstAuthResponse::AuthenticatorAndChallenge(selected, server_challenge) => {
// Find the selected authenticator ...
let mut authenticator: Box<dyn Authenticator + Send + Sync> = authenticators
.into_iter()
.find(|authenticator| authenticator.name() == selected)
.ok_or_else(|| {
HdbError::Impl("None of the available authenticators was accepted")
})?;
// ...and use it for the second request
async_second_auth_request(conn_core, &mut *authenticator, &server_challenge, reconnect)
.await?;
conn_core.set_authenticated();
trace!("session_id: {}", conn_core.session_id());
Ok(AuthenticationResult::Ok)
}
FirstAuthResponse::RedirectInfo(db_connect_info) => {
Ok(AuthenticationResult::Redirect(db_connect_info))
}
}
}
|
//! Query routing. More docs to come...
#![warn(
missing_docs,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused_qualifications
)]
#![warn(clippy::all, clippy::pedantic)]
#![allow(
clippy::module_name_repetitions,
clippy::default_trait_access,
clippy::cast_precision_loss
)]
use rand::distributions::Distribution;
/// This distribution produces values between 0 and `N - 1` by requesting the `next_u32` from the
/// random number generator and applying `mod N` operation on it.
///
/// This is meant for testing, e.g., together with `rand::rngs::mock::StepRng` it can produce
/// predictable values that can be used in unit tests.
pub struct WrappingEchoDistribution<T> {
size: T,
}
impl<T> WrappingEchoDistribution<T> {
/// Constructs a new distribution generating values between 0 and `size - 1`.
pub fn new(size: T) -> Self {
Self { size }
}
}
impl<T> Distribution<T> for WrappingEchoDistribution<T>
where
T: std::convert::TryFrom<u32> + std::ops::Rem<T, Output = T> + Copy,
<T as std::convert::TryFrom<u32>>::Error: std::fmt::Debug,
{
fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> T {
T::try_from(rng.next_u32()).unwrap() % self.size
}
}
/// A wrapper over a distribution generating integer values that casts them to floats.
pub struct ToFloatDistribution<D>(D);
impl<D> ToFloatDistribution<D> {
/// Constructs a float distribution from an integer one.
pub fn new(dist: D) -> Self {
Self(dist)
}
}
impl<D> Distribution<f32> for ToFloatDistribution<D>
where
D: Distribution<u64>,
{
fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> f32 {
self.0.sample(rng) as f32
}
}
|
// 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.
//! qmi-snoop is used for snooping Qmi messages sent/received by transport driver
use {
failure::{Error, ResultExt},
fidl::endpoints::ServerEnd,
fidl_fuchsia_telephony_snoop::{
Message as SnoopMessage, PublisherMarker as QmiSnoopMarker,
PublisherRequest as QmiSnoopRequest, PublisherRequestStream as QmiSnoopRequestStream,
},
fuchsia_async as fasync, futures,
futures::stream::TryStreamExt,
qmi,
std::fs::File,
std::path::PathBuf,
structopt::StructOpt,
};
#[derive(StructOpt, Debug)]
#[structopt(name = "qmi-snoop")]
struct Opt {
/// Device path (e.g. /dev/class/qmi-transport/000)
#[structopt(short = "d", long = "device", parse(from_os_str))]
device: Option<PathBuf>,
}
pub fn main() -> Result<(), Error> {
let mut exec = fasync::Executor::new().context("error creating event loop")?;
let args = Opt::from_args();
let device = match args.device {
Some(device_path) => device_path,
None => PathBuf::from("/dev/class/qmi-transport/000"),
};
let fut = async move {
eprintln!("Connecting with exclusive access to {}..", device.display());
let file: File = File::open(device)?;
let snoop_endpoint_server_side: ServerEnd<QmiSnoopMarker> =
qmi::connect_snoop_channel(&file).await?;
let mut request_stream: QmiSnoopRequestStream = snoop_endpoint_server_side.into_stream()?;
while let Ok(Some(QmiSnoopRequest::SendMessage { msg, control_handle: _ })) =
request_stream.try_next().await
{
let qmi_message = match msg {
SnoopMessage::QmiMessage(m) => Some(m),
};
match qmi_message {
Some(message) => {
let slice = &message.opaque_bytes;
eprint!(
"Received msg direction: {:?}, timestamp: {}, msg:",
message.direction, message.timestamp
);
for element in slice.iter() {
eprint!(" {}", element);
}
eprint!("\n");
}
None => {}
}
}
eprintln!("unexpected msg received");
Ok::<_, Error>(())
};
exec.run_singlethreaded(fut)
}
|
use std::env;
use substrate_subxt::{sp_core::sr25519, IndracoreNodeRuntime, PairSigner};
pub type Sr25519 = PairSigner<IndracoreNodeRuntime, sr25519::Pair>;
pub type Client = substrate_subxt::Client<IndracoreNodeRuntime>;
pub type IndracoreId = pallet_indices::address::Address<sp_core::crypto::AccountId32, u32>;
pub fn url() -> String {
dotenv::dotenv().expect("!!! Failed to read .env file");
let url = env::var("RPC");
url.unwrap_or("ws://127.0.0.1:9944".to_string())
}
pub fn decimal() -> u32 {
dotenv::dotenv().expect("!!! Failed to read .env file");
let decimal = std::env::var("DECIMAL").unwrap();
decimal.parse::<u32>().unwrap_or(15)
}
pub fn token_type() -> String {
dotenv::dotenv().expect("!!! Failed to read .env file");
let token = env::var("TOKEN");
token.unwrap_or("unit".into())
}
pub struct Token {
pub token: f64,
}
impl Token {
pub fn get(token: String) -> Token {
Token {
token: token.parse::<f64>().unwrap(),
}
}
pub fn pay(&self) -> u128 {
let decimal = 10u128.pow(decimal() - 9);
let amount = (self.token * 1_000_000_000.0) as u128;
amount * decimal
}
pub fn token(&self) -> f64 {
self.token
}
pub fn uamount(amount: u128) -> u128 {
amount.checked_div(10u128.pow(decimal())).unwrap()
}
pub fn famount(amount: u128) -> f64 {
amount as f64 / 10u128.pow(decimal()) as f64
}
}
|
use actix_web::{
web, HttpResponse,
};
use serde::Deserialize;
use chrono::NaiveDateTime;
use diesel::PgConnection;
use diesel::r2d2::ConnectionManager;
use crate::server::errors::Result;
use super::db::{
LoggingLevel,
LogNote,
NewLogNote
};
use std::str::FromStr;
pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
pub fn logs_routes(cfg: &mut web::ServiceConfig) {
cfg.service(web::scope("/logs")
.route("", web::get().to(get_logs))
.route("/range", web::get().to(get_logs_range))
.route("", web::post().to(create_log))
);
}
pub async fn get_logs(
conn: web::Data<DbPool>,
) -> Result<HttpResponse> {
let conn = conn.get()?;
let data = LogNote::get(&conn).await?;
Ok(HttpResponse::Ok().json(data))
}
#[derive(Deserialize)]
pub struct GetLogsRange {
pub from_time: String,
pub to_time: String,
pub logging_level: String,
}
pub async fn get_logs_range(
form: web::Query<GetLogsRange>,
conn: web::Data<DbPool>,
) -> Result<HttpResponse> {
let conn = conn.get()?;
let data = LogNote::get_range(
NaiveDateTime::parse_from_str(&form.from_time, "%Y-%m-%dT%H:%M:%S%.f")?,
NaiveDateTime::parse_from_str(&form.to_time, "%Y-%m-%dT%H:%M:%S%.f")?,
LoggingLevel::from_str(&form.logging_level)?,
&conn
)
.await?;
Ok(HttpResponse::Ok().json(data))
}
pub async fn create_log(
form: web::Json<NewLogNote>,
conn: web::Data<DbPool>,
) -> Result<HttpResponse> {
let conn = conn.get()?;
let form = form.into_inner();
LogNote::new(&form, &conn).await?;
Ok(HttpResponse::Ok().json(""))
} |
use decisionengine::datasource::deserialize_input_node;
use decisionengine::datasource::DecisionDataset;
extern crate serde_json;
use serde_json::Value;
use decisionengine::operations::*;
#[derive(Clone, PartialEq)]
pub enum NodeResult {
Numeric(i32),
Boolean(bool),
Text(String),
Array(Vec<NodeResult>),
Err(String),
}
pub trait EvalNode {
fn eval(&mut self, input: &mut DecisionDataset) -> NodeResult;
}
struct ConstantRootNode {
value: NodeResult,
}
impl EvalNode for ConstantRootNode {
fn eval(&mut self, _: &mut DecisionDataset) -> NodeResult {
match &self.value {
&NodeResult::Boolean(b) => NodeResult::Boolean(b),
&NodeResult::Numeric(n) => NodeResult::Numeric(n),
&NodeResult::Text(ref s) => NodeResult::Text(s.clone()),
&NodeResult::Array(ref a) => NodeResult::Array(a.clone()),
NodeResult::Err(msg) => NodeResult::Err(msg.clone()),
}
}
}
struct BinOpNode {
lvalue: Box<EvalNode>,
rvalue: Box<EvalNode>,
operation: Box<BinaryOperation>,
}
impl EvalNode for BinOpNode {
fn eval(&mut self, input: &mut DecisionDataset) -> NodeResult {
self.operation
.eval(&mut self.lvalue, &mut self.rvalue, input)
}
}
pub fn deserialize_node(v: &Value) -> (Box<EvalNode>, bool) {
let node_type = v["type"].as_str().unwrap();
if node_type == "constant" {
deserialize_const_node(v)
} else if node_type == "input" {
deserialize_input_node(v["value"].as_str().unwrap())
} else {
match v["type"].as_str().unwrap() {
"op" => match v["op"].as_str().unwrap() {
"pow" => deserialize_bin_op_node(v, Box::new(PowerOperation {})),
">=" => deserialize_bin_op_node(v, Box::new(GreaterThanOrEqualsOperation {})),
"<=" => deserialize_bin_op_node(v, Box::new(LessThanOrEqualsOperation {})),
"&&" => deserialize_bin_op_node(v, Box::new(AndOperation {})),
"+" => deserialize_bin_op_node(v, Box::new(AdditionOperation {})),
"==" => deserialize_bin_op_node(v, Box::new(EqualsOperation {})),
"array_contains" => deserialize_bin_op_node(v, Box::new(ArrayContainsOperation {})),
"regex_contains" => deserialize_bin_op_node(v, Box::new(RegexContainsOperation {})),
_ => panic!(format!(
"Cannot deserialize: unknown operation {}",
v["op"].to_string()
)),
},
_ => panic!(format!(
"Cannot deserialize node type: {}",
v["type"].to_string()
)),
}
}
}
fn deserialize_bin_op_node(v: &Value, op: Box<BinaryOperation>) -> (Box<EvalNode>, bool) {
let (mut lvalue, lconst) = deserialize_node(&v["lvalue"]);
let (mut rvalue, rconst) = deserialize_node(&v["rvalue"]);
if lconst && rconst {
(
Box::new(ConstantRootNode {
value: op.eval(&mut lvalue, &mut rvalue, &mut DecisionDataset::get_empty()),
}),
true,
)
} else {
(
Box::new(BinOpNode {
lvalue: lvalue,
rvalue: rvalue,
operation: op,
}),
false,
)
}
}
fn deserialize_const_node_value(v: &Value) -> NodeResult {
if v.is_array() {
let array_value: Vec<NodeResult> = v.as_array()
.unwrap()
.iter()
.map(|v| deserialize_const_node_value(v))
.collect();
return NodeResult::Array(array_value);
}
if v.is_boolean() {
return NodeResult::Boolean(v.as_bool().unwrap());
}
if v.is_string() {
return NodeResult::Text(v.as_str().unwrap().to_string());
}
if v.is_i64() {
return NodeResult::Numeric(v.as_i64().unwrap() as i32);
}
panic!(format!(
"Can't deserialize constant input: {}",
v.to_string()
));
}
fn deserialize_const_node(v: &Value) -> (Box<EvalNode>, bool) {
let root = ConstantRootNode {
value: deserialize_const_node_value(&v["value"]),
};
(Box::new(root), true)
}
|
fn main() {
let s = "hello world";
println!("{}", s.contains("world"));
} |
use anyhow::{bail, Context};
use std::collections::{HashMap, HashSet, VecDeque};
const INPUT: &str = include_str!("input.txt");
fn parse_orbits(input: &str) -> anyhow::Result<HashMap<&str, &str>> {
input
.lines()
.filter(|line| !line.is_empty())
.map(|line| {
let mut parts = line.split(')');
let center = parts.next().context("missing center")?;
let satellite = parts.next().context("missing satellite")?;
Ok((satellite, center))
})
.collect()
}
fn part1(orbits: &HashMap<&str, &str>) -> usize {
fn count_orbits(orbits: &HashMap<&str, &str>, object: &str) -> usize {
match orbits.get(object) {
Some(center) => 1 + count_orbits(orbits, center),
None => 0,
}
}
orbits
.keys()
.map(|object| count_orbits(orbits, object))
.sum()
}
fn part2(orbits: &HashMap<&str, &str>) -> anyhow::Result<usize> {
let mut queue = VecDeque::new();
let mut visited = HashSet::with_capacity(orbits.len());
queue.push_back((0, "YOU"));
while let Some((dist, object)) = queue.pop_front() {
if object == "SAN" {
return Ok(dist - 2);
}
if !visited.insert(object) {
continue;
}
if let Some(center) = orbits.get(object) {
queue.push_back((dist + 1, center));
}
for (satellite, _) in orbits.iter().filter(|(_, &v)| v == object) {
queue.push_back((dist + 1, satellite));
}
}
bail!("no path found");
}
fn main() -> anyhow::Result<()> {
let orbits = parse_orbits(INPUT)?;
println!("part 1: {}", part1(&orbits));
println!("part 2: {}", part2(&orbits)?);
Ok(())
}
|
use error::CompileError;
use lalrpop_util::ParseError;
use minijava::ast::Prg;
use minijava::lalrparser::PrgParser;
use minijava::lexer::Error;
use minijava::lexer::ErrorCode::*;
use minijava::lexer::Tokenizer;
extern crate term;
pub fn parse_prg(source: &str) -> Result<Prg, CompileError> {
let source_tokenizer = Tokenizer::new(source, 0);
PrgParser::new()
.parse(source, source_tokenizer)
.map_err(|e| match e {
ParseError::InvalidToken { location } => {
let msg = format!("Parse error: {:?}", e);
CompileError::new_with_context(source, location, location + 1, &msg)
}
ParseError::UnrecognizedToken {
token: Some((l1, _, l2)),
expected,
} => {
let mut msg = "Invalid token, expected ".to_owned();
let mut sep = "";
for tok in expected {
msg = format!("{}{}{}", msg, sep, tok);
sep = " or ";
}
msg = format!("{}.", msg);
CompileError::new_with_context(source, l1, l2, &msg)
}
ParseError::User {
error: Error { location, code },
} => {
let msg = match code {
UnrecognizedToken => "Unknown symbol",
UnterminatedStringLiteral => "Non-terminated string",
};
CompileError::new_with_context(source, location, location + 1, &msg)
}
_ => CompileError::new(&format!("Parse error: {:?}", e)),
})
}
|
pub type TableId = i32;
#[macro_export]
macro_rules! impl_table_mut {
($ty:ty, $id:ty) => {
use crate::db::Database;
use crate::error::{Error, Result};
impl $ty {
pub fn insert(&self, conn: &Database) -> Result<Self> {
diesel::insert_into(table).values(self).execute(&**conn)?;
table
.order(table_mod::id.desc())
.first(&**conn)
.map_err(|e| e.into())
}
pub fn get(conn: &Database, id: $id) -> Result<Self> {
table.find(id).first(&**conn).map_err(|e| e.into())
}
pub fn get_all(conn: &Database) -> Result<Vec<Self>> {
table
.order(table_mod::id)
.load(&**conn)
.map_err(|e| e.into())
}
pub fn update(&self, conn: &Database) -> Result<()> {
match self.id {
Some(id) => {
diesel::update(table.find(id)).set(self).execute(&**conn)?;
Ok(())
}
None => Err(Error::RequireAKey),
}
}
pub fn delete(conn: &Database, id: $id) -> Result<()> {
diesel::delete(table.find(id)).execute(&**conn)?;
Ok(())
}
}
};
}
|
// 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 lazy_static::lazy_static;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use x86_64::structures::tss::TaskStateSegment;
use x86_64::VirtAddr;
//use crate::println;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
lazy_static! {
static ref TSS: TaskStateSegment = {
let mut tss = TaskStateSegment::new();
let stack = {
const STACK_SIZE: usize = 4096;
static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE];
let stack_start = VirtAddr::from_ptr(unsafe { &STACK });
let stack_end = stack_start + STACK_SIZE;
stack_end
};
tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = stack;
tss
};
}
lazy_static! {
static ref GDT: (GlobalDescriptorTable, Selectors) = {
let mut gdt = GlobalDescriptorTable::new();
let code_selector = gdt.add_entry(Descriptor::kernel_code_segment());
//let data_selector = gdt.add_entry(Descriptor::kernel_code_segment());
let tss_selector = gdt.add_entry(Descriptor::tss_segment(&TSS));
(
gdt,
Selectors {
code_selector,
//data_selector,
tss_selector,
},
)
};
}
struct Selectors {
code_selector: SegmentSelector,
//data_selector: SegmentSelector,
tss_selector: SegmentSelector,
}
pub fn init() {
//use x86_64::instructions::segmentation::set_cs;
//use x86_64::instructions::tables::load_tss;
let gdtAddr: u64 = &GDT.0 as *const _ as u64;
let limit = (64 - 1) as u16; // 8 * 8
info!("the gdt is {:?}", GDT.0);
info!("the gdtAddr is {:x}, the limit is {:x}", gdtAddr, limit);
info!("the code_selector is {:?}, the ts_selector is {:?}",
GDT.1.code_selector, GDT.1.tss_selector);
//GDT.0.load();
//super::Kernel::Kernel::LoadGDT(gdtAddr, limit);
info!("after loadgdt");
/*unsafe {
//set_cs(GDT.1.code_selector);
//load_tss(GDT.1.tss_selector);
info!("start load ds");
//x86_64::instructions::segmentation::load_ds(GDT.1.data_selector);
//x86_64::instructions::segmentation::load_ss(GDT.1.data_selector);
//x86_64::instructions::segmentation::load_es(GDT.1.data_selector);
//x86_64::instructions::segmentation::load_fs(GDT.1.data_selector);
//x86_64::instructions::segmentation::load_gs(GDT.1.data_selector);
}*/
}
|
use derive_more::From;
use rand::Rng;
use std::{
borrow::Cow,
cmp::{self, Ordering},
fmt::{self, Debug, Display, Formatter},
intrinsics,
};
#[derive(Clone, Debug)]
pub struct SymbolTable {
symbols: Vec<String>,
}
impl SymbolTable {
pub fn get(&self, id: SymbolId) -> &str {
&self.symbols[id.0]
}
pub fn find_or_add(&mut self, symbol: impl Into<Cow<str>>) -> SymbolId {
let symbol: Cow<str> = symbol.into();
if let Some(index) = self.symbols.iter().position(|it| it == symbol.as_ref()) {
return SymbolId(index);
}
let id = SymbolId(self.symbols.len());
self.symbols.push(symbol.into_owned());
id
}
pub fn symbols(&self) -> &[String] {
&self.symbols
}
pub fn ids_and_symbols(&self) -> impl Iterator<Item = (SymbolId, &str)> {
self.symbols
.iter()
.enumerate()
.map(|(index, it)| (SymbolId(index), it.as_str()))
}
pub fn choose(&self, rng: &mut impl Rng) -> SymbolId {
SymbolId(rng.gen_range(0..self.symbols.len()))
}
}
impl AsRef<[String]> for SymbolTable {
fn as_ref(&self) -> &[String] {
&self.symbols
}
}
impl Default for SymbolTable {
fn default() -> Self {
// These symbols must be kept in sync with the `SymbolId` constants.
Self {
symbols: vec![
"Builtin".to_string(),
"Equal".to_string(),
"Error".to_string(),
"False".to_string(),
"Function".to_string(),
"Greater".to_string(),
"Int".to_string(),
"Less".to_string(),
"List".to_string(),
"Main".to_string(),
"Nothing".to_string(),
"Ok".to_string(),
"ReceivePort".to_string(),
"ReturnChannel".to_string(),
"SendPort".to_string(),
"Stdin".to_string(),
"Stdout".to_string(),
"Struct".to_string(),
"Tag".to_string(),
"Text".to_string(),
"True".to_string(),
],
}
}
}
#[derive(Copy, Clone, Eq, From, Hash, Ord, PartialEq, PartialOrd)]
pub struct SymbolId(usize);
impl SymbolId {
// These symbols are created by built-in functions or used for starting the
// program (main and environment keys). They have a fixed ID so that they
// can be used in the VM without lookups.
//
// Sorted alphabetically and must be kept in sync with
// `SymbolTable::default()`.
pub const BUILTIN: SymbolId = SymbolId(0);
pub const EQUAL: SymbolId = SymbolId(1);
pub const ERROR: SymbolId = SymbolId(2);
pub const FALSE: SymbolId = SymbolId(3);
pub const FUNCTION: SymbolId = SymbolId(4);
pub const GREATER: SymbolId = SymbolId(5);
pub const INT: SymbolId = SymbolId(6);
pub const LESS: SymbolId = SymbolId(7);
pub const LIST: SymbolId = SymbolId(8);
pub const MAIN: SymbolId = SymbolId(9);
pub const NOTHING: SymbolId = SymbolId(10);
pub const OK: SymbolId = SymbolId(11);
pub const RECEIVE_PORT: SymbolId = SymbolId(12);
pub const RETURN_CHANNEL: SymbolId = SymbolId(13);
pub const SEND_PORT: SymbolId = SymbolId(14);
pub const STDIN: SymbolId = SymbolId(15);
pub const STDOUT: SymbolId = SymbolId(16);
pub const STRUCT: SymbolId = SymbolId(17);
pub const TAG: SymbolId = SymbolId(18);
pub const TEXT: SymbolId = SymbolId(19);
pub const TRUE: SymbolId = SymbolId(20);
pub fn value(self) -> usize {
self.0
}
}
impl Debug for SymbolId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "<symbol-id {}>", self.0)
}
}
impl DisplayWithSymbolTable for SymbolId {
fn fmt(&self, f: &mut Formatter, symbol_table: &SymbolTable) -> fmt::Result {
write!(f, "{}", symbol_table.get(*self))
}
}
pub trait DisplayWithSymbolTable {
fn to_string(&self, symbol_table: &SymbolTable) -> String {
let mut buffer = String::new();
let mut formatter = fmt::Formatter::new(&mut buffer);
self.fmt(&mut formatter, symbol_table).unwrap();
buffer
}
fn fmt(&self, f: &mut Formatter, symbol_table: &SymbolTable) -> fmt::Result;
}
impl<T: Display> DisplayWithSymbolTable for T {
fn fmt(&self, f: &mut Formatter, _symbol_table: &SymbolTable) -> fmt::Result {
Display::fmt(&self, f)
}
}
pub trait OrdWithSymbolTable {
fn cmp(&self, symbol_table: &SymbolTable, other: &Self) -> Ordering;
}
impl<T: OrdWithSymbolTable> OrdWithSymbolTable for Option<T> {
fn cmp(&self, symbol_table: &SymbolTable, other: &Self) -> Ordering {
match (self, other) {
(Option::None, Option::None) => Ordering::Equal,
(Option::Some(this), Option::Some(other)) => this.cmp(symbol_table, other),
_ => intrinsics::discriminant_value(self).cmp(&intrinsics::discriminant_value(other)),
}
}
}
impl<T0: OrdWithSymbolTable, T1: OrdWithSymbolTable> OrdWithSymbolTable for (T0, T1) {
fn cmp(&self, symbol_table: &SymbolTable, other: &Self) -> Ordering {
self.0
.cmp(symbol_table, &other.0)
.then_with(|| self.1.cmp(symbol_table, &other.1))
}
}
impl<T: OrdWithSymbolTable> OrdWithSymbolTable for [T] {
fn cmp(&self, symbol_table: &SymbolTable, other: &Self) -> Ordering {
let l = cmp::min(self.len(), other.len());
// Slice to the loop iteration range to enable bound check
// elimination in the compiler
let lhs = &self[..l];
let rhs = &other[..l];
for i in 0..l {
match lhs[i].cmp(symbol_table, &rhs[i]) {
Ordering::Equal => (),
non_eq => return non_eq,
}
}
self.len().cmp(&other.len())
}
}
macro_rules! impl_ord_with_symbol_table_via_ord {
($type:ty) => {
impl crate::heap::OrdWithSymbolTable for $type {
fn cmp(
&self,
_symbol_table: &crate::heap::SymbolTable,
other: &Self,
) -> std::cmp::Ordering {
Ord::cmp(self, other)
}
}
};
}
pub(crate) use impl_ord_with_symbol_table_via_ord;
|
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 t = scan!(usize);
for _ in 0..t {
let (h, w) = scan!((usize, usize));
let s = scan!(String);
solve(h, w, s);
}
}
fn solve(h: usize, w: usize, s: String) {
let s: Vec<char> = s.chars().collect();
let row_ok = |n: usize| -> Option<usize> {
let mut top = 1;
let mut bottom = h;
for &ch in s.iter().take(n).rev() {
if ch == 'D' {
if bottom == 1 {
return None;
}
top = 1.max(top - 1);
bottom -= 1;
} else if ch == 'U' {
if top == h {
return None;
}
top += 1;
bottom = h.min(bottom + 1);
}
}
assert!(top <= bottom);
Some(top)
};
let col_ok = |n: usize| -> Option<usize> {
let mut left = 1;
let mut right = w;
for &ch in s.iter().take(n).rev() {
if ch == 'R' {
if right == 1 {
return None;
}
left = 1.max(left - 1);
right -= 1;
} else if ch == 'L' {
if left == w {
return None;
}
left += 1;
right = w.min(right + 1);
}
}
assert!(left <= right);
Some(left)
};
let mut ok = 0;
let mut ng = s.len() + 1;
let mut ans = (1, 1);
while ng - ok > 1 {
let mid = (ok + ng) / 2;
let r = row_ok(mid);
let c = col_ok(mid);
match (r, c) {
(Some(r), Some(c)) => {
ok = mid;
ans = (r, c);
}
_ => {
ng = mid;
}
}
}
dbg!(ok);
println!("{} {}", ans.0, ans.1);
}
|
use crate::RawDataRead;
use std::io::{Read, Result as IOResult};
use std::ffi::CStr;
pub struct TextureStringData {
pub data: Box<[u8]>
}
impl TextureStringData {
pub fn read(read: &mut dyn Read, length: u32) -> IOResult<Self> {
let data = read.read_data(length as usize)?;
Ok(Self {
data
})
}
pub fn get_string_at(&self, offset: u32) -> &CStr {
let offset_data = &self.data[offset as usize .. ];
let mut counter = 0usize;
for char in offset_data {
counter += 1;
if *char == 0 {
break;
}
}
return unsafe { CStr::from_bytes_with_nul_unchecked(&offset_data[.. counter as usize]) };
}
}
|
#[cfg(test)]
mod tests {
use actix_session::CookieSession;
use actix_web::web;
use actix_web::{http::StatusCode, test, App};
use serde_json::json;
use crate::api;
use crate::sql::store::user_repository::user::UserData;
#[actix_rt::test]
async fn test_user() {
crate::sql::tests::init();
let mut app = test::init_service(
App::new().service(
web::scope("/api-v2")
.wrap(CookieSession::signed(&[0; 32]).secure(false))
.configure(api::routes::public)
.configure(api::routes::private),
),
)
.await;
/*
* РЕГЕСТРИРУЮ НОВОГО ТЕСТОВОГО ПОЛЬЗОВАТЕЛЯ
*/
let request_body = json!({
"chat_id": 11,
"role": 1,
});
let resp = test::TestRequest::post()
.uri("/api-v2/registration")
.set_json(&request_body)
.send_request(&mut app)
.await;
assert_eq!(resp.status().as_u16(), StatusCode::CREATED);
/*
* РЕГЕСТРИРУЮ ТЕСТОВОГО АДМИНА
*/
let request_body = json!({
"chat_id": 10,
"role": 2,
});
let resp = test::TestRequest::post()
.uri("/api-v2/registration")
.set_json(&request_body)
.send_request(&mut app)
.await;
assert_eq!(resp.status().as_u16(), StatusCode::CREATED);
// Разбираю json на структуру
let user: UserData = test::read_body_json(resp).await;
/*
* ПЫТАЮСЬ АВТОРИЗОВАТЬСЯ АДМИНОМ
*/
let resp = test::TestRequest::post()
.uri(&format!("/api-v2/auth/{}", user.chat_id))
.set_json(&request_body)
.send_request(&mut app)
.await;
assert_eq!(resp.status().as_u16(), StatusCode::OK);
// Тестирую получение информации пользователя о себе
let resp_get_user = test::TestRequest::get()
.cookie(resp.response().cookies().next().unwrap())
.uri(&format!("/api-v2/user/{}", user.chat_id))
.send_request(&mut app)
.await;
assert_eq!(resp_get_user.status().as_u16(), StatusCode::OK);
let auth_resp = &resp;
/*
* ТЕСТИРОВАНИЕ ОБНОВЛЕНИЯ РОЛИ ДЛЯ ВТОРОГО ТЕСТОВОГО ПОЛЬЗОВАТЕЛЯ
*/
let request_body = json!({
"chat_id": 11,
"role": 2,
});
let resp = test::TestRequest::put()
.cookie(auth_resp.response().cookies().next().unwrap())
.set_json(&request_body)
.uri(&format!("/api-v2/user/{}", user.chat_id))
.send_request(&mut app)
.await;
assert_eq!(resp.status().as_u16(), StatusCode::OK);
let updated_user: UserData = test::read_body_json(resp).await;
assert_eq!(updated_user.role, 2);
/*
* ТЕСТИРОВАНИЕ УДАЛЕНИЯ ВТОРОГО ТЕСТОВОГО ПОЛЬЗОВАТЕЛЯ
*/
let request_body = json!({
"chat_id": 10,
});
let resp = test::TestRequest::delete()
.cookie(auth_resp.response().cookies().next().unwrap())
.set_json(&request_body)
.uri(&format!("/api-v2/user/{}", user.chat_id))
.send_request(&mut app)
.await;
assert_eq!(resp.status().as_u16(), StatusCode::OK);
}
}
|
use std::default::Default;
use std::f64;
pub struct GameObject {
pub pos: [f64; 2],
pub vel: [f64; 2],
pub size: [f64; 2],
}
impl GameObject {
pub fn intersects(&self, other: &GameObject) -> bool {
self.pos[0] - self.size[0]/2.0 < other.pos[0] + other.size[0]/2.0 &&
self.pos[0] + self.size[0]/2.0 > other.pos[0] - other.size[0]/2.0 &&
self.pos[1] - self.size[1]/2.0 < other.pos[1] + other.size[1]/2.0 &&
self.pos[1] + self.size[1]/2.0 > other.pos[1] - other.size[1]/2.0
}
pub fn collision_normal(&self, other: &GameObject) -> Option<[f64; 2]> {
if self.intersects(other) {
let diffs: [(f64, [f64; 2]); 4] = [
((self.pos[0] - self.size[0]/2.0 -
(other.pos[0] + other.size[0]/2.0)).abs(), [1.0, 0.0]),
((self.pos[0] + self.size[0]/2.0 -
(other.pos[0] - other.size[0]/2.0)).abs(), [-1.0, 0.0]),
((self.pos[1] - self.size[1]/2.0 -
(other.pos[1] + other.size[1]/2.0)).abs(), [0.0, -1.0]),
((self.pos[1] + self.size[1]/2.0 -
(other.pos[1] - other.size[1]/2.0)).abs(), [0.0, 1.0])
];
let mut min_d = f64::MAX;
let mut normal: [f64; 2] = [0.0, 0.0];
for diff in diffs.iter() {
let &(d, n) = diff;
if d < min_d {
min_d = d;
normal = n;
}
}
Some(normal)
} else {
None
}
}
}
impl Default for GameObject {
fn default() -> GameObject {
GameObject { pos: [0.0, 0.0], vel: [0.0, 0.0], size: [1.0, 1.0] }
}
}
|
//! GlusterFS API bindings
//! GlusterFS is a scalable network filesystem suitable for data-intensive
//! tasks such as cloud storage and media streaming.
//! This crate exposes the glfs module for low level interaction with the api.
//! It also exposes a set of safe wrappers in the gluster module
#[macro_use]
extern crate log;
pub mod glfs;
pub mod gluster;
|
use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.clone());
GeXY::new(model, x, y);
}
}
/// X = Y + C
pub struct EqXYC;
impl EqXYC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
// TODO merge or at least intersect domains
LeXYC::new(model.clone(), x.clone(), y.clone(), c);
GeXYC::new(model, x, y, c);
}
}
/// X = C
pub struct EqXC;
impl EqXC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, c: int) {
// TODO merge
LeXC::new(model.clone(), x.clone(), c);
GeXC::new(model, x, c);
}
}
/// X != Y
pub struct NeqXY;
impl NeqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
NeqXYCxy::new(model, x, y, 0);
}
}
/// X != Y + C
pub struct NeqXYC;
impl NeqXYC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
NeqXYCxy::new(model, x, y, c);
}
}
/// X != C
pub struct NeqXC;
#[allow(unused_variable)]
impl NeqXC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, c: int) {
x.remove(c);
}
}
struct NeqXYCxy : Prop {
c: int
}
impl NeqXYCxy {
fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
let id = model.propagators.borrow().len();
let this = NeqXYCxy { model: model.downgrade(), id: id, vars: vec![x, y], c: c};
let p = Rc::new((box this) as Box<Propagator>);
model.add_prop(p);
}
fn x(&self) -> Rc<FDVar> {
self.vars.get(0).clone()
}
fn y(&self) -> Rc<FDVar> {
self.vars.get(1).clone()
}
}
impl Propagator for NeqXYCxy {
fn id(&self) -> uint {
self.id
}
fn model(&self) -> Weak<Mod> {
self.model.clone()
}
fn events(&self) -> Vec<(uint, Event)> {
vec![(self.y().id, Ins), (self.x().id, Ins)]
}
fn propagate(&self) -> Vec<uint> {
if self.x().is_instanciated() {
self.unregister();
self.y().remove(self.x().min() - self.c)
}
else if self.y().is_instanciated() {
self.unregister();
self.x().remove(self.y().min() + self.c)
} else {
vec![]
}
}
}
#[cfg(test)]
mod tests;
|
#![feature(
plugin,
decl_macro,
option_filter,
slice_concat_ext,
custom_derive,
use_extern_macros,
crate_in_paths
)]
#![plugin(rocket_codegen)]
#![deny(dead_code)]
extern crate byteorder;
extern crate clap;
extern crate fs2;
extern crate nanoid;
extern crate reqwest;
extern crate rocket;
extern crate rocket_contrib;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate tempdir;
extern crate toml;
pub mod cli;
pub(crate) mod config;
pub(crate) mod fs;
pub(crate) mod server;
pub mod telegram;
pub(crate) mod time;
pub(crate) mod worker;
pub macro clap_app() {{
let version = env!("TOBY_VERSION");
app_from_crate!()
.version(version)
.about("🤖 Toby the friendly server bot")
}}
pub(crate) macro unwrap_err($val:expr) {
match $val {
Ok(val) => val,
Err(err) => {
eprintln!("{}", err);
::std::process::exit(1);
}
};
}
pub(crate) macro status {
($fmt:expr) => {
println!($fmt);
},
($fmt:expr, $($arg:tt)*) => {
println!($fmt, $($arg)*);
}
}
|
use super::calc;
use super::status_effect::status::{SetCombo, Status, StatusFlag, StatusFlags};
use super::status_effect::StatusEffect;
use super::{ActiveCombos, QueryActor};
use crate::sim::{SimState, SimTime};
use bevy_ecs::prelude::Entity;
use std::sync::Arc;
pub trait Apply {
fn apply(&self, sim: &SimState, query: &mut QueryActor, source: Entity, target: Entity);
}
#[derive(Default)]
pub struct DoDirectDamage {
pub potency: i64,
pub combo_action_id: Option<u32>,
pub combo_potency: Option<i64>,
pub attack_type: calc::AttackType,
}
impl DoDirectDamage {
fn consume_combo(&self, active_combos: &mut ActiveCombos) -> bool {
if let Some(action_id) = self.combo_action_id {
if active_combos.has_action(&action_id) {
active_combos.remove_action(&action_id);
return true;
}
}
false
}
}
impl Apply for DoDirectDamage {
fn apply(&self, sim: &SimState, query: &mut QueryActor, source: Entity, target: Entity) {
let calculated_damage;
if let Ok((_, job, _, _, _, _, mut status_effects, stats, mut active_combos)) =
query.get_mut(source)
{
let potency = if self.consume_combo(&mut active_combos) {
self.combo_potency.expect(
"Consumed a combo, but no combo_potency is set. This should not happen.",
)
} else {
self.potency
};
calculated_damage =
calc::direct_damage(sim, potency, *job, &stats, self.attack_type, vec![]);
status_effects.expire_with_flag(StatusFlag::ExpireOnDirectDamage);
} else {
panic!("Tried to get stats of a source with no stats.")
}
if let Ok((_, _, _, _, _, mut damage, _, _, _)) = query.get_mut(target) {
damage.add(calculated_damage);
} else {
panic!("Tried to do damage to a target that has no Damage component.")
}
}
}
pub struct StartRecast {
pub action_id: u32,
pub duration: SimTime,
}
impl Apply for StartRecast {
fn apply(&self, sim: &SimState, query: &mut QueryActor, source: Entity, _target: Entity) {
if let Ok((_, _, _, _, mut recast_expirations, _, _, _, _)) = query.get_mut(source) {
recast_expirations.set(self.action_id, sim.now() + self.duration);
}
}
}
pub struct GiveStatusEffect {
pub status: Status,
pub target_source: bool,
}
impl Apply for GiveStatusEffect {
fn apply(&self, sim: &SimState, query: &mut QueryActor, source: Entity, target: Entity) {
let receiver = if self.target_source { source } else { target };
if let Ok((_, _, _, _, _, _, mut status_effects, _, _)) = query.get_mut(receiver) {
status_effects.add(StatusEffect::new(self.status.clone(), source, sim.now()));
}
}
}
pub struct StartGcd {
base_duration: SimTime,
}
impl StartGcd {
pub fn new(duration: SimTime) -> Self {
StartGcd {
base_duration: duration,
}
}
}
impl Default for StartGcd {
fn default() -> Self {
StartGcd::new(2500)
}
}
impl Apply for StartGcd {
fn apply(&self, sim: &SimState, query: &mut QueryActor, source: Entity, _target: Entity) {
if let Ok((_, _, _, _, mut recast_expirations, _, _, _, _)) = query.get_mut(source) {
// TODO: calculate duration with skill speed
recast_expirations.set_gcd(sim.now() + self.base_duration);
}
}
}
pub struct ApplyCombo(pub u32);
impl Apply for ApplyCombo {
fn apply(&self, sim: &SimState, query: &mut QueryActor, source: Entity, _target: Entity) {
let set_combo = Status {
name: format!("{} Combo", self.0),
// TODO: figure out how long combos actually last.
duration: 15000,
flags: StatusFlags::new(&[StatusFlag::ExpireOnDirectDamage]),
effects: vec![Arc::new(SetCombo(self.0))],
..Default::default()
};
if let Ok((_, _, _, _, _, _, mut status_effects, _, _)) = query.get_mut(source) {
status_effects.add(StatusEffect::new(set_combo, source, sim.now()));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn potency() {
let ddd = DoDirectDamage {
potency: 100,
combo_potency: Some(200),
combo_action_id: Some(1),
..Default::default()
};
let mut active_combos = ActiveCombos::default();
active_combos.add_action(2);
assert_eq!(false, ddd.consume_combo(&mut active_combos));
active_combos.add_action(1);
assert_eq!(true, ddd.consume_combo(&mut active_combos));
assert_eq!(false, ddd.consume_combo(&mut active_combos));
assert_eq!(true, active_combos.has_action(&2));
assert_eq!(false, active_combos.has_action(&1));
}
}
|
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use clap::Clap;
use http_impl_demo::request::{Get, Post, Patch, Delete, Request, RequestHandler};
use http_impl_demo::{Opts, Response, ThreadPool};
use std::io;
fn main() {
let matches: Arc<Opts> = Arc::new(Opts::parse());
let socket = format!("{}:{}", matches.host, matches.port);
let listener = TcpListener::bind(&socket).expect("Could not bind to socket");
let pool = ThreadPool::new(num_cpus::get(), matches.clone());
println!("Serving on http://{}", socket);
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|opts| {
handle_connection(stream, opts).unwrap();
});
}
println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream, opts: Arc<Opts>) -> Result<(), io::Error> {
const BUFFER_SIZE: usize = 1_048_576; // 1MB
let mut buffer = [0; BUFFER_SIZE];
stream.read(&mut buffer)?;
let req = Request::from_bytes(&buffer);
let response = match match req.status_line.method {
"GET" => Get::get_response(&req, opts),
"POST" => Post::get_response(&req, opts),
"PATCH" => Patch::get_response(&req, opts),
"DELETE" => Delete::get_response(&req, opts),
_ => Ok(Response::error(
501,
Some(format!("Method {} is not supported", req.status_line.method).as_str()),
)),
} {
Ok(res) => res,
Err(err) => {
println!("ERR: {}", err);
Response::error(500, Some(err.to_string().as_str()))
}
};
stream.write(response.to_bytes().as_slice())?;
stream.flush()?;
log(&req, &response);
Ok(())
}
fn log(req: &Request, res: &Response) {
let host = req.headers.get("Host").unwrap_or(&"?????");
let date = res.headers.get("Date").unwrap();
let method = req.status_line.method;
let code = res.status_code;
let uri = req.status_line.uri;
println!("[{}]\t{}\t{} {} {}", date, host, method, code, uri);
}
|
use {
crate::{
demos::{Chunk, Demo},
types::{Hitable, HitableList, Ray, Sphere, Vec3},
Camera,
},
rand::Rng,
};
pub struct DiffuseMaterials;
impl Demo for DiffuseMaterials {
fn name(&self) -> &'static str {
"diffuse-materials"
}
fn world(&self) -> Option<HitableList> {
Some(HitableList {
list: vec![
Box::new(Sphere::new(Vec3::new(0.0, 0.0, -1.0), 0.5)),
Box::new(Sphere::new(Vec3::new(0.0, -100.5, -1.0), 100.0)),
],
})
}
fn render_chunk(
&self,
chunk: &mut Chunk,
camera: Option<&Camera>,
world: Option<&HitableList>,
samples: u8,
) {
let &mut Chunk {
x,
y,
nx,
ny,
start_x,
start_y,
ref mut buffer,
} = chunk;
let camera = camera.unwrap();
let world = world.unwrap();
let mut rng = rand::thread_rng();
let mut offset = 0;
for j in start_y..start_y + ny {
for i in start_x..start_x + nx {
let mut color = Vec3::new(0.0, 0.0, 0.0);
for _s in 0..samples {
let u = (i as f64 + rng.gen::<f64>()) / x as f64;
let v = (j as f64 + rng.gen::<f64>()) / y as f64;
let r = camera.get_ray(u, v);
color += calc_color(r, &world, &mut rng);
}
color /= samples as f64;
// Without taking square root of each color, we get a picture that
// is quite dark
// Spheres in this case are absorbing 50% of the light casted on them
// So, IRL, It *should* look a bit lighter in color
// To do that, We apply gamma correction by a factor of 2
// which means multiple rgb values by 1/gamma aka 1/2
buffer[offset] = (255.99 * color.r().sqrt()) as u8;
buffer[offset + 1] = (255.99 * color.g().sqrt()) as u8;
buffer[offset + 2] = (255.99 * color.b().sqrt()) as u8;
offset += 4;
}
}
}
}
fn calc_color(ray: Ray, world: &HitableList, rng: &mut rand::rngs::ThreadRng) -> Vec3 {
// The value of t_min here could've been 0.0 but since f32/f64 can only be
// partially compared, It may cause shadow acne effect.
// To combat this problem, We set a bias
// More information here, https://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/#shadow-acne
if let Some(hit_rec) = world.hit(&ray, 0.001, std::f64::MAX) {
let target = hit_rec.p + hit_rec.normal + random_point_in_unit_sphere(rng);
calc_color(Ray::new(hit_rec.p, target - hit_rec.p), &world, rng) * 0.5
} else {
let unit_direction = ray.direction().unit_vector();
let t = 0.5 * (unit_direction.y() + 1.0);
Vec3::new(1.0, 1.0, 1.0) * (1.0 - t) + Vec3::new(0.5, 0.7, 1.0) * t
}
}
fn random_point_in_unit_sphere(rng: &mut rand::rngs::ThreadRng) -> Vec3 {
let mut point = Vec3::new(rng.gen::<f64>(), rng.gen::<f64>(), rng.gen::<f64>()) * 2.0
- Vec3::new(1.0, 1.0, 1.0);
while point.sq_len() >= 1.0 {
point = Vec3::new(rng.gen::<f64>(), rng.gen::<f64>(), rng.gen::<f64>()) * 2.0
- Vec3::new(1.0, 1.0, 1.0);
}
point
}
|
use std::sync::Arc;
use sourcerenderer_core::graphics::{
AttachmentBlendInfo,
AttachmentInfo,
Backend as GraphicsBackend,
BarrierAccess,
BarrierSync,
BlendInfo,
CommandBuffer,
CompareFunc,
CullMode,
DepthStencilAttachmentRef,
DepthStencilInfo,
FillMode,
Format,
FrontFace,
IndexFormat,
InputAssemblerElement,
InputRate,
LoadOp,
LogicOp,
OutputAttachmentRef,
PipelineBinding,
PrimitiveType,
RasterizerInfo,
RenderPassAttachment,
RenderPassAttachmentView,
RenderPassBeginInfo,
RenderPassInfo,
RenderpassRecordingMode,
SampleCount,
Scissor,
ShaderInputElement,
StencilInfo,
StoreOp,
SubpassInfo,
Texture,
TextureDimension,
TextureInfo,
TextureLayout,
TextureUsage,
TextureView,
TextureViewInfo,
VertexLayoutInfo,
Viewport,
};
use sourcerenderer_core::{
Platform,
Vec2,
Vec2I,
Vec2UI,
};
use super::draw_prep::DrawPrepPass;
use super::gpu_scene::DRAW_CAPACITY;
use crate::renderer::render_path::RenderPassParameters;
use crate::renderer::renderer_resources::{
HistoryResourceEntry,
RendererResources,
};
use crate::renderer::shader_manager::{
GraphicsPipelineHandle,
GraphicsPipelineInfo,
ShaderManager,
};
pub struct VisibilityBufferPass {
pipeline: GraphicsPipelineHandle,
}
impl VisibilityBufferPass {
pub const BARYCENTRICS_TEXTURE_NAME: &'static str = "barycentrics";
pub const PRIMITIVE_ID_TEXTURE_NAME: &'static str = "primitive";
pub const DEPTH_TEXTURE_NAME: &'static str = "depth";
pub fn new<P: Platform>(
resolution: Vec2UI,
resources: &mut RendererResources<P::GraphicsBackend>,
shader_manager: &mut ShaderManager<P>,
) -> Self {
let barycentrics_texture_info = TextureInfo {
dimension: TextureDimension::Dim2D,
format: Format::RG16UNorm,
width: resolution.x,
height: resolution.y,
depth: 1,
mip_levels: 1,
array_length: 1,
samples: SampleCount::Samples1,
usage: TextureUsage::SAMPLED
| TextureUsage::RENDER_TARGET
| TextureUsage::COPY_SRC
| TextureUsage::STORAGE,
supports_srgb: false,
};
resources.create_texture(
Self::BARYCENTRICS_TEXTURE_NAME,
&barycentrics_texture_info,
false,
);
let primitive_id_texture_info = TextureInfo {
dimension: TextureDimension::Dim2D,
format: Format::R32UInt,
width: resolution.x,
height: resolution.y,
depth: 1,
mip_levels: 1,
array_length: 1,
samples: SampleCount::Samples1,
usage: TextureUsage::SAMPLED
| TextureUsage::RENDER_TARGET
| TextureUsage::COPY_SRC
| TextureUsage::STORAGE,
supports_srgb: false,
};
resources.create_texture(
Self::PRIMITIVE_ID_TEXTURE_NAME,
&primitive_id_texture_info,
false,
);
let depth_texture_info = TextureInfo {
dimension: TextureDimension::Dim2D,
format: Format::D24,
width: resolution.x,
height: resolution.y,
depth: 1,
mip_levels: 1,
array_length: 1,
samples: SampleCount::Samples1,
usage: TextureUsage::SAMPLED | TextureUsage::DEPTH_STENCIL,
supports_srgb: false,
};
resources.create_texture(Self::DEPTH_TEXTURE_NAME, &depth_texture_info, true);
let pipeline_info: GraphicsPipelineInfo = GraphicsPipelineInfo {
vs: "shaders/visibility_buffer.vert.spv",
fs: Some("shaders/visibility_buffer.frag.spv"),
primitive_type: PrimitiveType::Triangles,
vertex_layout: VertexLayoutInfo {
input_assembler: &[InputAssemblerElement {
binding: 0,
stride: 64,
input_rate: InputRate::PerVertex,
}],
shader_inputs: &[ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 0,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 0,
format: Format::RGB32Float,
}],
},
rasterizer: RasterizerInfo {
fill_mode: FillMode::Fill,
cull_mode: CullMode::Back,
front_face: FrontFace::Clockwise,
sample_count: SampleCount::Samples1,
},
depth_stencil: DepthStencilInfo {
depth_test_enabled: true,
depth_write_enabled: true,
depth_func: CompareFunc::LessEqual,
stencil_enable: false,
stencil_read_mask: 0u8,
stencil_write_mask: 0u8,
stencil_front: StencilInfo::default(),
stencil_back: StencilInfo::default(),
},
blend: BlendInfo {
alpha_to_coverage_enabled: false,
logic_op_enabled: false,
logic_op: LogicOp::And,
constants: [0f32, 0f32, 0f32, 0f32],
attachments: &[
AttachmentBlendInfo::default(),
AttachmentBlendInfo::default(),
],
},
};
let pipeline = shader_manager.request_graphics_pipeline(
&pipeline_info,
&RenderPassInfo {
attachments: &[
AttachmentInfo {
format: primitive_id_texture_info.format,
samples: primitive_id_texture_info.samples,
},
AttachmentInfo {
format: barycentrics_texture_info.format,
samples: barycentrics_texture_info.samples,
},
AttachmentInfo {
format: depth_texture_info.format,
samples: depth_texture_info.samples,
},
],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[
OutputAttachmentRef {
index: 0,
resolve_attachment_index: None,
},
OutputAttachmentRef {
index: 1,
resolve_attachment_index: None,
},
],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 2,
read_only: false,
}),
}],
},
0,
);
Self { pipeline }
}
#[profiling::function]
pub(super) fn execute<P: Platform>(
&mut self,
cmd_buffer: &mut <P::GraphicsBackend as GraphicsBackend>::CommandBuffer,
params: &RenderPassParameters<'_, P>
) {
cmd_buffer.begin_label("Visibility Buffer pass");
let draw_buffer = params.resources.access_buffer(
cmd_buffer,
DrawPrepPass::INDIRECT_DRAW_BUFFER,
BarrierSync::INDIRECT,
BarrierAccess::INDIRECT_READ,
HistoryResourceEntry::Current,
);
let barycentrics_rtv = params.resources.access_view(
cmd_buffer,
Self::BARYCENTRICS_TEXTURE_NAME,
BarrierSync::RENDER_TARGET,
BarrierAccess::RENDER_TARGET_WRITE,
TextureLayout::RenderTarget,
true,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let primitive_id_rtv = params.resources.access_view(
cmd_buffer,
Self::PRIMITIVE_ID_TEXTURE_NAME,
BarrierSync::RENDER_TARGET,
BarrierAccess::RENDER_TARGET_WRITE,
TextureLayout::RenderTarget,
true,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let dsv = params.resources.access_view(
cmd_buffer,
Self::DEPTH_TEXTURE_NAME,
BarrierSync::LATE_DEPTH | BarrierSync::EARLY_DEPTH,
BarrierAccess::DEPTH_STENCIL_READ | BarrierAccess::DEPTH_STENCIL_WRITE,
TextureLayout::DepthStencilReadWrite,
true,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
cmd_buffer.begin_render_pass(
&RenderPassBeginInfo {
attachments: &[
RenderPassAttachment {
view: RenderPassAttachmentView::RenderTarget(&primitive_id_rtv),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
},
RenderPassAttachment {
view: RenderPassAttachmentView::RenderTarget(&barycentrics_rtv),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
},
RenderPassAttachment {
view: RenderPassAttachmentView::DepthStencil(&dsv),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
},
],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[
OutputAttachmentRef {
index: 0,
resolve_attachment_index: None,
},
OutputAttachmentRef {
index: 1,
resolve_attachment_index: None,
},
],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 2,
read_only: false,
}),
}],
},
RenderpassRecordingMode::Commands,
);
let rtv_info = barycentrics_rtv.texture().info();
let pipeline = params.shader_manager.get_graphics_pipeline(self.pipeline);
cmd_buffer.set_pipeline(PipelineBinding::Graphics(&pipeline));
cmd_buffer.set_viewports(&[Viewport {
position: Vec2::new(0.0f32, 0.0f32),
extent: Vec2::new(rtv_info.width as f32, rtv_info.height as f32),
min_depth: 0.0f32,
max_depth: 1.0f32,
}]);
cmd_buffer.set_scissors(&[Scissor {
position: Vec2I::new(0, 0),
extent: Vec2UI::new(9999, 9999),
}]);
cmd_buffer.set_vertex_buffer(params.scene.vertex_buffer, 0);
cmd_buffer.set_index_buffer(params.scene.index_buffer, 0, IndexFormat::U32);
cmd_buffer.finish_binding();
cmd_buffer.draw_indexed_indirect(&draw_buffer, 4, &draw_buffer, 0, DRAW_CAPACITY, 20);
cmd_buffer.end_render_pass();
cmd_buffer.end_label();
}
}
|
use crate::ptr::MutPtr;
use crate::worker::{
commands::*,
component::{self, Component, UpdateParameters},
entity::Entity,
internal::utils::cstr_to_string,
locator::*,
metrics::Metrics,
op::OpList,
parameters::ConnectionParameters,
{EntityId, InterestOverride, LogLevel, RequestId},
};
use futures::{Async, Future};
use spatialos_sdk_sys::worker::*;
use std::{
ffi::{CStr, CString, NulError},
ptr,
};
/// Information about the status of a worker connection or network request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectionStatus {
/// The status of the connection or request.
pub code: ConnectionStatusCode,
/// Detailed, human-readable description of the connection status.
///
/// Will be "OK" if no error occurred.
pub detail: String,
}
#[derive(Copy, Clone, PartialOrd, PartialEq, Eq, Debug)]
pub enum ConnectionStatusCode {
Success,
InternalError,
InvalidArgument,
NetworkError,
Timeout,
Cancelled,
Rejected,
PlayerIdentityTokenExpired,
LoginTokenExpired,
CapacityExceeded,
RateExceeded,
ServerShutdown,
}
impl From<u8> for ConnectionStatusCode {
fn from(value: u8) -> Self {
match u32::from(value) {
1 => ConnectionStatusCode::Success,
2 => ConnectionStatusCode::InternalError,
3 => ConnectionStatusCode::InvalidArgument,
4 => ConnectionStatusCode::NetworkError,
5 => ConnectionStatusCode::Timeout,
6 => ConnectionStatusCode::Cancelled,
7 => ConnectionStatusCode::Rejected,
8 => ConnectionStatusCode::PlayerIdentityTokenExpired,
9 => ConnectionStatusCode::LoginTokenExpired,
10 => ConnectionStatusCode::CapacityExceeded,
11 => ConnectionStatusCode::RateExceeded,
12 => ConnectionStatusCode::ServerShutdown,
_ => panic!(format!("Unknown connection status code: {}", value)),
}
}
}
/// Connection trait to allow for mocking the connection.
pub trait Connection {
fn send_log_message(
&mut self,
level: LogLevel,
logger_name: &str,
message: &str,
entity_id: Option<EntityId>,
);
fn send_metrics(&mut self, metrics: &Metrics);
fn send_reserve_entity_ids_request(
&mut self,
payload: ReserveEntityIdsRequest,
timeout_millis: Option<u32>,
) -> RequestId<ReserveEntityIdsRequest>;
fn send_create_entity_request(
&mut self,
entity: Entity,
entity_id: Option<EntityId>,
timeout_millis: Option<u32>,
) -> RequestId<CreateEntityRequest>;
fn send_delete_entity_request(
&mut self,
payload: DeleteEntityRequest,
timeout_millis: Option<u32>,
) -> RequestId<DeleteEntityRequest>;
fn send_entity_query_request(
&mut self,
payload: EntityQueryRequest,
timeout_millis: Option<u32>,
) -> RequestId<EntityQueryRequest>;
fn send_command_request<C: Component>(
&mut self,
entity_id: EntityId,
request: C::CommandRequest,
timeout_millis: Option<u32>,
params: CommandParameters,
) -> RequestId<OutgoingCommandRequest>;
fn send_command_response<C: Component>(
&mut self,
request_id: RequestId<IncomingCommandRequest>,
response: C::CommandResponse,
);
fn send_command_failure(
&mut self,
request_id: RequestId<IncomingCommandRequest>,
message: &str,
) -> Result<(), NulError>;
fn send_component_update<C: Component>(
&mut self,
entity_id: EntityId,
update: C::Update,
parameters: UpdateParameters,
);
fn send_component_interest(
&mut self,
entity_id: EntityId,
interest_overrides: &[InterestOverride],
);
fn send_authority_loss_imminent_acknowledgement(
&mut self,
entity_id: EntityId,
component_id: u32,
);
fn set_protocol_logging_enabled(&mut self, enabled: bool);
fn get_connection_status(&mut self) -> ConnectionStatus;
fn get_worker_flag(&mut self, name: &str) -> Option<String>;
fn get_op_list(&mut self, timeout_millis: u32) -> OpList;
fn get_worker_id(&self) -> &str;
fn get_worker_attributes(&self) -> &[String];
}
pub struct WorkerConnection {
// NOTE: The `Worker_Connection` pointer is wrapped in a `MutPtr` to ensure
// that we only attempt to use the connection pointer in methods that take
// `&mut self`. This enforces the thread-safety requirements of
// `Worker_Connection`. See this forum post for more information:
// https://forums.improbable.io/t/thread-safety-of-worker-connection-object/5358/2
//
// TODO: Replace the forum post URL with the actual relevant C API docs, once
// the docs have been updated to clarify the thread-safety requirements of
// the worker connection object.
connection_ptr: MutPtr<Worker_Connection>,
// Cached copies of static connection data. These are stored internally so that we can guarantee it will be safe to access this data through `&self`.
id: String,
attributes: Vec<String>,
}
impl WorkerConnection {
pub(crate) fn new(connection_ptr: *mut Worker_Connection) -> Self {
unsafe {
let worker_id = Worker_Connection_GetWorkerId(connection_ptr);
let cstr = CStr::from_ptr(worker_id);
let sdk_attr = Worker_Connection_GetWorkerAttributes(connection_ptr);
let attributes = if (*sdk_attr).attributes.is_null() {
Vec::new()
} else {
::std::slice::from_raw_parts(
(*sdk_attr).attributes,
(*sdk_attr).attribute_count as usize,
)
.iter()
.map(|s| CStr::from_ptr(*s).to_string_lossy().to_string())
.collect()
};
WorkerConnection {
connection_ptr: MutPtr::new(connection_ptr),
id: cstr.to_string_lossy().to_string(),
attributes,
}
}
}
pub fn connect_receptionist_async(
worker_id: &str,
hostname: &str,
port: u16,
params: &ConnectionParameters,
) -> WorkerConnectionFuture {
let hostname_cstr = CString::new(hostname).expect("Received 0 byte in supplied hostname.");
let worker_id_cstr =
CString::new(worker_id).expect("Received 0 byte in supplied Worker ID");
// Flatten the Rust representation of the connection parameters into a format more
// compatible with the C API.
let params = params.flatten();
let future_ptr = unsafe {
Worker_ConnectAsync(
hostname_cstr.as_ptr(),
port,
worker_id_cstr.as_ptr(),
¶ms.as_raw(),
)
};
assert!(!future_ptr.is_null());
WorkerConnectionFuture::new(future_ptr)
}
pub fn connect_locator_async(
locator: &Locator,
params: &ConnectionParameters,
) -> WorkerConnectionFuture {
// Flatten the Rust representation of the connection parameters into a format more
// compatible with the C API.
let params = params.flatten();
let future_ptr = unsafe { Worker_Locator_ConnectAsync(locator.locator, ¶ms.as_raw()) };
assert!(!future_ptr.is_null());
WorkerConnectionFuture::new(future_ptr)
}
}
impl Connection for WorkerConnection {
fn send_log_message(
&mut self,
level: LogLevel,
logger_name: &str,
message: &str,
entity_id: Option<EntityId>,
) {
assert!(!self.connection_ptr.is_null());
let logger_name = CString::new(logger_name).unwrap();
let message = CString::new(message).unwrap();
unsafe {
let log_message = Worker_LogMessage {
level: level.to_worker_sdk(),
logger_name: logger_name.as_ptr(),
message: message.as_ptr(),
entity_id: match entity_id {
Some(e) => &e.id,
None => ptr::null(),
},
};
Worker_Connection_SendLogMessage(self.connection_ptr.get(), &log_message);
}
}
fn send_metrics(&mut self, metrics: &Metrics) {
assert!(!self.connection_ptr.is_null());
let worker_metrics = metrics.to_worker_sdk();
unsafe { Worker_Connection_SendMetrics(self.connection_ptr.get(), &worker_metrics.metrics) }
}
fn send_reserve_entity_ids_request(
&mut self,
payload: ReserveEntityIdsRequest,
timeout_millis: Option<u32>,
) -> RequestId<ReserveEntityIdsRequest> {
unsafe {
let timeout = match timeout_millis {
Some(c) => &c,
None => ptr::null(),
};
let id = Worker_Connection_SendReserveEntityIdsRequest(
self.connection_ptr.get(),
payload.0,
timeout,
);
RequestId::new(id)
}
}
fn send_create_entity_request(
&mut self,
entity: Entity,
entity_id: Option<EntityId>,
timeout_millis: Option<u32>,
) -> RequestId<CreateEntityRequest> {
let timeout = match timeout_millis {
Some(c) => &c,
None => ptr::null(),
};
let entity_id = match entity_id {
Some(e) => &e.id,
None => ptr::null(),
};
let mut component_data = entity.raw_component_data();
let id = unsafe {
Worker_Connection_SendCreateEntityRequest(
self.connection_ptr.get(),
component_data.components.len() as _,
component_data.components.as_mut_ptr(),
entity_id,
timeout,
)
};
RequestId::new(id)
}
fn send_delete_entity_request(
&mut self,
payload: DeleteEntityRequest,
timeout_millis: Option<u32>,
) -> RequestId<DeleteEntityRequest> {
unsafe {
let timeout = match timeout_millis {
Some(c) => &c,
None => ptr::null(),
};
let id = Worker_Connection_SendDeleteEntityRequest(
self.connection_ptr.get(),
payload.0.id,
timeout,
);
RequestId::new(id)
}
}
fn send_entity_query_request(
&mut self,
payload: EntityQueryRequest,
timeout_millis: Option<u32>,
) -> RequestId<EntityQueryRequest> {
unsafe {
let timeout = match timeout_millis {
Some(c) => &c,
None => ptr::null(),
};
let worker_query = payload.0.to_worker_sdk();
let id = Worker_Connection_SendEntityQueryRequest(
self.connection_ptr.get(),
&worker_query.query,
timeout,
);
RequestId::new(id)
}
}
fn send_command_request<C: Component>(
&mut self,
entity_id: EntityId,
request: C::CommandRequest,
timeout_millis: Option<u32>,
params: CommandParameters,
) -> RequestId<OutgoingCommandRequest> {
let command_index = C::get_request_command_index(&request);
let timeout = match timeout_millis {
Some(c) => &c,
None => ptr::null(),
};
let mut command_request = Worker_CommandRequest {
reserved: ptr::null_mut(),
component_id: C::ID,
command_index,
schema_type: ptr::null_mut(),
user_handle: component::handle_allocate(request),
};
let request_id = unsafe {
Worker_Connection_SendCommandRequest(
self.connection_ptr.get(),
entity_id.id,
&mut command_request,
timeout,
¶ms.to_worker_sdk(),
)
};
unsafe {
component::handle_free::<C::CommandRequest>(command_request.user_handle);
}
RequestId::new(request_id)
}
fn send_command_response<C: Component>(
&mut self,
request_id: RequestId<IncomingCommandRequest>,
response: C::CommandResponse,
) {
unsafe {
let mut raw_response = Worker_CommandResponse {
reserved: ptr::null_mut(),
component_id: C::ID,
command_index: C::get_response_command_index(&response),
schema_type: ptr::null_mut(),
user_handle: component::handle_allocate(response),
};
Worker_Connection_SendCommandResponse(
self.connection_ptr.get(),
request_id.id,
&mut raw_response,
);
component::handle_free::<C::CommandResponse>(raw_response.user_handle);
}
}
fn send_command_failure(
&mut self,
request_id: RequestId<IncomingCommandRequest>,
message: &str,
) -> Result<(), NulError> {
let message = CString::new(message)?;
unsafe {
Worker_Connection_SendCommandFailure(
self.connection_ptr.get(),
request_id.id,
message.as_ptr(),
);
}
Ok(())
}
fn send_component_update<C: Component>(
&mut self,
entity_id: EntityId,
update: C::Update,
parameters: UpdateParameters,
) {
let mut component_update = Worker_ComponentUpdate {
reserved: ptr::null_mut(),
component_id: C::ID,
schema_type: ptr::null_mut(),
user_handle: component::handle_allocate(update),
};
let params = parameters.to_worker_sdk();
unsafe {
Worker_Connection_SendComponentUpdate(
self.connection_ptr.get(),
entity_id.id,
&mut component_update,
¶ms,
);
component::handle_free::<C::Update>(component_update.user_handle);
}
}
fn send_component_interest(
&mut self,
entity_id: EntityId,
interest_overrides: &[InterestOverride],
) {
assert!(!self.connection_ptr.is_null());
let worker_sdk_overrides = interest_overrides
.iter()
.map(InterestOverride::to_worker_sdk)
.collect::<Vec<Worker_InterestOverride>>();
unsafe {
Worker_Connection_SendComponentInterest(
self.connection_ptr.get(),
entity_id.id,
worker_sdk_overrides.as_ptr(),
worker_sdk_overrides.len() as u32,
);
}
}
fn send_authority_loss_imminent_acknowledgement(
&mut self,
entity_id: EntityId,
component_id: u32,
) {
assert!(!self.connection_ptr.is_null());
unsafe {
Worker_Connection_SendAuthorityLossImminentAcknowledgement(
self.connection_ptr.get(),
entity_id.id,
component_id,
);
}
}
fn set_protocol_logging_enabled(&mut self, enabled: bool) {
assert!(!self.connection_ptr.is_null());
unsafe {
Worker_Connection_SetProtocolLoggingEnabled(self.connection_ptr.get(), enabled as u8);
}
}
fn get_connection_status(&mut self) -> ConnectionStatus {
let ptr = self.connection_ptr.get();
unsafe {
let code = ConnectionStatusCode::from(Worker_Connection_GetConnectionStatusCode(ptr));
let detail = cstr_to_string(Worker_Connection_GetConnectionStatusDetailString(ptr));
ConnectionStatus { code, detail }
}
}
fn get_worker_flag(&mut self, name: &str) -> Option<String> {
let flag_name = CString::new(name).unwrap();
extern "C" fn worker_flag_handler(
user_data: *mut ::std::os::raw::c_void,
value: *const ::std::os::raw::c_char,
) {
unsafe {
if value.is_null() {
return;
}
let data: &mut Option<String> = &mut *(user_data as *mut Option<String>);
let str = CStr::from_ptr(value).to_string_lossy().to_string();
*data = Some(str);
}
};
let mut data: Option<String> = None;
unsafe {
Worker_Connection_GetWorkerFlag(
self.connection_ptr.get(),
flag_name.as_ptr(),
(&mut data as *mut Option<String>) as *mut ::std::os::raw::c_void,
Some(worker_flag_handler),
);
}
data
}
fn get_op_list(&mut self, timeout_millis: u32) -> OpList {
assert!(!self.connection_ptr.is_null());
let raw_op_list =
unsafe { Worker_Connection_GetOpList(self.connection_ptr.get(), timeout_millis) };
assert!(!raw_op_list.is_null());
OpList::new(raw_op_list)
}
fn get_worker_id(&self) -> &str {
&self.id
}
fn get_worker_attributes(&self) -> &[String] {
&self.attributes
}
}
impl Drop for WorkerConnection {
fn drop(&mut self) {
assert!(!self.connection_ptr.is_null());
unsafe { Worker_Connection_Destroy(self.connection_ptr.get()) };
}
}
// SAFE: The worker connection object is safe to send between threads.
unsafe impl Send for WorkerConnection {}
unsafe impl Sync for WorkerConnection {}
pub struct WorkerConnectionFuture {
future_ptr: *mut Worker_ConnectionFuture,
was_consumed: bool,
}
impl WorkerConnectionFuture {
pub(crate) fn new(ptr: *mut Worker_ConnectionFuture) -> Self {
WorkerConnectionFuture {
future_ptr: ptr,
was_consumed: false,
}
}
}
impl Drop for WorkerConnectionFuture {
fn drop(&mut self) {
assert!(!self.future_ptr.is_null());
unsafe {
Worker_ConnectionFuture_Destroy(self.future_ptr);
};
}
}
impl Future for WorkerConnectionFuture {
type Item = WorkerConnection;
type Error = String;
fn poll(&mut self) -> Result<Async<<Self as Future>::Item>, <Self as Future>::Error> {
if self.was_consumed {
return Err("WorkerConnectionFuture has already been consumed.".to_owned());
}
assert!(!self.future_ptr.is_null());
let connection_ptr = unsafe { Worker_ConnectionFuture_Get(self.future_ptr, &0) };
if connection_ptr.is_null() {
return Ok(Async::NotReady);
}
self.was_consumed = true;
let mut connection = WorkerConnection::new(connection_ptr);
let status = connection.get_connection_status();
if status.code == ConnectionStatusCode::Success {
return Ok(Async::Ready(connection));
}
Err(status.detail)
}
fn wait(self) -> Result<<Self as Future>::Item, <Self as Future>::Error>
where
Self: Sized,
{
if self.was_consumed {
return Err("WorkerConnectionFuture has already been consumed.".to_owned());
}
assert!(!self.future_ptr.is_null());
let connection_ptr = unsafe { Worker_ConnectionFuture_Get(self.future_ptr, ptr::null()) };
let mut connection = WorkerConnection::new(connection_ptr);
let status = connection.get_connection_status();
if status.code == ConnectionStatusCode::Success {
return Ok(connection);
}
Err(status.detail)
}
}
|
use rand;
use rand::*;
/// Adds one
///
/// # Example
/// ```
/// let a = 2;
///
/// assert_eq!(3, add_one::add_one(a));
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
pub fn ret_rand(mut random_g: rand::ThreadRng) -> u32 {
random_g.next_u32()
}
#[cfg(test)]
mod tests {
use super::add_one;
#[test]
fn it_works() {
assert_eq!(3, add_one(2));
}
}
|
extern crate regex;
use std::io;
use std::fs;
use std::io::BufRead;
use std::path::Path;
use std::collections::HashMap;
use regex::Regex;
use itertools::Itertools;
fn main() {
let input = parse_input();
let instructions = input.instructions;
let set = vec![4, 2, 1];
println!("Power set of {:?} = {:?}", set, power_set_of_bits(&set));
part_1(&instructions);
part_2(&instructions);
}
fn part_1(instructions: &Vec<Instruction>) {
let mut mask = None;
let mut memory: HashMap<usize, u64> = HashMap::new();
for (i, instruction) in instructions.iter().enumerate() {
match instruction {
UpdateMask(m) => { mask = Some(m); }
Execute(Assign {
index,
value,
}) => {
if let Some(m) = mask {
let masked_value = m.mask_value(value);
memory.insert(*index, masked_value);
} else {
panic!("No mask! Row {}", i);
}
}
}
}
// 16003257187056
println!("Final sum of values = {}", memory.values().fold(0, |acc, num| acc + num));
}
fn part_2(instructions: &Vec<Instruction>) {
let mut mask = None;
let mut memory: HashMap<usize, u64> = HashMap::new();
for (i, instruction) in instructions.iter().enumerate() {
match instruction {
UpdateMask(m) => { mask = Some(m); }
Execute(Assign {
index,
value,
}) => {
if let Some(m) = mask {
for masked_index in m.masked_indexes(index) {
memory.insert(masked_index, *value);
}
} else {
panic!("No mask! Row {}", i);
}
}
}
}
// 16003257187056
println!("Final sum of values = {}", memory.values().fold(0, |acc, num| acc + num));
}
struct InputData {
instructions: Vec<Instruction>,
}
enum Bit {
Zero,
One,
Float,
}
struct Mask {
bits: Vec<Bit>,
}
impl Mask {
fn mask_value(&self, value: &u64) -> u64 {
let mut zeros_to_and = 1;
let mut ones_to_or = 0;
for bit in self.bits.iter() {
zeros_to_and = zeros_to_and << 1;
ones_to_or = ones_to_or << 1;
match bit {
Bit::Float => { zeros_to_and += 1; }
Bit::One => { ones_to_or += 1; zeros_to_and += 1 }
Bit::Zero => { }
}
}
(value & zeros_to_and) | ones_to_or
}
fn masked_indexes(&self, index: &usize) -> Vec<usize> {
let mut zeros_to_and = 1;
let mut ones_to_or = 0;
let mut floats_to_power_set = vec![];
for bit in self.bits.iter() {
zeros_to_and = zeros_to_and << 1;
ones_to_or = ones_to_or << 1;
floats_to_power_set = floats_to_power_set.iter().map(|i| i << 1).collect();
match bit {
Bit::Float => { floats_to_power_set.push(1); }
Bit::One => { ones_to_or += 1; zeros_to_and += 1 }
Bit::Zero => { zeros_to_and += 1; }
}
}
let base_index = (index & zeros_to_and) | ones_to_or;
power_set_of_bits(&floats_to_power_set).
iter().
map(|mask| mask | base_index).
collect()
}
}
fn power_set_of_bits(bits: &Vec<usize>) -> Vec<usize> {
(0..=bits.len()).
flat_map(|subset_size| {
bits.iter().combinations(subset_size).collect::<Vec<_>>()
}).
map(|nums: Vec<_>| nums.iter().fold(0, |acc, num| acc | **num)).
collect()
}
struct Assign {
index: usize,
value: u64,
}
enum Instruction {
UpdateMask(Mask),
Execute(Assign)
}
use Instruction::*;
fn parse_mask(s: &str) -> Mask {
Mask {
bits: s.chars().map(|c| {
match c {
'X' => Bit::Float,
'1' => Bit::One,
'0' => Bit::Zero,
_ => panic!("Unknown char {}", c),
}
}).collect(),
}
}
fn parse_input() -> InputData {
let io_result = lines_in_file("inputs/day14.txt");
let mask_update_regex = Regex::new(r"^mask = (?P<mask>[X01]+)$").unwrap();
let assign_regex = Regex::new(r"^mem\[(?P<index>\d+)\] = (?P<value>\d+)$").unwrap();
match io_result {
Ok(lines) => {
let instructions = lines.map(|line| match line {
Ok(stuff) => {
let mask_result = mask_update_regex.captures(&stuff);
if let Some(captures) = mask_result {
let mask_string = captures.name("mask").unwrap().as_str();
UpdateMask(parse_mask(mask_string))
} else {
let captures = assign_regex.captures(&stuff).unwrap();
Execute(Assign {
index: captures.name("index").unwrap().as_str().parse().unwrap(),
value: captures.name("value").unwrap().as_str().parse().unwrap(),
})
}
}
Err(_) => panic!("Error reading line"),
}).collect();
InputData {
instructions: instructions,
}
},
Err(_) => panic!("Error reading file"),
}
}
fn lines_in_file<P>(file_path: P) -> io::Result<io::Lines<io::BufReader<fs::File>>> where P: AsRef<Path> {
let file = fs::File::open(file_path)?;
Ok(io::BufReader::new(file).lines())
}
|
fn main() {
// Type annotation
let v: Vec<i32> = Vec::new();
println!("{:?}", v);
// Inferred type w/ vec! macro
let v = vec![1, 2, 3];
println!("{:?}", v);
// Updating a vector
let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
println!("{:?}", v);
// Big zero vector
let mut zero_vec = vec![0; 1000];
println!("zero_vec.len(): {:?}", zero_vec.len());
// Updating the zero vector
for i in 1..999 {
if i % 2 == 0 {
zero_vec[i] = 1;
}
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qgraphicstransform.h
// dst-file: /src/widgets/qgraphicstransform.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 super::qgraphicstransform::QGraphicsTransform; // 773
use std::ops::Deref;
use super::super::gui::qvector3d::*; // 771
use super::super::core::qobject::*; // 771
use super::super::core::qobjectdefs::*; // 771
use super::super::gui::qmatrix4x4::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QGraphicsRotation_Class_Size() -> c_int;
// proto: QVector3D QGraphicsRotation::origin();
fn C_ZNK17QGraphicsRotation6originEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsRotation::setAngle(qreal );
fn C_ZN17QGraphicsRotation8setAngleEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QGraphicsRotation::QGraphicsRotation(QObject * parent);
fn C_ZN17QGraphicsRotationC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: const QMetaObject * QGraphicsRotation::metaObject();
fn C_ZNK17QGraphicsRotation10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsRotation::~QGraphicsRotation();
fn C_ZN17QGraphicsRotationD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsRotation::setOrigin(const QVector3D & point);
fn C_ZN17QGraphicsRotation9setOriginERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QVector3D QGraphicsRotation::axis();
fn C_ZNK17QGraphicsRotation4axisEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsRotation::applyTo(QMatrix4x4 * matrix);
fn C_ZNK17QGraphicsRotation7applyToEP10QMatrix4x4(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsRotation::setAxis(const QVector3D & axis);
fn C_ZN17QGraphicsRotation7setAxisERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: qreal QGraphicsRotation::angle();
fn C_ZNK17QGraphicsRotation5angleEv(qthis: u64 /* *mut c_void*/) -> c_double;
fn QGraphicsScale_Class_Size() -> c_int;
// proto: void QGraphicsScale::applyTo(QMatrix4x4 * matrix);
fn C_ZNK14QGraphicsScale7applyToEP10QMatrix4x4(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: qreal QGraphicsScale::zScale();
fn C_ZNK14QGraphicsScale6zScaleEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: qreal QGraphicsScale::xScale();
fn C_ZNK14QGraphicsScale6xScaleEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: qreal QGraphicsScale::yScale();
fn C_ZNK14QGraphicsScale6yScaleEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QGraphicsScale::setOrigin(const QVector3D & point);
fn C_ZN14QGraphicsScale9setOriginERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsScale::setYScale(qreal );
fn C_ZN14QGraphicsScale9setYScaleEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: QVector3D QGraphicsScale::origin();
fn C_ZNK14QGraphicsScale6originEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScale::setZScale(qreal );
fn C_ZN14QGraphicsScale9setZScaleEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QGraphicsScale::setXScale(qreal );
fn C_ZN14QGraphicsScale9setXScaleEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: const QMetaObject * QGraphicsScale::metaObject();
fn C_ZNK14QGraphicsScale10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScale::QGraphicsScale(QObject * parent);
fn C_ZN14QGraphicsScaleC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: void QGraphicsScale::~QGraphicsScale();
fn C_ZN14QGraphicsScaleD2Ev(qthis: u64 /* *mut c_void*/);
fn QGraphicsTransform_Class_Size() -> c_int;
// proto: void QGraphicsTransform::applyTo(QMatrix4x4 * matrix);
fn C_ZNK18QGraphicsTransform7applyToEP10QMatrix4x4(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsTransform::~QGraphicsTransform();
fn C_ZN18QGraphicsTransformD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsTransform::QGraphicsTransform(QObject * parent);
fn C_ZN18QGraphicsTransformC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: const QMetaObject * QGraphicsTransform::metaObject();
fn C_ZNK18QGraphicsTransform10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
fn QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation12angleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation11axisChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation13originChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale12scaleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13originChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13zScaleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13yScaleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13xScaleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QGraphicsRotation)=1
#[derive(Default)]
pub struct QGraphicsRotation {
qbase: QGraphicsTransform,
pub qclsinst: u64 /* *mut c_void*/,
pub _originChanged: QGraphicsRotation_originChanged_signal,
pub _axisChanged: QGraphicsRotation_axisChanged_signal,
pub _angleChanged: QGraphicsRotation_angleChanged_signal,
}
// class sizeof(QGraphicsScale)=1
#[derive(Default)]
pub struct QGraphicsScale {
qbase: QGraphicsTransform,
pub qclsinst: u64 /* *mut c_void*/,
pub _yScaleChanged: QGraphicsScale_yScaleChanged_signal,
pub _xScaleChanged: QGraphicsScale_xScaleChanged_signal,
pub _zScaleChanged: QGraphicsScale_zScaleChanged_signal,
pub _scaleChanged: QGraphicsScale_scaleChanged_signal,
pub _originChanged: QGraphicsScale_originChanged_signal,
}
// class sizeof(QGraphicsTransform)=1
#[derive(Default)]
pub struct QGraphicsTransform {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QGraphicsRotation {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGraphicsRotation {
return QGraphicsRotation{qbase: QGraphicsTransform::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGraphicsRotation {
type Target = QGraphicsTransform;
fn deref(&self) -> &QGraphicsTransform {
return & self.qbase;
}
}
impl AsRef<QGraphicsTransform> for QGraphicsRotation {
fn as_ref(& self) -> & QGraphicsTransform {
return & self.qbase;
}
}
// proto: QVector3D QGraphicsRotation::origin();
impl /*struct*/ QGraphicsRotation {
pub fn origin<RetType, T: QGraphicsRotation_origin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.origin(self);
// return 1;
}
}
pub trait QGraphicsRotation_origin<RetType> {
fn origin(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: QVector3D QGraphicsRotation::origin();
impl<'a> /*trait*/ QGraphicsRotation_origin<QVector3D> for () {
fn origin(self , rsthis: & QGraphicsRotation) -> QVector3D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QGraphicsRotation6originEv()};
let mut ret = unsafe {C_ZNK17QGraphicsRotation6originEv(rsthis.qclsinst)};
let mut ret1 = QVector3D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsRotation::setAngle(qreal );
impl /*struct*/ QGraphicsRotation {
pub fn setAngle<RetType, T: QGraphicsRotation_setAngle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAngle(self);
// return 1;
}
}
pub trait QGraphicsRotation_setAngle<RetType> {
fn setAngle(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: void QGraphicsRotation::setAngle(qreal );
impl<'a> /*trait*/ QGraphicsRotation_setAngle<()> for (f64) {
fn setAngle(self , rsthis: & QGraphicsRotation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QGraphicsRotation8setAngleEd()};
let arg0 = self as c_double;
unsafe {C_ZN17QGraphicsRotation8setAngleEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsRotation::QGraphicsRotation(QObject * parent);
impl /*struct*/ QGraphicsRotation {
pub fn new<T: QGraphicsRotation_new>(value: T) -> QGraphicsRotation {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGraphicsRotation_new {
fn new(self) -> QGraphicsRotation;
}
// proto: void QGraphicsRotation::QGraphicsRotation(QObject * parent);
impl<'a> /*trait*/ QGraphicsRotation_new for (Option<&'a QObject>) {
fn new(self) -> QGraphicsRotation {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QGraphicsRotationC2EP7QObject()};
let ctysz: c_int = unsafe{QGraphicsRotation_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN17QGraphicsRotationC2EP7QObject(arg0)};
let rsthis = QGraphicsRotation{qbase: QGraphicsTransform::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QGraphicsRotation::metaObject();
impl /*struct*/ QGraphicsRotation {
pub fn metaObject<RetType, T: QGraphicsRotation_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QGraphicsRotation_metaObject<RetType> {
fn metaObject(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: const QMetaObject * QGraphicsRotation::metaObject();
impl<'a> /*trait*/ QGraphicsRotation_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QGraphicsRotation) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QGraphicsRotation10metaObjectEv()};
let mut ret = unsafe {C_ZNK17QGraphicsRotation10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsRotation::~QGraphicsRotation();
impl /*struct*/ QGraphicsRotation {
pub fn free<RetType, T: QGraphicsRotation_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGraphicsRotation_free<RetType> {
fn free(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: void QGraphicsRotation::~QGraphicsRotation();
impl<'a> /*trait*/ QGraphicsRotation_free<()> for () {
fn free(self , rsthis: & QGraphicsRotation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QGraphicsRotationD2Ev()};
unsafe {C_ZN17QGraphicsRotationD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsRotation::setOrigin(const QVector3D & point);
impl /*struct*/ QGraphicsRotation {
pub fn setOrigin<RetType, T: QGraphicsRotation_setOrigin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setOrigin(self);
// return 1;
}
}
pub trait QGraphicsRotation_setOrigin<RetType> {
fn setOrigin(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: void QGraphicsRotation::setOrigin(const QVector3D & point);
impl<'a> /*trait*/ QGraphicsRotation_setOrigin<()> for (&'a QVector3D) {
fn setOrigin(self , rsthis: & QGraphicsRotation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QGraphicsRotation9setOriginERK9QVector3D()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN17QGraphicsRotation9setOriginERK9QVector3D(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QVector3D QGraphicsRotation::axis();
impl /*struct*/ QGraphicsRotation {
pub fn axis<RetType, T: QGraphicsRotation_axis<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.axis(self);
// return 1;
}
}
pub trait QGraphicsRotation_axis<RetType> {
fn axis(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: QVector3D QGraphicsRotation::axis();
impl<'a> /*trait*/ QGraphicsRotation_axis<QVector3D> for () {
fn axis(self , rsthis: & QGraphicsRotation) -> QVector3D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QGraphicsRotation4axisEv()};
let mut ret = unsafe {C_ZNK17QGraphicsRotation4axisEv(rsthis.qclsinst)};
let mut ret1 = QVector3D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsRotation::applyTo(QMatrix4x4 * matrix);
impl /*struct*/ QGraphicsRotation {
pub fn applyTo<RetType, T: QGraphicsRotation_applyTo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.applyTo(self);
// return 1;
}
}
pub trait QGraphicsRotation_applyTo<RetType> {
fn applyTo(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: void QGraphicsRotation::applyTo(QMatrix4x4 * matrix);
impl<'a> /*trait*/ QGraphicsRotation_applyTo<()> for (&'a QMatrix4x4) {
fn applyTo(self , rsthis: & QGraphicsRotation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QGraphicsRotation7applyToEP10QMatrix4x4()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZNK17QGraphicsRotation7applyToEP10QMatrix4x4(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsRotation::setAxis(const QVector3D & axis);
impl /*struct*/ QGraphicsRotation {
pub fn setAxis<RetType, T: QGraphicsRotation_setAxis<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAxis(self);
// return 1;
}
}
pub trait QGraphicsRotation_setAxis<RetType> {
fn setAxis(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: void QGraphicsRotation::setAxis(const QVector3D & axis);
impl<'a> /*trait*/ QGraphicsRotation_setAxis<()> for (&'a QVector3D) {
fn setAxis(self , rsthis: & QGraphicsRotation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QGraphicsRotation7setAxisERK9QVector3D()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN17QGraphicsRotation7setAxisERK9QVector3D(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QGraphicsRotation::angle();
impl /*struct*/ QGraphicsRotation {
pub fn angle<RetType, T: QGraphicsRotation_angle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.angle(self);
// return 1;
}
}
pub trait QGraphicsRotation_angle<RetType> {
fn angle(self , rsthis: & QGraphicsRotation) -> RetType;
}
// proto: qreal QGraphicsRotation::angle();
impl<'a> /*trait*/ QGraphicsRotation_angle<f64> for () {
fn angle(self , rsthis: & QGraphicsRotation) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QGraphicsRotation5angleEv()};
let mut ret = unsafe {C_ZNK17QGraphicsRotation5angleEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
impl /*struct*/ QGraphicsScale {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGraphicsScale {
return QGraphicsScale{qbase: QGraphicsTransform::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGraphicsScale {
type Target = QGraphicsTransform;
fn deref(&self) -> &QGraphicsTransform {
return & self.qbase;
}
}
impl AsRef<QGraphicsTransform> for QGraphicsScale {
fn as_ref(& self) -> & QGraphicsTransform {
return & self.qbase;
}
}
// proto: void QGraphicsScale::applyTo(QMatrix4x4 * matrix);
impl /*struct*/ QGraphicsScale {
pub fn applyTo<RetType, T: QGraphicsScale_applyTo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.applyTo(self);
// return 1;
}
}
pub trait QGraphicsScale_applyTo<RetType> {
fn applyTo(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: void QGraphicsScale::applyTo(QMatrix4x4 * matrix);
impl<'a> /*trait*/ QGraphicsScale_applyTo<()> for (&'a QMatrix4x4) {
fn applyTo(self , rsthis: & QGraphicsScale) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScale7applyToEP10QMatrix4x4()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZNK14QGraphicsScale7applyToEP10QMatrix4x4(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QGraphicsScale::zScale();
impl /*struct*/ QGraphicsScale {
pub fn zScale<RetType, T: QGraphicsScale_zScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.zScale(self);
// return 1;
}
}
pub trait QGraphicsScale_zScale<RetType> {
fn zScale(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: qreal QGraphicsScale::zScale();
impl<'a> /*trait*/ QGraphicsScale_zScale<f64> for () {
fn zScale(self , rsthis: & QGraphicsScale) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScale6zScaleEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScale6zScaleEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: qreal QGraphicsScale::xScale();
impl /*struct*/ QGraphicsScale {
pub fn xScale<RetType, T: QGraphicsScale_xScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.xScale(self);
// return 1;
}
}
pub trait QGraphicsScale_xScale<RetType> {
fn xScale(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: qreal QGraphicsScale::xScale();
impl<'a> /*trait*/ QGraphicsScale_xScale<f64> for () {
fn xScale(self , rsthis: & QGraphicsScale) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScale6xScaleEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScale6xScaleEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: qreal QGraphicsScale::yScale();
impl /*struct*/ QGraphicsScale {
pub fn yScale<RetType, T: QGraphicsScale_yScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.yScale(self);
// return 1;
}
}
pub trait QGraphicsScale_yScale<RetType> {
fn yScale(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: qreal QGraphicsScale::yScale();
impl<'a> /*trait*/ QGraphicsScale_yScale<f64> for () {
fn yScale(self , rsthis: & QGraphicsScale) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScale6yScaleEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScale6yScaleEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QGraphicsScale::setOrigin(const QVector3D & point);
impl /*struct*/ QGraphicsScale {
pub fn setOrigin<RetType, T: QGraphicsScale_setOrigin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setOrigin(self);
// return 1;
}
}
pub trait QGraphicsScale_setOrigin<RetType> {
fn setOrigin(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: void QGraphicsScale::setOrigin(const QVector3D & point);
impl<'a> /*trait*/ QGraphicsScale_setOrigin<()> for (&'a QVector3D) {
fn setOrigin(self , rsthis: & QGraphicsScale) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScale9setOriginERK9QVector3D()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScale9setOriginERK9QVector3D(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScale::setYScale(qreal );
impl /*struct*/ QGraphicsScale {
pub fn setYScale<RetType, T: QGraphicsScale_setYScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setYScale(self);
// return 1;
}
}
pub trait QGraphicsScale_setYScale<RetType> {
fn setYScale(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: void QGraphicsScale::setYScale(qreal );
impl<'a> /*trait*/ QGraphicsScale_setYScale<()> for (f64) {
fn setYScale(self , rsthis: & QGraphicsScale) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScale9setYScaleEd()};
let arg0 = self as c_double;
unsafe {C_ZN14QGraphicsScale9setYScaleEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QVector3D QGraphicsScale::origin();
impl /*struct*/ QGraphicsScale {
pub fn origin<RetType, T: QGraphicsScale_origin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.origin(self);
// return 1;
}
}
pub trait QGraphicsScale_origin<RetType> {
fn origin(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: QVector3D QGraphicsScale::origin();
impl<'a> /*trait*/ QGraphicsScale_origin<QVector3D> for () {
fn origin(self , rsthis: & QGraphicsScale) -> QVector3D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScale6originEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScale6originEv(rsthis.qclsinst)};
let mut ret1 = QVector3D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScale::setZScale(qreal );
impl /*struct*/ QGraphicsScale {
pub fn setZScale<RetType, T: QGraphicsScale_setZScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setZScale(self);
// return 1;
}
}
pub trait QGraphicsScale_setZScale<RetType> {
fn setZScale(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: void QGraphicsScale::setZScale(qreal );
impl<'a> /*trait*/ QGraphicsScale_setZScale<()> for (f64) {
fn setZScale(self , rsthis: & QGraphicsScale) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScale9setZScaleEd()};
let arg0 = self as c_double;
unsafe {C_ZN14QGraphicsScale9setZScaleEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScale::setXScale(qreal );
impl /*struct*/ QGraphicsScale {
pub fn setXScale<RetType, T: QGraphicsScale_setXScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setXScale(self);
// return 1;
}
}
pub trait QGraphicsScale_setXScale<RetType> {
fn setXScale(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: void QGraphicsScale::setXScale(qreal );
impl<'a> /*trait*/ QGraphicsScale_setXScale<()> for (f64) {
fn setXScale(self , rsthis: & QGraphicsScale) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScale9setXScaleEd()};
let arg0 = self as c_double;
unsafe {C_ZN14QGraphicsScale9setXScaleEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: const QMetaObject * QGraphicsScale::metaObject();
impl /*struct*/ QGraphicsScale {
pub fn metaObject<RetType, T: QGraphicsScale_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QGraphicsScale_metaObject<RetType> {
fn metaObject(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: const QMetaObject * QGraphicsScale::metaObject();
impl<'a> /*trait*/ QGraphicsScale_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QGraphicsScale) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScale10metaObjectEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScale10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScale::QGraphicsScale(QObject * parent);
impl /*struct*/ QGraphicsScale {
pub fn new<T: QGraphicsScale_new>(value: T) -> QGraphicsScale {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGraphicsScale_new {
fn new(self) -> QGraphicsScale;
}
// proto: void QGraphicsScale::QGraphicsScale(QObject * parent);
impl<'a> /*trait*/ QGraphicsScale_new for (Option<&'a QObject>) {
fn new(self) -> QGraphicsScale {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScaleC2EP7QObject()};
let ctysz: c_int = unsafe{QGraphicsScale_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN14QGraphicsScaleC2EP7QObject(arg0)};
let rsthis = QGraphicsScale{qbase: QGraphicsTransform::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QGraphicsScale::~QGraphicsScale();
impl /*struct*/ QGraphicsScale {
pub fn free<RetType, T: QGraphicsScale_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGraphicsScale_free<RetType> {
fn free(self , rsthis: & QGraphicsScale) -> RetType;
}
// proto: void QGraphicsScale::~QGraphicsScale();
impl<'a> /*trait*/ QGraphicsScale_free<()> for () {
fn free(self , rsthis: & QGraphicsScale) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScaleD2Ev()};
unsafe {C_ZN14QGraphicsScaleD2Ev(rsthis.qclsinst)};
// return 1;
}
}
impl /*struct*/ QGraphicsTransform {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGraphicsTransform {
return QGraphicsTransform{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGraphicsTransform {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QGraphicsTransform {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QGraphicsTransform::applyTo(QMatrix4x4 * matrix);
impl /*struct*/ QGraphicsTransform {
pub fn applyTo<RetType, T: QGraphicsTransform_applyTo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.applyTo(self);
// return 1;
}
}
pub trait QGraphicsTransform_applyTo<RetType> {
fn applyTo(self , rsthis: & QGraphicsTransform) -> RetType;
}
// proto: void QGraphicsTransform::applyTo(QMatrix4x4 * matrix);
impl<'a> /*trait*/ QGraphicsTransform_applyTo<()> for (&'a QMatrix4x4) {
fn applyTo(self , rsthis: & QGraphicsTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QGraphicsTransform7applyToEP10QMatrix4x4()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZNK18QGraphicsTransform7applyToEP10QMatrix4x4(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsTransform::~QGraphicsTransform();
impl /*struct*/ QGraphicsTransform {
pub fn free<RetType, T: QGraphicsTransform_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGraphicsTransform_free<RetType> {
fn free(self , rsthis: & QGraphicsTransform) -> RetType;
}
// proto: void QGraphicsTransform::~QGraphicsTransform();
impl<'a> /*trait*/ QGraphicsTransform_free<()> for () {
fn free(self , rsthis: & QGraphicsTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QGraphicsTransformD2Ev()};
unsafe {C_ZN18QGraphicsTransformD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsTransform::QGraphicsTransform(QObject * parent);
impl /*struct*/ QGraphicsTransform {
pub fn new<T: QGraphicsTransform_new>(value: T) -> QGraphicsTransform {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGraphicsTransform_new {
fn new(self) -> QGraphicsTransform;
}
// proto: void QGraphicsTransform::QGraphicsTransform(QObject * parent);
impl<'a> /*trait*/ QGraphicsTransform_new for (Option<&'a QObject>) {
fn new(self) -> QGraphicsTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QGraphicsTransformC2EP7QObject()};
let ctysz: c_int = unsafe{QGraphicsTransform_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN18QGraphicsTransformC2EP7QObject(arg0)};
let rsthis = QGraphicsTransform{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QGraphicsTransform::metaObject();
impl /*struct*/ QGraphicsTransform {
pub fn metaObject<RetType, T: QGraphicsTransform_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QGraphicsTransform_metaObject<RetType> {
fn metaObject(self , rsthis: & QGraphicsTransform) -> RetType;
}
// proto: const QMetaObject * QGraphicsTransform::metaObject();
impl<'a> /*trait*/ QGraphicsTransform_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QGraphicsTransform) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QGraphicsTransform10metaObjectEv()};
let mut ret = unsafe {C_ZNK18QGraphicsTransform10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
#[derive(Default)] // for QGraphicsRotation_originChanged
pub struct QGraphicsRotation_originChanged_signal{poi:u64}
impl /* struct */ QGraphicsRotation {
pub fn originChanged(&self) -> QGraphicsRotation_originChanged_signal {
return QGraphicsRotation_originChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsRotation_originChanged_signal {
pub fn connect<T: QGraphicsRotation_originChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsRotation_originChanged_signal_connect {
fn connect(self, sigthis: QGraphicsRotation_originChanged_signal);
}
#[derive(Default)] // for QGraphicsRotation_axisChanged
pub struct QGraphicsRotation_axisChanged_signal{poi:u64}
impl /* struct */ QGraphicsRotation {
pub fn axisChanged(&self) -> QGraphicsRotation_axisChanged_signal {
return QGraphicsRotation_axisChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsRotation_axisChanged_signal {
pub fn connect<T: QGraphicsRotation_axisChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsRotation_axisChanged_signal_connect {
fn connect(self, sigthis: QGraphicsRotation_axisChanged_signal);
}
#[derive(Default)] // for QGraphicsRotation_angleChanged
pub struct QGraphicsRotation_angleChanged_signal{poi:u64}
impl /* struct */ QGraphicsRotation {
pub fn angleChanged(&self) -> QGraphicsRotation_angleChanged_signal {
return QGraphicsRotation_angleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsRotation_angleChanged_signal {
pub fn connect<T: QGraphicsRotation_angleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsRotation_angleChanged_signal_connect {
fn connect(self, sigthis: QGraphicsRotation_angleChanged_signal);
}
// angleChanged()
extern fn QGraphicsRotation_angleChanged_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsRotation_angleChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsRotation_angleChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsRotation_angleChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsRotation_angleChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation12angleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsRotation_angleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsRotation_angleChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsRotation_angleChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation12angleChangedEv(arg0, arg1, arg2)};
}
}
// axisChanged()
extern fn QGraphicsRotation_axisChanged_signal_connect_cb_1(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsRotation_axisChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsRotation_axisChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsRotation_axisChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsRotation_axisChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation11axisChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsRotation_axisChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsRotation_axisChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsRotation_axisChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation11axisChangedEv(arg0, arg1, arg2)};
}
}
// originChanged()
extern fn QGraphicsRotation_originChanged_signal_connect_cb_2(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsRotation_originChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsRotation_originChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsRotation_originChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsRotation_originChanged_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation13originChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsRotation_originChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsRotation_originChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsRotation_originChanged_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsRotation_SlotProxy_connect__ZN17QGraphicsRotation13originChangedEv(arg0, arg1, arg2)};
}
}
#[derive(Default)] // for QGraphicsScale_yScaleChanged
pub struct QGraphicsScale_yScaleChanged_signal{poi:u64}
impl /* struct */ QGraphicsScale {
pub fn yScaleChanged(&self) -> QGraphicsScale_yScaleChanged_signal {
return QGraphicsScale_yScaleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScale_yScaleChanged_signal {
pub fn connect<T: QGraphicsScale_yScaleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScale_yScaleChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScale_yScaleChanged_signal);
}
#[derive(Default)] // for QGraphicsScale_xScaleChanged
pub struct QGraphicsScale_xScaleChanged_signal{poi:u64}
impl /* struct */ QGraphicsScale {
pub fn xScaleChanged(&self) -> QGraphicsScale_xScaleChanged_signal {
return QGraphicsScale_xScaleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScale_xScaleChanged_signal {
pub fn connect<T: QGraphicsScale_xScaleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScale_xScaleChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScale_xScaleChanged_signal);
}
#[derive(Default)] // for QGraphicsScale_zScaleChanged
pub struct QGraphicsScale_zScaleChanged_signal{poi:u64}
impl /* struct */ QGraphicsScale {
pub fn zScaleChanged(&self) -> QGraphicsScale_zScaleChanged_signal {
return QGraphicsScale_zScaleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScale_zScaleChanged_signal {
pub fn connect<T: QGraphicsScale_zScaleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScale_zScaleChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScale_zScaleChanged_signal);
}
#[derive(Default)] // for QGraphicsScale_scaleChanged
pub struct QGraphicsScale_scaleChanged_signal{poi:u64}
impl /* struct */ QGraphicsScale {
pub fn scaleChanged(&self) -> QGraphicsScale_scaleChanged_signal {
return QGraphicsScale_scaleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScale_scaleChanged_signal {
pub fn connect<T: QGraphicsScale_scaleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScale_scaleChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScale_scaleChanged_signal);
}
#[derive(Default)] // for QGraphicsScale_originChanged
pub struct QGraphicsScale_originChanged_signal{poi:u64}
impl /* struct */ QGraphicsScale {
pub fn originChanged(&self) -> QGraphicsScale_originChanged_signal {
return QGraphicsScale_originChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScale_originChanged_signal {
pub fn connect<T: QGraphicsScale_originChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScale_originChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScale_originChanged_signal);
}
// scaleChanged()
extern fn QGraphicsScale_scaleChanged_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsScale_scaleChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsScale_scaleChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsScale_scaleChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_scaleChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale12scaleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScale_scaleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsScale_scaleChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_scaleChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale12scaleChangedEv(arg0, arg1, arg2)};
}
}
// originChanged()
extern fn QGraphicsScale_originChanged_signal_connect_cb_1(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsScale_originChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsScale_originChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsScale_originChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_originChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13originChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScale_originChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsScale_originChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_originChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13originChangedEv(arg0, arg1, arg2)};
}
}
// zScaleChanged()
extern fn QGraphicsScale_zScaleChanged_signal_connect_cb_2(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsScale_zScaleChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsScale_zScaleChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsScale_zScaleChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_zScaleChanged_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13zScaleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScale_zScaleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsScale_zScaleChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_zScaleChanged_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13zScaleChangedEv(arg0, arg1, arg2)};
}
}
// yScaleChanged()
extern fn QGraphicsScale_yScaleChanged_signal_connect_cb_3(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsScale_yScaleChanged_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsScale_yScaleChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsScale_yScaleChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_yScaleChanged_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13yScaleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScale_yScaleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsScale_yScaleChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_yScaleChanged_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13yScaleChangedEv(arg0, arg1, arg2)};
}
}
// xScaleChanged()
extern fn QGraphicsScale_xScaleChanged_signal_connect_cb_4(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsScale_xScaleChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsScale_xScaleChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsScale_xScaleChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_xScaleChanged_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13xScaleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScale_xScaleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsScale_xScaleChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScale_xScaleChanged_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScale_SlotProxy_connect__ZN14QGraphicsScale13xScaleChangedEv(arg0, arg1, arg2)};
}
}
// <= body block end
|
// Copyright 2018 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.
// `#[macro_export] macro_rules` that doen't originate from macro expansions can be placed
// into the root module soon enough to act as usual items and shadow globs and preludes.
#![feature(decl_macro)]
// `macro_export` shadows globs
use inner1::*;
mod inner1 {
pub macro exported() {}
}
exported!();
mod deep {
fn deep() {
type Deeper = [u8; {
#[macro_export]
macro_rules! exported {
() => ( struct Б; ) //~ ERROR non-ascii idents are not fully supported
}
0
}];
}
}
// `macro_export` shadows std prelude
fn main() {
panic!();
}
mod inner3 {
#[macro_export]
macro_rules! panic {
() => ( struct Г; ) //~ ERROR non-ascii idents are not fully supported
}
}
// `macro_export` shadows builtin macros
include!();
mod inner4 {
#[macro_export]
macro_rules! include {
() => ( struct Д; ) //~ ERROR non-ascii idents are not fully supported
}
}
|
use super::server_streaming::{self, ServerStreaming};
use {Request, Response};
use protobuf::server::UnaryService;
use futures::{Future, Stream, Poll};
use tower::Service;
/// Maps to a unary gRPC service.
#[derive(Debug)]
pub struct Unary<T, S> {
inner: ServerStreaming<Inner<T>, S>,
}
pub struct ResponseFuture<T, S>
where T: UnaryService,
S: Stream,
{
inner: server_streaming::ResponseFuture<Inner<T>, S>,
}
#[derive(Debug)]
pub struct Once<T> {
inner: Option<T>,
}
/// Maps inbound requests
#[derive(Debug, Clone)]
struct Inner<T>(pub T);
struct InnerFuture<T>(T);
// ===== impl Unary =====
impl<T, S, U> Unary<T, S>
where T: UnaryService<Request = S::Item, Response = U>,
S: Stream<Error = ::Error>,
{
/// Return a new `Unary` gRPC service handler
pub fn new(inner: T) -> Self {
let inner = ServerStreaming::new(Inner(inner));
Unary { inner }
}
}
impl<T, S, U> Service for Unary<T, S>
where T: UnaryService<Request = S::Item, Response = U>,
S: Stream<Error = ::Error>,
{
type Request = Request<S>;
type Response = ::Response<Once<U>>;
type Error = ::Error;
type Future = ResponseFuture<T, S>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Service::poll_ready(&mut self.inner)
}
fn call(&mut self, request: Self::Request) -> Self::Future {
let inner = Service::call(&mut self.inner, request);
ResponseFuture { inner }
}
}
impl<T, S> Clone for Unary<T, S>
where T: Clone,
{
fn clone(&self) -> Self {
Unary { inner: self.inner.clone() }
}
}
// ===== impl Inner =====
impl<T> Service for Inner<T>
where T: UnaryService,
{
type Request = Request<T::Request>;
type Response = Response<Once<T::Response>>;
type Error = ::Error;
type Future = InnerFuture<T::Future>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.0.poll_ready()
}
fn call(&mut self, request: Self::Request) -> Self::Future {
let inner = self.0.call(request);
InnerFuture(inner)
}
}
// ===== impl ResponseFuture ======
impl<T, S, U> Future for ResponseFuture<T, S>
where T: UnaryService<Request = S::Item, Response = U>,
S: Stream<Error = ::Error>,
{
type Item = Response<Once<U>>;
type Error = ::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.inner.poll()
}
}
// ===== impl InnerFuture ======
impl<T, U> Future for InnerFuture<T>
where T: Future<Item = Response<U>, Error = ::Error> {
type Item = Response<Once<U>>;
type Error = ::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let response = try_ready!(self.0.poll());
Ok(Once::map(response).into())
}
}
// ===== impl Once =====
impl<T> Once<T> {
/// Map a response to a response of a `Once` stream
pub(super) fn map(response: Response<T>) -> Response<Self> {
// A bunch of junk to map the body type
let http = response.into_http();
let (head, body) = http.into_parts();
// Wrap with `Once`
let body = Once { inner: Some(body) };
let http = ::http::Response::from_parts(head, body);
Response::from_http(http)
}
}
impl<T> Stream for Once<T> {
type Item = T;
type Error = ::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
Ok(self.inner.take().into())
}
}
|
use proconio::marker::Chars;
fn main(){
proconio::input!{s:Chars};
println!("{}",if s[2] == s[3] && s[4] == s[5]{"Yes"}else{"No"})
} |
extern crate dialoguer;
use dialoguer::theme::ColoredTheme;
use dialoguer::{Input, KeyPrompt};
fn main() {
let rv = KeyPrompt::with_theme(&ColoredTheme::default())
.with_text("Do you want to continue?")
.items(&['y', 'n', 'p'])
.default(1)
.interact()
.unwrap();
if rv == 'y' {
println!("Looks like you want to continue");
} else {
println!("nevermind then :(");
return;
}
let input: String = Input::new().with_prompt("Your name").interact().unwrap();
println!("Hello {}!", input);
}
|
use self::HorizontalAlignment::*;
use crate::cell::*;
use std::cmp::*;
use std::fmt::*;
use std::marker::PhantomData;
use std::ops::Deref;
use unicode_width::UnicodeWidthStr;
/// A data structure that can be formatted into cells.
///
/// The number of columns must be statically determined from the type.
///
/// If the number of columns is dynamically determined, [`GridSchema`] must be used. See [`grid_schema`] for details.
pub trait CellsSource {
/// Define columns. see [`CellsFormatter`] for details.
fn fmt(f: &mut CellsFormatter<&Self>);
}
impl CellsSource for () {
fn fmt(_: &mut CellsFormatter<&Self>) {}
}
impl<T: ?Sized + CellsSource> CellsSource for &T {
fn fmt(f: &mut CellsFormatter<&Self>) {
T::fmt(&mut f.map(|x| **x));
}
}
impl<T: ?Sized + CellsSource> CellsSource for &mut T {
fn fmt(f: &mut CellsFormatter<&Self>) {
T::fmt(&mut f.map(|x| **x as &T));
}
}
impl<T: CellsSource, const N: usize> CellsSource for [T; N] {
fn fmt(f: &mut CellsFormatter<&Self>) {
for i in 0..N {
f.column(i, |x| &x[i]);
}
}
}
impl<T: CellsSource> CellsSource for Option<T> {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.filter_map(|x| x.as_ref()).content(|x| *x)
}
}
impl<T: CellsSource, E: CellSource> CellsSource for std::result::Result<T, E> {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.ok_with(|f| f.content(|&x| x))
}
}
/// Column definitions.
///
/// Define columns using [`CellsFormatter`].
///
/// To dynamically create a `GridSchema`, use [`grid_schema`].
///
/// # Examples
/// ```
/// use text_grid::*;
///
/// struct MyGridSchema {
/// len: usize,
/// }
///
/// impl GridSchema for MyGridSchema {
/// type Source = [u32];
/// fn fmt(&self, f: &mut CellsFormatter<&[u32]>) {
/// for i in 0..self.len {
/// f.column(i, |s| s[i]);
/// }
/// }
/// }
///
/// let mut g = Grid::new_with_schema(MyGridSchema { len: 3 });
/// g.push(&[1, 2, 3]);
/// g.push(&[4, 5, 6]);
///
/// assert_eq!(format!("\n{g}"), r#"
/// 0 | 1 | 2 |
/// ---|---|---|
/// 1 | 2 | 3 |
/// 4 | 5 | 6 |
/// "#);
/// ```
pub trait GridSchema {
type Source: ?Sized;
/// Define column information. see [`CellsFormatter`] for details.
fn fmt(&self, f: &mut CellsFormatter<&Self::Source>);
}
impl<T: GridSchema> GridSchema for Vec<T> {
type Source = T::Source;
fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
for s in self {
s.fmt(f);
}
}
}
impl<T: GridSchema> GridSchema for [T] {
type Source = T::Source;
fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
for s in self {
s.fmt(f);
}
}
}
impl<T: ?Sized + GridSchema> GridSchema for &T {
type Source = T::Source;
fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
T::fmt(self, f)
}
}
/// [`GridSchema`] implementation that use [`CellsSource`].
#[derive(Clone, Copy, Debug)]
pub struct DefaultGridSchema<T: ?Sized>(PhantomData<T>);
impl<T: CellsSource + ?Sized> Default for DefaultGridSchema<T> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<T: CellsSource + ?Sized> GridSchema for DefaultGridSchema<T> {
type Source = T;
fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
T::fmt(f);
}
}
/// Create [`GridSchema`] from closure.
///
/// # Examples
///
/// By calculating the number of columns at runtime and creating a schema,
/// it is possible to create tables where the number of columns cannot be obtained statically.
///
/// ```rust
/// use text_grid::*;
/// let rows = vec![vec![1, 2, 3], vec![1, 2], vec![1, 2, 3, 4]];
/// let max_colunm_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
/// let schema = grid_schema::<Vec<u32>>(move |f| {
/// for i in 0..max_colunm_count {
/// f.column(i, |x| x.get(i));
/// }
/// });
/// let mut g = Grid::new_with_schema(schema);
/// g.extend(rows);
/// assert_eq!(format!("\n{g}"), OUTPUT);
///
/// const OUTPUT: &str = r"
/// 0 | 1 | 2 | 3 |
/// ---|---|---|---|
/// 1 | 2 | 3 | |
/// 1 | 2 | | |
/// 1 | 2 | 3 | 4 |
/// ";
/// ```
pub fn grid_schema<T: ?Sized>(
fmt: impl Fn(&mut CellsFormatter<&T>),
) -> impl GridSchema<Source = T> {
struct FnGridSchema<T: ?Sized, F> {
fmt: F,
_phantom: PhantomData<fn(&mut CellsFormatter<&T>)>,
}
impl<T: ?Sized, F: Fn(&mut CellsFormatter<&T>)> GridSchema for FnGridSchema<T, F> {
type Source = T;
fn fmt(&self, f: &mut CellsFormatter<&T>) {
(self.fmt)(f)
}
}
FnGridSchema {
fmt,
_phantom: PhantomData,
}
}
/// Used to define columns.
///
/// - Use [`column`](Self::column) to create column.
/// - Use [`column_with`](Self::column_with) to create multi level header.
/// - Use [`content`](Self::content) to create shared header columns.
pub struct CellsFormatter<'a, T> {
w: &'a mut dyn CellsWrite,
d: Option<T>,
}
impl<'a, T> CellsFormatter<'a, T> {
/// Define column group. Used to create multi row header.
///
/// - header : Column group header's cell. If horizontal alignment is not specified, it is set to the center.
/// - f : A function to define columns in the group.
///
/// # Examples
///
/// ```
/// use text_grid::*;
/// struct RowData {
/// a: u32,
/// b_1: u32,
/// b_2: u32,
/// }
/// impl CellsSource for RowData {
/// fn fmt(f: &mut CellsFormatter<&Self>) {
/// f.column("a", |s| s.a);
/// f.column_with("b", |f| {
/// f.column("1", |s| s.b_1);
/// f.column("2", |s| s.b_2);
/// });
/// }
/// }
///
/// let mut g = Grid::new();
/// g.push(&RowData {
/// a: 300,
/// b_1: 10,
/// b_2: 20,
/// });
/// g.push(&RowData {
/// a: 300,
/// b_1: 1,
/// b_2: 500,
/// });
/// assert_eq!(format!("\n{g}"), r#"
/// a | b |
/// -----|----------|
/// | 1 | 2 |
/// -----|----|-----|
/// 300 | 10 | 20 |
/// 300 | 1 | 500 |
/// "#);
/// ```
pub fn column_with(&mut self, header: impl CellSource, f: impl FnOnce(&mut CellsFormatter<T>)) {
self.w.column_start();
f(self);
self.w.column_end(&header);
}
/// Define column content. Used to create shared header column.
///
/// - f : A function to obtain cells.
///
/// # Examples
///
/// ```
/// use text_grid::*;
/// struct RowData {
/// a: u32,
/// b_1: u32,
/// b_2: u32,
/// }
/// impl CellsSource for RowData {
/// fn fmt(f: &mut CellsFormatter<&Self>) {
/// f.column("a", |s| s.a);
/// f.column_with("b", |f| {
/// f.content(|s| s.b_1);
/// f.content(|_| " ");
/// f.content(|s| s.b_2);
/// });
/// }
/// }
///
/// let mut g = Grid::new();
/// g.push(&RowData {
/// a: 300,
/// b_1: 10,
/// b_2: 20,
/// });
/// g.push(&RowData {
/// a: 300,
/// b_1: 1,
/// b_2: 500,
/// });
/// assert_eq!(format!("\n{g}"), r#"
/// a | b |
/// -----|--------|
/// 300 | 10 20 |
/// 300 | 1 500 |
/// "#);
/// ```
pub fn content<U: CellsSource>(&mut self, f: impl FnOnce(&T) -> U) {
U::fmt(&mut self.map(f).as_ref())
}
/// Define column content.
///
/// - f : A function to obtain cell.
pub(crate) fn content_cell<U: CellSource>(&mut self, f: impl FnOnce(&T) -> U) {
self.w.content(
self.d
.as_ref()
.map(f)
.as_ref()
.map(|x| x as &dyn CellSource),
);
}
/// Define column.
///
/// - header : Column header's cell. If horizontal alignment is not specified, it is set to the center.
/// - f : A function to obtain cell.
///
/// # Examples
///
/// ```
/// use text_grid::*;
/// struct RowData {
/// a: u32,
/// b: u32,
/// }
/// impl CellsSource for RowData {
/// fn fmt(f: &mut CellsFormatter<&Self>) {
/// f.column("a", |s| s.a);
/// f.column("b", |s| s.b);
/// }
/// }
///
/// let mut g = Grid::new();
/// g.push(&RowData { a: 300, b: 1 });
/// g.push(&RowData { a: 2, b: 200 });
/// assert_eq!(format!("\n{g}"), r#"
/// a | b |
/// -----|-----|
/// 300 | 1 |
/// 2 | 200 |
/// "#);
/// ```
pub fn column<U: CellsSource>(&mut self, header: impl CellSource, f: impl FnOnce(&T) -> U) {
self.column_with(header, |cf| cf.content(f));
}
/// Creates a [`CellsFormatter`] whose source value was converted.
pub fn map<'x, U: 'x>(&'x mut self, f: impl FnOnce(&T) -> U) -> CellsFormatter<'x, U> {
CellsFormatter {
w: self.w,
d: self.d.as_ref().map(f),
}
}
/// Creates a [`CellsFormatter`] whose source value was converted to reference.
pub fn as_ref(&mut self) -> CellsFormatter<&T> {
CellsFormatter {
w: self.w,
d: self.d.as_ref(),
}
}
/// Creates a [`CellsFormatter`] that outputs the body cell only when the source value satisfies the condition.
pub fn filter(&mut self, f: impl FnOnce(&T) -> bool) -> CellsFormatter<&T> {
CellsFormatter {
w: self.w,
d: self.d.as_ref().filter(|data| f(data)),
}
}
/// Creates a [`CellsFormatter`] that both filters and maps.
pub fn filter_map<'x, U: 'x>(
&'x mut self,
f: impl FnOnce(&T) -> Option<U>,
) -> CellsFormatter<'x, U> {
CellsFormatter {
w: self.w,
d: self.d.as_ref().and_then(f),
}
}
/// Apply `f` to self.
pub fn with(&mut self, f: impl Fn(&mut Self)) {
f(self);
}
}
impl<T, E: CellSource> CellsFormatter<'_, std::result::Result<T, E>> {
/// If `Ok`, output the cells defined by `f`. If `Err`, output the cell by the error value using the colspan of the cells output by `f`.
pub fn ok_with(&mut self, f: impl FnOnce(&mut CellsFormatter<&T>)) {
if let Some(Err(_)) = &self.d {
self.w.content_start();
}
f(&mut self.as_ref().filter_map(|&x| x.as_ref().ok()));
if let Some(Err(e)) = &self.d {
self.w.content_end(e);
}
}
}
impl<T, E: CellSource> CellsFormatter<'_, &'_ std::result::Result<T, E>> {
/// If `Ok`, output the cells defined by `f`. If `Err`, output the cell by the error value using the colspan of the cells output by `f`.
pub fn ok_with(&mut self, f: impl FnOnce(&mut CellsFormatter<&T>)) {
if let Some(Err(_)) = &self.d {
self.w.content_start();
}
f(&mut self.as_ref().filter_map(|&x| x.as_ref().ok()));
if let Some(Err(e)) = &self.d {
self.w.content_end(e);
}
}
}
trait CellsWrite {
fn content(&mut self, cell: Option<&dyn CellSource>);
fn content_start(&mut self);
fn content_end(&mut self, cell: &dyn CellSource);
fn column_start(&mut self);
fn column_end(&mut self, header: &dyn CellSource);
}
pub(crate) struct GridLayout {
pub depth: usize,
pub depth_max: usize,
pub separators: Vec<bool>,
}
impl GridLayout {
pub fn from_schema<T: ?Sized>(schema: &dyn GridSchema<Source = T>) -> Self {
let mut this = GridLayout::new();
schema.fmt(&mut CellsFormatter {
w: &mut this,
d: None,
});
this.separators.pop();
this
}
fn new() -> Self {
Self {
depth: 0,
depth_max: 0,
separators: Vec::new(),
}
}
fn set_separator(&mut self) {
if let Some(last) = self.separators.last_mut() {
*last = true;
}
}
}
impl CellsWrite for GridLayout {
fn content(&mut self, _cell: Option<&dyn CellSource>) {
self.separators.push(false);
}
fn content_start(&mut self) {}
fn content_end(&mut self, _cell: &dyn CellSource) {}
fn column_start(&mut self) {
self.set_separator();
self.depth += 1;
self.depth_max = max(self.depth_max, self.depth);
}
fn column_end(&mut self, _header: &dyn CellSource) {
self.depth -= 1;
self.set_separator()
}
}
struct HeaderWriter<'a, 'b> {
b: &'a mut RowBuilder<'b>,
depth: usize,
target: usize,
column: usize,
column_last: usize,
}
impl<'a, 'b> HeaderWriter<'a, 'b> {
fn new(b: &'a mut RowBuilder<'b>, target: usize) -> Self {
Self {
b,
depth: 0,
target,
column: 0,
column_last: 0,
}
}
fn push_cell(&mut self, cell: impl CellSource) {
let colspan = self.column - self.column_last;
self.b.push_with_colspan(cell, colspan);
self.column_last = self.column;
}
}
impl CellsWrite for HeaderWriter<'_, '_> {
fn content(&mut self, _cell: Option<&dyn CellSource>) {
self.column += 1;
}
fn content_start(&mut self) {}
fn content_end(&mut self, _cell: &dyn CellSource) {}
fn column_start(&mut self) {
if self.depth <= self.target {
self.push_cell(Cell::empty());
}
self.depth += 1;
}
fn column_end(&mut self, header: &dyn CellSource) {
self.depth -= 1;
if self.depth == self.target {
let style = CellStyle {
align_h: Some(HorizontalAlignment::Center),
};
let header = Cell::new(header).with_base_style(style);
self.push_cell(header);
}
}
}
impl Drop for HeaderWriter<'_, '_> {
fn drop(&mut self) {
self.push_cell("");
}
}
struct BodyWriter<'a, 'b> {
b: &'a mut RowBuilder<'b>,
colspan: Option<usize>,
}
impl<'a, 'b> BodyWriter<'a, 'b> {
fn new(b: &'a mut RowBuilder<'b>) -> Self {
Self { b, colspan: None }
}
}
impl CellsWrite for BodyWriter<'_, '_> {
fn content(&mut self, cell: Option<&dyn CellSource>) {
if let Some(colspan) = &mut self.colspan {
*colspan += 1;
} else {
self.b.push(cell);
}
}
fn content_start(&mut self) {
assert!(self.colspan.is_none());
self.colspan = Some(0);
}
fn content_end(&mut self, cell: &dyn CellSource) {
let colspan = self.colspan.take().unwrap();
self.b.push_with_colspan(cell, colspan);
}
fn column_start(&mut self) {}
fn column_end(&mut self, _header: &dyn CellSource) {}
}
/// A builder used to create plain-text table.
///
/// # Examples
/// ```rust
/// use text_grid::*;
/// let mut g = GridBuilder::new();
/// g.push(|b| {
/// b.push(cell("name").right());
/// b.push("type");
/// b.push("value");
/// });
/// g.push_separator();
/// g.push(|b| {
/// b.push(cell(String::from("X")).right());
/// b.push("A");
/// b.push(10);
/// });
/// g.push(|b| {
/// b.push(cell("Y").right());
/// b.push_with_colspan(cell("BBB").center(), 2);
/// });
/// assert_eq!(format!("\n{g}"), r#"
/// name | type | value |
/// ------|------|-------|
/// X | A | 10 |
/// Y | BBB |
/// "#);
/// ```
#[derive(Default)]
pub struct GridBuilder {
s: String,
cells: Vec<CellEntry>,
rows: Vec<RowEntry>,
columns: usize,
column_separators: Vec<bool>,
}
struct CellEntry {
s_idx: usize,
width: usize,
colspan: usize,
style: CellStyle,
}
struct RowEntry {
cells_idx: usize,
has_separator: bool,
}
impl GridBuilder {
/// Create a new `GridBuilder`.
pub fn new() -> Self {
GridBuilder {
s: String::new(),
cells: Vec::new(),
rows: Vec::new(),
columns: 0,
column_separators: Vec::new(),
}
}
pub(crate) fn new_with_header<T: ?Sized>(schema: &dyn GridSchema<Source = T>) -> Self {
let mut this = Self::new();
let layout = GridLayout::from_schema(schema);
this.set_column_separators(layout.separators);
for target in 0..layout.depth_max {
this.push(|b| {
schema.fmt(&mut CellsFormatter {
w: &mut HeaderWriter::new(b, target),
d: None,
})
});
this.push_separator();
}
this
}
/// Set column separator's visibility.
///
/// `separators[0]` indicate visibility of the right side of the leftmost column.
///
/// # Examples
///
/// ```rust
/// use text_grid::*;
/// let mut g = GridBuilder::new();
/// g.push(|b| {
/// b.push("A");
/// b.push("B");
/// b.push("C");
/// });
/// g.push(|b| {
/// b.push("AAA");
/// b.push("BBB");
/// b.push("CCC");
/// });
/// g.set_column_separators(vec![true, true]);
/// assert_eq!(format!("\n{g}"), r#"
/// A | B | C |
/// AAA | BBB | CCC |
/// "#);
///
/// g.set_column_separators(vec![false, true]);
/// assert_eq!(format!("\n{g}"), r#"
/// A B | C |
/// AAABBB | CCC |
/// "#);
pub fn set_column_separators(&mut self, separators: Vec<bool>) {
self.column_separators = separators;
}
/// Append a row to the bottom of the grid.
pub fn push(&mut self, f: impl FnOnce(&mut RowBuilder)) {
let cells_idx = self.cells.len();
f(&mut RowBuilder {
grid: self,
cells_idx,
})
}
/// Append a row separator to the bottom of the grid.
pub fn push_separator(&mut self) {
if let Some(row) = self.rows.last_mut() {
row.has_separator = true;
}
}
fn push_cell<S: CellSource>(&mut self, cell: S, colspan: usize) {
let s_idx = self.s.len();
cell.fmt(&mut self.s);
self.cells.push(CellEntry {
s_idx,
width: self.s[s_idx..].width(),
colspan,
style: cell.style().or(cell.style_for_body()),
});
}
fn get_width(&self, widths: &[usize], column: usize, colspan: usize) -> usize {
assert!(colspan >= 1);
let mut result = widths[column];
for i in 1..colspan {
if self.has_border(column + i) {
result += 3;
}
result += widths[column + i];
}
result
}
fn has_border(&self, n: usize) -> bool {
if n == 0 {
false
} else if n == self.columns {
true
} else if let Some(&value) = self.column_separators.get(n - 1) {
value
} else {
true
}
}
fn has_left_padding(&self, n: usize) -> bool {
if n == 0 {
true
} else {
self.has_border(n)
}
}
fn has_right_padding(&self, n: usize) -> bool {
if n == self.columns {
true
} else {
self.has_border(n + 1)
}
}
fn get_widths(&self) -> Vec<usize> {
let mut widths = vec![0; self.columns];
for row in 0..self.rows.len() {
for c in self.row(row) {
if c.colspan == 1 {
widths[c.column] = max(widths[c.column], c.width);
}
}
}
let mut smalls = Vec::new();
for row in 0..self.rows.len() {
for c in self.row(row) {
if c.colspan > 1 {
let mut width_sum = self.get_width(&widths, c.column, c.colspan);
while width_sum < c.width {
smalls.clear();
smalls.push(0);
let mut min_width = widths[c.column];
let mut next_width = usize::max_value();
for i in 1..c.colspan {
let width = widths[c.column + i];
if width < min_width {
smalls.clear();
next_width = min_width;
min_width = width;
}
if width == min_width {
smalls.push(i);
}
}
for i in 0..smalls.len() {
let count = smalls.len() - i;
let expand_width_all = c.width - width_sum;
let expand_width = (expand_width_all + count - 1) / count;
let expand_width = min(expand_width, next_width - min_width);
width_sum += expand_width;
widths[c.column + smalls[i]] += expand_width;
}
}
}
}
}
widths
}
fn row(&self, row: usize) -> Cursor {
Cursor {
grid: self,
column: 0,
idx: self.cells_idx(row),
end: self.cells_idx(row + 1),
}
}
fn cells_idx(&self, row: usize) -> usize {
if let Some(row) = self.rows.get(row) {
row.cells_idx
} else {
self.cells.len()
}
}
fn s_idx(&self, cells_idx: usize) -> usize {
if let Some(cell) = self.cells.get(cells_idx) {
cell.s_idx
} else {
self.s.len()
}
}
}
impl Display for GridBuilder {
fn fmt(&self, f: &mut Formatter) -> Result {
let widths = self.get_widths();
for row in 0..self.rows.len() {
if self.has_border(0) {
write!(f, "|")?;
}
for c in self.row(row) {
let width = self.get_width(&widths, c.column, c.colspan);
if self.has_left_padding(c.column) {
write!(f, " ")?;
}
let p = width - c.width;
match c.style.align_h.unwrap_or(Left) {
Left => write!(f, "{0}{1:<p$}", c.s, "", p = p),
Right => write!(f, "{1:<p$}{0}", c.s, "", p = p),
Center => {
let lp = p / 2;
let rp = p - lp;
write!(f, "{1:<lp$}{0}{1:<rp$}", c.s, "", lp = lp, rp = rp)
}
}?;
if self.has_right_padding(c.column + c.colspan - 1) {
write!(f, " ")?;
}
if self.has_border(c.column + c.colspan) {
write!(f, "|")?;
}
}
writeln!(f)?;
if self.rows[row].has_separator {
let mut cs = [self.row(row), self.row(row + 1)];
for (column, _) in widths.iter().enumerate() {
if self.has_left_padding(column) {
write!(f, "-")?;
}
write!(f, "{:-<f$}", "", f = widths[column])?;
if self.has_right_padding(column) {
write!(f, "-")?;
}
for c in cs.iter_mut() {
while c.column <= column && c.next().is_some() {}
}
if self.has_border(column + 1) {
if cs.iter().all(|x| x.column == column + 1) {
write!(f, "|")?;
} else {
write!(f, "-")?;
}
}
}
writeln!(f)?;
}
}
Ok(())
}
}
impl Debug for GridBuilder {
fn fmt(&self, f: &mut Formatter) -> Result {
Display::fmt(self, f)
}
}
/// A builder used to create row of [`GridBuilder`].
///
/// This structure is created by [`GridBuilder::push`].
pub struct RowBuilder<'a> {
grid: &'a mut GridBuilder,
cells_idx: usize,
}
impl RowBuilder<'_> {
/// Append a cell to the right of row.
pub fn push(&mut self, cell: impl CellSource) {
self.grid.push_cell(cell, 1);
}
/// Append a multi-column cell to the right of row.
///
/// - `cell` : Contents of cell to be appended.
/// - `colspan` : Number of columns used by the cell to be appended.
///
/// if `colspan == 0`, this method will do nothing.
pub fn push_with_colspan(&mut self, cell: impl CellSource, colspan: usize) {
if colspan != 0 {
self.grid.push_cell(cell, colspan);
}
}
pub fn extend<T: ?Sized + CellsSource>(&mut self, source: &T) {
T::fmt(&mut CellsFormatter {
w: &mut BodyWriter::new(self),
d: Some(source),
})
}
pub fn extend_with_schema<T: ?Sized>(
&mut self,
source: &T,
schema: &dyn GridSchema<Source = T>,
) {
schema.fmt(&mut CellsFormatter {
w: &mut BodyWriter::new(self),
d: Some(source),
})
}
}
impl Drop for RowBuilder<'_> {
fn drop(&mut self) {
self.grid.columns = max(self.grid.columns, self.grid.cells.len() - self.cells_idx);
self.grid.rows.push(RowEntry {
cells_idx: self.cells_idx,
has_separator: false,
});
}
}
struct Cursor<'a> {
grid: &'a GridBuilder,
column: usize,
idx: usize,
end: usize,
}
impl<'a> Iterator for Cursor<'a> {
type Item = CellRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.idx == self.end {
None
} else {
let g = self.grid;
let r = CellRef {
cell: &g.cells[self.idx],
s: &g.s[g.s_idx(self.idx)..g.s_idx(self.idx + 1)],
column: self.column,
};
self.column += r.colspan;
self.idx += 1;
Some(r)
}
}
}
struct CellRef<'a> {
cell: &'a CellEntry,
s: &'a str,
column: usize,
}
impl<'a> Deref for CellRef<'a> {
type Target = &'a CellEntry;
fn deref(&self) -> &Self::Target {
&self.cell
}
}
macro_rules! impl_for_tuple {
($($idx:tt : $ty:ident,)*) => {
impl<$($ty),*> CellsSource for ($($ty,)*) where $($ty: CellsSource),* {
fn fmt(f: &mut CellsFormatter<&Self>) {
$(
$ty::fmt(&mut f.map(|x| &x.$idx));
)*
}
}
impl<$($ty),*> GridSchema for ($($ty,)*)
where
$($ty: GridSchema, $ty::Source: Sized,)*
{
type Source = ($($ty::Source,)*);
fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
$(self.$idx.fmt(&mut f.map(|&x| &x.$idx));)*
}
}
};
}
impl_for_tuple!(0: T0,);
impl_for_tuple!(0: T0, 1: T1,);
impl_for_tuple!(0: T0, 1: T1, 2: T2,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5, 6: T6,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5, 6: T6, 7: T7,);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
10: T10,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
10: T10,
11: T11,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
10: T10,
11: T11,
12: T12,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
10: T10,
11: T11,
12: T12,
13: T13,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
10: T10,
11: T11,
12: T12,
13: T13,
14: T14,
);
impl_for_tuple!(
0: T0,
1: T1,
2: T2,
3: T3,
4: T4,
5: T5,
6: T6,
7: T7,
8: T8,
9: T9,
10: T10,
11: T11,
12: T12,
13: T13,
14: T14,
15: T15,
);
|
use actix_web::{get, post, web, Error, HttpResponse};
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
// Use super here better than crate in case of restructure the mod
// e.g. move user to a service layer
use super::actions;
use super::models;
type DbPool = r2d2::Pool<ConnectionManager<MysqlConnection>>;
#[get("/users/{user_id}")]
pub(crate) async fn get_user(
pool: web::Data<DbPool>,
user_id: web::Path<i64>,
) -> Result<HttpResponse, Error> {
let user_id = user_id.into_inner();
let conn = pool.get().expect("couldn't get db connection from pool");
let user = web::block(move || actions::find_user_by_id(user_id, &conn))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
if let Some(user) = user {
Ok(HttpResponse::Ok().json(user))
} else {
let res = HttpResponse::NotFound()
.body(format!("No user found with uid: {}", user_id));
Ok(res)
}
}
#[post("/users")]
pub(crate) async fn add_user(
pool: web::Data<DbPool>,
form: web::Json<models::NewUser>,
) -> Result<HttpResponse, Error> {
let conn = pool.get().expect("couldn't get db connection from pool");
let user = web::block(move || actions::insert_new_user(form.0, &conn))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
Ok(HttpResponse::Ok().json(user))
}
|
//! `parser` contains the `Parser`, which turns a stream of `Token`s into a stream of `ASTType`s.
mod error;
pub use self::error::*;
use self::error::ParseResult::*;
use crate::ast::{ASTType, AST};
use crate::lexer::Lexer;
use crate::token::{Token, TokenType};
use std::iter::Peekable;
/// The `Parser` turns a stream of `Token`s into `AST`s.
pub struct Parser<'i> {
/// The `Lexer`, from which the `Token`s will be read.
lexer: Peekable<Lexer<'i>>,
}
impl<'i> Parser<'i> {
/// Create a new `Parser` with a `Lexer` that supplies `Token`s.
pub fn new(lexer: Lexer<'i>) -> Parser<'i> {
Parser {
lexer: lexer.peekable(),
}
}
/// Parse the next expression.
pub fn parse_expression(&mut self) -> ParseResult<AST> {
let token = match self.next_token() {
Ok(t) => t,
Err(e) => return Err(e),
Eof => return Eof,
};
let position = token.position;
let ast = match token.token {
TokenType::Integer(v) => ASTType::Integer(v),
TokenType::Identifier(ident) => ASTType::Identifier(ident),
TokenType::LeftBracket => return self.parse_function(),
// Unexpected tokens. Do not use `_` here, to cause compile errors when a new
// `TokenType` is added.
TokenType::RightBracket | TokenType::Define | TokenType::If => {
return Err(ParseError::UnexpectedToken(token))
}
};
Ok(AST { ast, position })
}
/// Peek the `TokenType` of the next `Token`.
fn peek_token_type(&mut self) -> Option<&TokenType> {
match self.lexer.peek() {
Some(Result::Ok(t)) => Some(&t.token),
_ => None,
}
}
/// Get the next `Token` in the stream.
fn next_token(&mut self) -> ParseResult<Token> {
match self.lexer.next() {
Some(Result::Ok(t)) => Ok(t),
Some(Result::Err(e)) => Err(ParseError::LexerError(e)),
None => Eof,
}
}
/// Parse a function call.
fn parse_function(&mut self) -> ParseResult<AST> {
match self.peek_token_type() {
Some(&TokenType::Identifier(_)) => self.parse_function_call(),
Some(&TokenType::If) => self.parse_if(),
Some(&TokenType::Define) => self.parse_define(),
None => Err(ParseError::UnexpectedEof {
expected: "`if`, `define`, a value, or an identifier",
}),
_ => Err(ParseError::UnexpectedToken(self.next_token().unwrap())),
}
}
/// Parse a function call expression.
fn parse_function_call(&mut self) -> ParseResult<AST> {
let name = self.next_token().unwrap();
let position = name.position;
let name = match name.token {
TokenType::Identifier(n) => n,
_ => panic!(
"parse_function_call may only be called when the next token is an identifier."
),
};
let mut arguments = Vec::new();
while self.peek_token_type() != Some(&TokenType::RightBracket) {
match self.parse_expression() {
Ok(p) => arguments.push(p),
Err(e) => return Err(e),
Eof => {
return Err(ParseError::UnexpectedEof {
expected: "function parameter or `)`",
})
}
};
}
// Expect RightBracket.
match self.peek_token_type() {
Some(&TokenType::RightBracket) => {
self.next_token();
}
None => return Err(ParseError::UnexpectedEof { expected: "`)`" }),
_ => return Err(ParseError::UnexpectedToken(self.next_token().unwrap())),
}
Ok(AST {
ast: ASTType::FunctionCall { name, arguments },
position,
})
}
/// Parse an if expression.
fn parse_if(&mut self) -> ParseResult<AST> {
let if_token = self.next_token().unwrap();
assert_eq!(if_token.token, TokenType::If);
let position = if_token.position;
let condition = match self.parse_expression() {
Ok(v) => Box::new(v),
Err(e) => return Err(e),
Eof => {
return Err(ParseError::UnexpectedEof {
expected: "condition in if expression",
})
}
};
let consequence = match self.parse_expression() {
Ok(v) => Box::new(v),
Err(e) => return Err(e),
Eof => {
return Err(ParseError::UnexpectedEof {
expected: "consequence in if expression",
})
}
};
let alternative = match self.parse_expression() {
Ok(v) => Box::new(v),
Err(e) => return Err(e),
Eof => {
return Err(ParseError::UnexpectedEof {
expected: "alternative in if expression",
})
}
};
// Next token must be a right bracket.
let right_bracket = match self.next_token() {
Ok(t) => t,
Err(e) => return Err(e),
Eof => return Err(ParseError::UnexpectedEof { expected: "`)`" }),
};
match right_bracket.token {
TokenType::RightBracket => {}
_ => return Err(ParseError::UnexpectedToken(right_bracket)),
}
Ok(AST {
ast: ASTType::If {
condition,
consequence,
alternative,
},
position,
})
}
/// Parse a define expression.
fn parse_define(&mut self) -> ParseResult<AST> {
let define_token = self.next_token().unwrap();
assert_eq!(define_token.token, TokenType::Define);
let position = define_token.position;
let (name, arguments) = match self.parse_expression() {
Ok(AST {
ast: ASTType::FunctionCall { name, arguments },
..
}) => {
let mut identifiers = Vec::new();
for parameter in arguments {
match parameter {
AST {
ast: ASTType::Identifier(p),
..
} => identifiers.push(p),
expr => return Err(ParseError::UnexpectedExpression(expr)),
}
}
(name, Some(identifiers))
}
Ok(AST {
ast: ASTType::Identifier(name),
..
}) => (name, None),
Ok(expr) => return Err(ParseError::UnexpectedExpression(expr)),
e => return e,
};
let value = match self.parse_expression() {
Ok(v) => v,
e => return e,
};
// Next token must be a right bracket.
let right_bracket = match self.next_token() {
Ok(t) => t,
Err(e) => return Err(e),
Eof => return Err(ParseError::UnexpectedEof { expected: "`)`" }),
};
match right_bracket.token {
TokenType::RightBracket => {}
_ => return Err(ParseError::UnexpectedToken(right_bracket)),
}
Ok(AST {
ast: ASTType::Define {
name,
arguments,
value: Box::new(value),
},
position,
})
}
}
impl<'i> Iterator for Parser<'i> {
type Item = Result<AST, ParseError>;
fn next(&mut self) -> Option<Result<AST, ParseError>> {
match self.parse_expression() {
Ok(v) => Some(Result::Ok(v)),
Err(e) => Some(Result::Err(e)),
Eof => None,
}
}
}
|
use super::*;
use crate::unpeek;
use crate::IResult;
mod complete {
use super::*;
use crate::error::InputError;
macro_rules! assert_parse(
($left: expr, $right: expr) => {
let res: $crate::IResult<_, _, InputError<_>> = $left;
assert_eq!(res, $right);
};
);
#[test]
fn i8_tests() {
assert_parse!(i8.parse_peek(&[0x00][..]), Ok((&b""[..], 0)));
assert_parse!(i8.parse_peek(&[0x7f][..]), Ok((&b""[..], 127)));
assert_parse!(i8.parse_peek(&[0xff][..]), Ok((&b""[..], -1)));
assert_parse!(i8.parse_peek(&[0x80][..]), Ok((&b""[..], -128)));
}
#[test]
fn be_i8_tests() {
assert_parse!(be_i8.parse_peek(&[0x00][..]), Ok((&b""[..], 0)));
assert_parse!(be_i8.parse_peek(&[0x7f][..]), Ok((&b""[..], 127)));
assert_parse!(be_i8.parse_peek(&[0xff][..]), Ok((&b""[..], -1)));
assert_parse!(be_i8.parse_peek(&[0x80][..]), Ok((&b""[..], -128)));
}
#[test]
fn be_i16_tests() {
assert_parse!(be_i16.parse_peek(&[0x00, 0x00][..]), Ok((&b""[..], 0)));
assert_parse!(
be_i16.parse_peek(&[0x7f, 0xff][..]),
Ok((&b""[..], 32_767_i16))
);
assert_parse!(be_i16.parse_peek(&[0xff, 0xff][..]), Ok((&b""[..], -1)));
assert_parse!(
be_i16.parse_peek(&[0x80, 0x00][..]),
Ok((&b""[..], -32_768_i16))
);
}
#[test]
fn be_u24_tests() {
assert_parse!(
be_u24.parse_peek(&[0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0))
);
assert_parse!(
be_u24.parse_peek(&[0x00, 0xFF, 0xFF][..]),
Ok((&b""[..], 65_535_u32))
);
assert_parse!(
be_u24.parse_peek(&[0x12, 0x34, 0x56][..]),
Ok((&b""[..], 1_193_046_u32))
);
}
#[test]
fn be_i24_tests() {
assert_parse!(
be_i24.parse_peek(&[0xFF, 0xFF, 0xFF][..]),
Ok((&b""[..], -1_i32))
);
assert_parse!(
be_i24.parse_peek(&[0xFF, 0x00, 0x00][..]),
Ok((&b""[..], -65_536_i32))
);
assert_parse!(
be_i24.parse_peek(&[0xED, 0xCB, 0xAA][..]),
Ok((&b""[..], -1_193_046_i32))
);
}
#[test]
fn be_i32_tests() {
assert_parse!(
be_i32.parse_peek(&[0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0))
);
assert_parse!(
be_i32.parse_peek(&[0x7f, 0xff, 0xff, 0xff][..]),
Ok((&b""[..], 2_147_483_647_i32))
);
assert_parse!(
be_i32.parse_peek(&[0xff, 0xff, 0xff, 0xff][..]),
Ok((&b""[..], -1))
);
assert_parse!(
be_i32.parse_peek(&[0x80, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], -2_147_483_648_i32))
);
}
#[test]
fn be_i64_tests() {
assert_parse!(
be_i64.parse_peek(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0))
);
assert_parse!(
be_i64.parse_peek(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]),
Ok((&b""[..], 9_223_372_036_854_775_807_i64))
);
assert_parse!(
be_i64.parse_peek(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]),
Ok((&b""[..], -1))
);
assert_parse!(
be_i64.parse_peek(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], -9_223_372_036_854_775_808_i64))
);
}
#[test]
fn be_i128_tests() {
assert_parse!(
be_i128.parse_peek(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00
][..]
),
Ok((&b""[..], 0))
);
assert_parse!(
be_i128.parse_peek(
&[
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff
][..]
),
Ok((
&b""[..],
170_141_183_460_469_231_731_687_303_715_884_105_727_i128
))
);
assert_parse!(
be_i128.parse_peek(
&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff
][..]
),
Ok((&b""[..], -1))
);
assert_parse!(
be_i128.parse_peek(
&[
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00
][..]
),
Ok((
&b""[..],
-170_141_183_460_469_231_731_687_303_715_884_105_728_i128
))
);
}
#[test]
fn le_i8_tests() {
assert_parse!(le_i8.parse_peek(&[0x00][..]), Ok((&b""[..], 0)));
assert_parse!(le_i8.parse_peek(&[0x7f][..]), Ok((&b""[..], 127)));
assert_parse!(le_i8.parse_peek(&[0xff][..]), Ok((&b""[..], -1)));
assert_parse!(le_i8.parse_peek(&[0x80][..]), Ok((&b""[..], -128)));
}
#[test]
fn le_i16_tests() {
assert_parse!(le_i16.parse_peek(&[0x00, 0x00][..]), Ok((&b""[..], 0)));
assert_parse!(
le_i16.parse_peek(&[0xff, 0x7f][..]),
Ok((&b""[..], 32_767_i16))
);
assert_parse!(le_i16.parse_peek(&[0xff, 0xff][..]), Ok((&b""[..], -1)));
assert_parse!(
le_i16.parse_peek(&[0x00, 0x80][..]),
Ok((&b""[..], -32_768_i16))
);
}
#[test]
fn le_u24_tests() {
assert_parse!(
le_u24.parse_peek(&[0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0))
);
assert_parse!(
le_u24.parse_peek(&[0xFF, 0xFF, 0x00][..]),
Ok((&b""[..], 65_535_u32))
);
assert_parse!(
le_u24.parse_peek(&[0x56, 0x34, 0x12][..]),
Ok((&b""[..], 1_193_046_u32))
);
}
#[test]
fn le_i24_tests() {
assert_parse!(
le_i24.parse_peek(&[0xFF, 0xFF, 0xFF][..]),
Ok((&b""[..], -1_i32))
);
assert_parse!(
le_i24.parse_peek(&[0x00, 0x00, 0xFF][..]),
Ok((&b""[..], -65_536_i32))
);
assert_parse!(
le_i24.parse_peek(&[0xAA, 0xCB, 0xED][..]),
Ok((&b""[..], -1_193_046_i32))
);
}
#[test]
fn le_i32_tests() {
assert_parse!(
le_i32.parse_peek(&[0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0))
);
assert_parse!(
le_i32.parse_peek(&[0xff, 0xff, 0xff, 0x7f][..]),
Ok((&b""[..], 2_147_483_647_i32))
);
assert_parse!(
le_i32.parse_peek(&[0xff, 0xff, 0xff, 0xff][..]),
Ok((&b""[..], -1))
);
assert_parse!(
le_i32.parse_peek(&[0x00, 0x00, 0x00, 0x80][..]),
Ok((&b""[..], -2_147_483_648_i32))
);
}
#[test]
fn le_i64_tests() {
assert_parse!(
le_i64.parse_peek(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0))
);
assert_parse!(
le_i64.parse_peek(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f][..]),
Ok((&b""[..], 9_223_372_036_854_775_807_i64))
);
assert_parse!(
le_i64.parse_peek(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]),
Ok((&b""[..], -1))
);
assert_parse!(
le_i64.parse_peek(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80][..]),
Ok((&b""[..], -9_223_372_036_854_775_808_i64))
);
}
#[test]
fn le_i128_tests() {
assert_parse!(
le_i128.parse_peek(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00
][..]
),
Ok((&b""[..], 0))
);
assert_parse!(
le_i128.parse_peek(
&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x7f
][..]
),
Ok((
&b""[..],
170_141_183_460_469_231_731_687_303_715_884_105_727_i128
))
);
assert_parse!(
le_i128.parse_peek(
&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff
][..]
),
Ok((&b""[..], -1))
);
assert_parse!(
le_i128.parse_peek(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80
][..]
),
Ok((
&b""[..],
-170_141_183_460_469_231_731_687_303_715_884_105_728_i128
))
);
}
#[test]
fn be_f32_tests() {
assert_parse!(
be_f32.parse_peek(&[0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0_f32))
);
assert_parse!(
be_f32.parse_peek(&[0x4d, 0x31, 0x1f, 0xd8][..]),
Ok((&b""[..], 185_728_380_f32))
);
}
#[test]
fn be_f64_tests() {
assert_parse!(
be_f64.parse_peek(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0_f64))
);
assert_parse!(
be_f64.parse_peek(&[0x41, 0xa6, 0x23, 0xfb, 0x10, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 185_728_392_f64))
);
}
#[test]
fn le_f32_tests() {
assert_parse!(
le_f32.parse_peek(&[0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0_f32))
);
assert_parse!(
le_f32.parse_peek(&[0xd8, 0x1f, 0x31, 0x4d][..]),
Ok((&b""[..], 185_728_380_f32))
);
}
#[test]
fn le_f64_tests() {
assert_parse!(
le_f64.parse_peek(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),
Ok((&b""[..], 0_f64))
);
assert_parse!(
le_f64.parse_peek(&[0x00, 0x00, 0x00, 0x10, 0xfb, 0x23, 0xa6, 0x41][..]),
Ok((&b""[..], 185_728_392_f64))
);
}
#[test]
fn configurable_endianness() {
use crate::binary::Endianness;
fn be_tst16(i: &[u8]) -> IResult<&[u8], u16> {
u16(Endianness::Big).parse_peek(i)
}
fn le_tst16(i: &[u8]) -> IResult<&[u8], u16> {
u16(Endianness::Little).parse_peek(i)
}
assert_eq!(be_tst16(&[0x80, 0x00]), Ok((&b""[..], 32_768_u16)));
assert_eq!(le_tst16(&[0x80, 0x00]), Ok((&b""[..], 128_u16)));
fn be_tst32(i: &[u8]) -> IResult<&[u8], u32> {
u32(Endianness::Big).parse_peek(i)
}
fn le_tst32(i: &[u8]) -> IResult<&[u8], u32> {
u32(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tst32(&[0x12, 0x00, 0x60, 0x00]),
Ok((&b""[..], 302_014_464_u32))
);
assert_eq!(
le_tst32(&[0x12, 0x00, 0x60, 0x00]),
Ok((&b""[..], 6_291_474_u32))
);
fn be_tst64(i: &[u8]) -> IResult<&[u8], u64> {
u64(Endianness::Big).parse_peek(i)
}
fn le_tst64(i: &[u8]) -> IResult<&[u8], u64> {
u64(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tst64(&[0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),
Ok((&b""[..], 1_297_142_246_100_992_000_u64))
);
assert_eq!(
le_tst64(&[0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),
Ok((&b""[..], 36_028_874_334_666_770_u64))
);
fn be_tsti16(i: &[u8]) -> IResult<&[u8], i16> {
i16(Endianness::Big).parse_peek(i)
}
fn le_tsti16(i: &[u8]) -> IResult<&[u8], i16> {
i16(Endianness::Little).parse_peek(i)
}
assert_eq!(be_tsti16(&[0x00, 0x80]), Ok((&b""[..], 128_i16)));
assert_eq!(le_tsti16(&[0x00, 0x80]), Ok((&b""[..], -32_768_i16)));
fn be_tsti32(i: &[u8]) -> IResult<&[u8], i32> {
i32(Endianness::Big).parse_peek(i)
}
fn le_tsti32(i: &[u8]) -> IResult<&[u8], i32> {
i32(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tsti32(&[0x00, 0x12, 0x60, 0x00]),
Ok((&b""[..], 1_204_224_i32))
);
assert_eq!(
le_tsti32(&[0x00, 0x12, 0x60, 0x00]),
Ok((&b""[..], 6_296_064_i32))
);
fn be_tsti64(i: &[u8]) -> IResult<&[u8], i64> {
i64(Endianness::Big).parse_peek(i)
}
fn le_tsti64(i: &[u8]) -> IResult<&[u8], i64> {
i64(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),
Ok((&b""[..], 71_881_672_479_506_432_i64))
);
assert_eq!(
le_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),
Ok((&b""[..], 36_028_874_334_732_032_i64))
);
}
}
mod partial {
use super::*;
use crate::error::ErrMode;
use crate::error::InputError;
use crate::error::Needed;
#[cfg(feature = "alloc")]
use crate::lib::std::vec::Vec;
use crate::Partial;
use crate::{
ascii::digit1 as digit,
binary::{be_u16, be_u8},
error::ErrorKind,
lib::std::str::{self, FromStr},
IResult,
};
macro_rules! assert_parse(
($left: expr, $right: expr) => {
let res: $crate::IResult<_, _, InputError<_>> = $left;
assert_eq!(res, $right);
};
);
#[test]
fn i8_tests() {
assert_parse!(
be_i8.parse_peek(Partial::new(&[0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
be_i8.parse_peek(Partial::new(&[0x7f][..])),
Ok((Partial::new(&b""[..]), 127))
);
assert_parse!(
be_i8.parse_peek(Partial::new(&[0xff][..])),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
be_i8.parse_peek(Partial::new(&[0x80][..])),
Ok((Partial::new(&b""[..]), -128))
);
assert_parse!(
be_i8.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn i16_tests() {
assert_parse!(
be_i16.parse_peek(Partial::new(&[0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
be_i16.parse_peek(Partial::new(&[0x7f, 0xff][..])),
Ok((Partial::new(&b""[..]), 32_767_i16))
);
assert_parse!(
be_i16.parse_peek(Partial::new(&[0xff, 0xff][..])),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
be_i16.parse_peek(Partial::new(&[0x80, 0x00][..])),
Ok((Partial::new(&b""[..]), -32_768_i16))
);
assert_parse!(
be_i16.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(2)))
);
assert_parse!(
be_i16.parse_peek(Partial::new(&[0x00][..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn u24_tests() {
assert_parse!(
be_u24.parse_peek(Partial::new(&[0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
be_u24.parse_peek(Partial::new(&[0x00, 0xFF, 0xFF][..])),
Ok((Partial::new(&b""[..]), 65_535_u32))
);
assert_parse!(
be_u24.parse_peek(Partial::new(&[0x12, 0x34, 0x56][..])),
Ok((Partial::new(&b""[..]), 1_193_046_u32))
);
assert_parse!(
be_u24.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(3)))
);
assert_parse!(
be_u24.parse_peek(Partial::new(&[0x00][..])),
Err(ErrMode::Incomplete(Needed::new(2)))
);
assert_parse!(
be_u24.parse_peek(Partial::new(&[0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn i24_tests() {
assert_parse!(
be_i24.parse_peek(Partial::new(&[0xFF, 0xFF, 0xFF][..])),
Ok((Partial::new(&b""[..]), -1_i32))
);
assert_parse!(
be_i24.parse_peek(Partial::new(&[0xFF, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), -65_536_i32))
);
assert_parse!(
be_i24.parse_peek(Partial::new(&[0xED, 0xCB, 0xAA][..])),
Ok((Partial::new(&b""[..]), -1_193_046_i32))
);
assert_parse!(
be_i24.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(3)))
);
assert_parse!(
be_i24.parse_peek(Partial::new(&[0x00][..])),
Err(ErrMode::Incomplete(Needed::new(2)))
);
assert_parse!(
be_i24.parse_peek(Partial::new(&[0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn i32_tests() {
assert_parse!(
be_i32.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[0x7f, 0xff, 0xff, 0xff][..])),
Ok((Partial::new(&b""[..]), 2_147_483_647_i32))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[0xff, 0xff, 0xff, 0xff][..])),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[0x80, 0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), -2_147_483_648_i32))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(4)))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[0x00][..])),
Err(ErrMode::Incomplete(Needed::new(3)))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(2)))
);
assert_parse!(
be_i32.parse_peek(Partial::new(&[0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn i64_tests() {
assert_parse!(
be_i64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
be_i64.parse_peek(Partial::new(
&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]
)),
Ok((Partial::new(&b""[..]), 9_223_372_036_854_775_807_i64))
);
assert_parse!(
be_i64.parse_peek(Partial::new(
&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]
)),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
be_i64.parse_peek(Partial::new(
&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Ok((Partial::new(&b""[..]), -9_223_372_036_854_775_808_i64))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(8)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[0x00][..])),
Err(ErrMode::Incomplete(Needed::new(7)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(6)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(5)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(4)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(3)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(2)))
);
assert_parse!(
be_i64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn i128_tests() {
assert_parse!(
be_i128.parse_peek(Partial::new(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00
][..]
)),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff
][..]
)),
Ok((
Partial::new(&b""[..]),
170_141_183_460_469_231_731_687_303_715_884_105_727_i128
))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff
][..]
)),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00
][..]
)),
Ok((
Partial::new(&b""[..]),
-170_141_183_460_469_231_731_687_303_715_884_105_728_i128
))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[][..])),
Err(ErrMode::Incomplete(Needed::new(16)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[0x00][..])),
Err(ErrMode::Incomplete(Needed::new(15)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(14)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(13)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(12)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(11)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..])),
Err(ErrMode::Incomplete(Needed::new(10)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(9)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(8)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(7)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(6)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(5)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(4)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Err(ErrMode::Incomplete(Needed::new(3)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
][..]
)),
Err(ErrMode::Incomplete(Needed::new(2)))
);
assert_parse!(
be_i128.parse_peek(Partial::new(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00
][..]
)),
Err(ErrMode::Incomplete(Needed::new(1)))
);
}
#[test]
fn le_i8_tests() {
assert_parse!(
le_i8.parse_peek(Partial::new(&[0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
le_i8.parse_peek(Partial::new(&[0x7f][..])),
Ok((Partial::new(&b""[..]), 127))
);
assert_parse!(
le_i8.parse_peek(Partial::new(&[0xff][..])),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
le_i8.parse_peek(Partial::new(&[0x80][..])),
Ok((Partial::new(&b""[..]), -128))
);
}
#[test]
fn le_i16_tests() {
assert_parse!(
le_i16.parse_peek(Partial::new(&[0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
le_i16.parse_peek(Partial::new(&[0xff, 0x7f][..])),
Ok((Partial::new(&b""[..]), 32_767_i16))
);
assert_parse!(
le_i16.parse_peek(Partial::new(&[0xff, 0xff][..])),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
le_i16.parse_peek(Partial::new(&[0x00, 0x80][..])),
Ok((Partial::new(&b""[..]), -32_768_i16))
);
}
#[test]
fn le_u24_tests() {
assert_parse!(
le_u24.parse_peek(Partial::new(&[0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
le_u24.parse_peek(Partial::new(&[0xFF, 0xFF, 0x00][..])),
Ok((Partial::new(&b""[..]), 65_535_u32))
);
assert_parse!(
le_u24.parse_peek(Partial::new(&[0x56, 0x34, 0x12][..])),
Ok((Partial::new(&b""[..]), 1_193_046_u32))
);
}
#[test]
fn le_i24_tests() {
assert_parse!(
le_i24.parse_peek(Partial::new(&[0xFF, 0xFF, 0xFF][..])),
Ok((Partial::new(&b""[..]), -1_i32))
);
assert_parse!(
le_i24.parse_peek(Partial::new(&[0x00, 0x00, 0xFF][..])),
Ok((Partial::new(&b""[..]), -65_536_i32))
);
assert_parse!(
le_i24.parse_peek(Partial::new(&[0xAA, 0xCB, 0xED][..])),
Ok((Partial::new(&b""[..]), -1_193_046_i32))
);
}
#[test]
fn le_i32_tests() {
assert_parse!(
le_i32.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
le_i32.parse_peek(Partial::new(&[0xff, 0xff, 0xff, 0x7f][..])),
Ok((Partial::new(&b""[..]), 2_147_483_647_i32))
);
assert_parse!(
le_i32.parse_peek(Partial::new(&[0xff, 0xff, 0xff, 0xff][..])),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
le_i32.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x80][..])),
Ok((Partial::new(&b""[..]), -2_147_483_648_i32))
);
}
#[test]
fn le_i64_tests() {
assert_parse!(
le_i64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
le_i64.parse_peek(Partial::new(
&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f][..]
)),
Ok((Partial::new(&b""[..]), 9_223_372_036_854_775_807_i64))
);
assert_parse!(
le_i64.parse_peek(Partial::new(
&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]
)),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
le_i64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80][..]
)),
Ok((Partial::new(&b""[..]), -9_223_372_036_854_775_808_i64))
);
}
#[test]
fn le_i128_tests() {
assert_parse!(
le_i128.parse_peek(Partial::new(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00
][..]
)),
Ok((Partial::new(&b""[..]), 0))
);
assert_parse!(
le_i128.parse_peek(Partial::new(
&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x7f
][..]
)),
Ok((
Partial::new(&b""[..]),
170_141_183_460_469_231_731_687_303_715_884_105_727_i128
))
);
assert_parse!(
le_i128.parse_peek(Partial::new(
&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff
][..]
)),
Ok((Partial::new(&b""[..]), -1))
);
assert_parse!(
le_i128.parse_peek(Partial::new(
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80
][..]
)),
Ok((
Partial::new(&b""[..]),
-170_141_183_460_469_231_731_687_303_715_884_105_728_i128
))
);
}
#[test]
fn be_f32_tests() {
assert_parse!(
be_f32.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0_f32))
);
assert_parse!(
be_f32.parse_peek(Partial::new(&[0x4d, 0x31, 0x1f, 0xd8][..])),
Ok((Partial::new(&b""[..]), 185_728_380_f32))
);
}
#[test]
fn be_f64_tests() {
assert_parse!(
be_f64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Ok((Partial::new(&b""[..]), 0_f64))
);
assert_parse!(
be_f64.parse_peek(Partial::new(
&[0x41, 0xa6, 0x23, 0xfb, 0x10, 0x00, 0x00, 0x00][..]
)),
Ok((Partial::new(&b""[..]), 185_728_392_f64))
);
}
#[test]
fn le_f32_tests() {
assert_parse!(
le_f32.parse_peek(Partial::new(&[0x00, 0x00, 0x00, 0x00][..])),
Ok((Partial::new(&b""[..]), 0_f32))
);
assert_parse!(
le_f32.parse_peek(Partial::new(&[0xd8, 0x1f, 0x31, 0x4d][..])),
Ok((Partial::new(&b""[..]), 185_728_380_f32))
);
}
#[test]
fn le_f64_tests() {
assert_parse!(
le_f64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]
)),
Ok((Partial::new(&b""[..]), 0_f64))
);
assert_parse!(
le_f64.parse_peek(Partial::new(
&[0x00, 0x00, 0x00, 0x10, 0xfb, 0x23, 0xa6, 0x41][..]
)),
Ok((Partial::new(&b""[..]), 185_728_392_f64))
);
}
#[test]
fn configurable_endianness() {
use crate::binary::Endianness;
fn be_tst16(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u16> {
u16(Endianness::Big).parse_peek(i)
}
fn le_tst16(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u16> {
u16(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tst16(Partial::new(&[0x80, 0x00])),
Ok((Partial::new(&b""[..]), 32_768_u16))
);
assert_eq!(
le_tst16(Partial::new(&[0x80, 0x00])),
Ok((Partial::new(&b""[..]), 128_u16))
);
fn be_tst32(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u32> {
u32(Endianness::Big).parse_peek(i)
}
fn le_tst32(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u32> {
u32(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tst32(Partial::new(&[0x12, 0x00, 0x60, 0x00])),
Ok((Partial::new(&b""[..]), 302_014_464_u32))
);
assert_eq!(
le_tst32(Partial::new(&[0x12, 0x00, 0x60, 0x00])),
Ok((Partial::new(&b""[..]), 6_291_474_u32))
);
fn be_tst64(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u64> {
u64(Endianness::Big).parse_peek(i)
}
fn le_tst64(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u64> {
u64(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tst64(Partial::new(&[
0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00
])),
Ok((Partial::new(&b""[..]), 1_297_142_246_100_992_000_u64))
);
assert_eq!(
le_tst64(Partial::new(&[
0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00
])),
Ok((Partial::new(&b""[..]), 36_028_874_334_666_770_u64))
);
fn be_tsti16(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, i16> {
i16(Endianness::Big).parse_peek(i)
}
fn le_tsti16(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, i16> {
i16(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tsti16(Partial::new(&[0x00, 0x80])),
Ok((Partial::new(&b""[..]), 128_i16))
);
assert_eq!(
le_tsti16(Partial::new(&[0x00, 0x80])),
Ok((Partial::new(&b""[..]), -32_768_i16))
);
fn be_tsti32(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, i32> {
i32(Endianness::Big).parse_peek(i)
}
fn le_tsti32(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, i32> {
i32(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tsti32(Partial::new(&[0x00, 0x12, 0x60, 0x00])),
Ok((Partial::new(&b""[..]), 1_204_224_i32))
);
assert_eq!(
le_tsti32(Partial::new(&[0x00, 0x12, 0x60, 0x00])),
Ok((Partial::new(&b""[..]), 6_296_064_i32))
);
fn be_tsti64(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, i64> {
i64(Endianness::Big).parse_peek(i)
}
fn le_tsti64(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, i64> {
i64(Endianness::Little).parse_peek(i)
}
assert_eq!(
be_tsti64(Partial::new(&[
0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00
])),
Ok((Partial::new(&b""[..]), 71_881_672_479_506_432_i64))
);
assert_eq!(
le_tsti64(Partial::new(&[
0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00
])),
Ok((Partial::new(&b""[..]), 36_028_874_334_732_032_i64))
);
}
#[test]
#[cfg(feature = "alloc")]
fn length_count_test() {
fn number(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u32> {
digit
.try_map(str::from_utf8)
.try_map(FromStr::from_str)
.parse_peek(i)
}
fn cnt(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, Vec<&[u8]>> {
length_count(unpeek(number), "abc").parse_peek(i)
}
assert_eq!(
cnt(Partial::new(&b"2abcabcabcdef"[..])),
Ok((Partial::new(&b"abcdef"[..]), vec![&b"abc"[..], &b"abc"[..]]))
);
assert_eq!(
cnt(Partial::new(&b"2ab"[..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
assert_eq!(
cnt(Partial::new(&b"3abcab"[..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
assert_eq!(
cnt(Partial::new(&b"xxx"[..])),
Err(ErrMode::Backtrack(error_position!(
&Partial::new(&b"xxx"[..]),
ErrorKind::Slice
)))
);
assert_eq!(
cnt(Partial::new(&b"2abcxxx"[..])),
Err(ErrMode::Backtrack(error_position!(
&Partial::new(&b"xxx"[..]),
ErrorKind::Tag
)))
);
}
#[test]
fn length_data_test() {
fn number(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u32> {
digit
.try_map(str::from_utf8)
.try_map(FromStr::from_str)
.parse_peek(i)
}
fn take(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, &[u8]> {
length_data(unpeek(number)).parse_peek(i)
}
assert_eq!(
take(Partial::new(&b"6abcabcabcdef"[..])),
Ok((Partial::new(&b"abcdef"[..]), &b"abcabc"[..]))
);
assert_eq!(
take(Partial::new(&b"3ab"[..])),
Err(ErrMode::Incomplete(Needed::new(1)))
);
assert_eq!(
take(Partial::new(&b"xxx"[..])),
Err(ErrMode::Backtrack(error_position!(
&Partial::new(&b"xxx"[..]),
ErrorKind::Slice
)))
);
assert_eq!(
take(Partial::new(&b"2abcxxx"[..])),
Ok((Partial::new(&b"cxxx"[..]), &b"ab"[..]))
);
}
#[test]
fn length_value_test() {
use crate::stream::StreamIsPartial;
fn length_value_1(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, u16> {
length_value(be_u8, be_u16).parse_peek(i)
}
fn length_value_2(i: Partial<&[u8]>) -> IResult<Partial<&[u8]>, (u8, u8)> {
length_value(be_u8, (be_u8, be_u8)).parse_peek(i)
}
let mut empty_complete = Partial::new(&b""[..]);
let _ = empty_complete.complete();
let i1 = [0, 5, 6];
assert_eq!(
length_value_1(Partial::new(&i1)),
Err(ErrMode::Backtrack(error_position!(
&empty_complete,
ErrorKind::Slice
)))
);
assert_eq!(
length_value_2(Partial::new(&i1)),
Err(ErrMode::Backtrack(error_position!(
&empty_complete,
ErrorKind::Token
)))
);
let i2 = [1, 5, 6, 3];
{
let mut middle_complete = Partial::new(&i2[1..2]);
let _ = middle_complete.complete();
assert_eq!(
length_value_1(Partial::new(&i2)),
Err(ErrMode::Backtrack(error_position!(
&middle_complete,
ErrorKind::Slice
)))
);
assert_eq!(
length_value_2(Partial::new(&i2)),
Err(ErrMode::Backtrack(error_position!(
&empty_complete,
ErrorKind::Token
)))
);
}
let i3 = [2, 5, 6, 3, 4, 5, 7];
assert_eq!(
length_value_1(Partial::new(&i3)),
Ok((Partial::new(&i3[3..]), 1286))
);
assert_eq!(
length_value_2(Partial::new(&i3)),
Ok((Partial::new(&i3[3..]), (5, 6)))
);
let i4 = [3, 5, 6, 3, 4, 5];
assert_eq!(
length_value_1(Partial::new(&i4)),
Ok((Partial::new(&i4[4..]), 1286))
);
assert_eq!(
length_value_2(Partial::new(&i4)),
Ok((Partial::new(&i4[4..]), (5, 6)))
);
}
}
|
use crate::common::types::{VertexId, Weight};
use std::collections::HashMap;
pub type ShortestPathsBF = HashMap<VertexId, Weight>;
pub type ShortestPathsFW = HashMap<(VertexId, VertexId), Weight>;
|
use std::fs;
use std::collections::HashMap;
fn main() {
let contents = fs::read_to_string("input.txt")
.expect("Failed to read file");
let mut numbers: Vec<i64> = contents.trim().split("\n").map(|n| { n.trim().parse().unwrap() }).collect();
numbers.sort();
// part 1
let mut prev_n: i64 = 0;
let mut counts = HashMap::new();
for i in 0..=numbers.len() {
let diff = if i == numbers.len() { 3 } else { numbers[i] - prev_n};
let count = counts.entry(diff).or_insert(0);
*count += 1;
if i != numbers.len() {
prev_n = numbers[i];
}
}
println!("{:?}", counts);
// part 2
let mut segments: Vec<Vec<i64>> = Vec::new();
let mut current_segment: Vec<i64> = Vec::new();
let mut prev_n: i64 = 0;
current_segment.push(0);
for n in numbers {
if n - prev_n == 3 {
if current_segment.len() > 2 {
segments.push(current_segment);
}
current_segment = Vec::new();
}
current_segment.push(n);
prev_n = n;
}
segments.push(current_segment);
let mut result: i64 = 1;
for segment in segments {
let l = segment.len() as i64 - 2;
result *= l * (l + 1) / 2 + 1;
}
println!("{:?}", result);
}
|
use crate::class::{classfile::ClassFile, constant_pool::ConstantPool, method::MethodInfo};
use ConstantPool::*;
#[derive(Debug)]
pub struct VM {
constant_pools: Vec<ConstantPool>,
}
impl From<ClassFile> for VM {
fn from(c: ClassFile) -> Self {
return Self {
constant_pools: c.constant_pools,
};
}
}
impl VM {
pub fn get_method_name(&self, method: &MethodInfo) -> &str {
match self
.constant_pools
.get(method.name_index as usize - 1)
.unwrap()
{
Utf8 { bytes, length: _ } => &bytes,
_ => unreachable!(),
}
}
pub fn exec(&mut self, methods: Vec<MethodInfo>) -> Option<&MethodInfo> {
let mut main = 0;
for (i, method) in methods.iter().enumerate() {
if dbg!(self.get_method_name(method)) == "main" {
main = i;
}
}
self.exec_method(&methods.get(main).unwrap().clone());
None
}
fn exec_method(&mut self, method: &MethodInfo) {
dbg!(method);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.