text stringlengths 8 4.13M |
|---|
use crate::parser::token::Op;
use std::convert::From;
#[derive(Clone, Copy, Debug)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
Eq,
Ne,
Gt,
Lt,
Gte,
Lte
}
impl From<Op> for BinOp {
fn from(op: Op) -> BinOp {
match op {
Op::Add => BinOp::Add,
Op::Sub => BinOp::Sub,
Op::Mul => BinOp::Mul,
Op::Div => BinOp::Div,
Op::Mod => BinOp::Mod,
Op::Eq => BinOp::Eq,
Op::Ne => BinOp::Ne,
Op::Gt => BinOp::Gt,
Op::Lt => BinOp::Lt,
Op::Gte => BinOp::Gte,
Op::Lte => BinOp::Lte,
_ => panic!("from_op:: attemp to create BinOp from non-binary Op")
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum UnaryOp {
Deref
}
impl From<Op> for UnaryOp {
fn from(op: Op) -> UnaryOp {
match op {
Op::Deref => UnaryOp::Deref,
_ => panic!("from_op: attempt to create UnaryOp from non-unary Op")
}
}
} |
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width >= other.width && self.height >= other.height
}
fn big_than(&self, other: &Rectangle) -> bool {
self.area() > other.area()
}
}
fn main() {
let rect1 = Rectangle::new(30, 50);
let rect2 = Rectangle::new(60, 40);
println!("{}", rect2.can_hold(&rect1));
println!("{}", rect2.big_than(&rect1));
}
|
use game::Game;
use text_io::read;
extern crate text_io;
mod game;
fn main() {
let mut game = Game::default();
loop {
println!("Multiplayer or Ai(M/A): ");
match read!() {
'M' | 'm' => game.run_game(),
'A' | 'a' => game.run_game_vs_ai(),
_ => {}
}
println!("Do you want to quit?(Y/N)");
match read!() {
'Y' | 'y' => break,
_ => {}
}
game.clear_board();
}
}
#[test]
fn test_negamax() {
let mut game = Game::new();
game.run_game_vs_ai();
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataLakeStoreAccount {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<EncryptionIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DataLakeStoreAccountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataLakeStoreAccountBasic {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DataLakeStoreAccountPropertiesBasic>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataLakeStoreAccountProperties {
#[serde(flatten)]
pub data_lake_store_account_properties_basic: DataLakeStoreAccountPropertiesBasic,
#[serde(rename = "defaultGroup", default, skip_serializing_if = "Option::is_none")]
pub default_group: Option<String>,
#[serde(rename = "encryptionConfig", default, skip_serializing_if = "Option::is_none")]
pub encryption_config: Option<EncryptionConfig>,
#[serde(rename = "encryptionState", default, skip_serializing_if = "Option::is_none")]
pub encryption_state: Option<data_lake_store_account_properties::EncryptionState>,
#[serde(rename = "encryptionProvisioningState", default, skip_serializing_if = "Option::is_none")]
pub encryption_provisioning_state: Option<data_lake_store_account_properties::EncryptionProvisioningState>,
#[serde(rename = "firewallRules", default, skip_serializing_if = "Vec::is_empty")]
pub firewall_rules: Vec<FirewallRule>,
#[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_network_rules: Vec<VirtualNetworkRule>,
#[serde(rename = "firewallState", default, skip_serializing_if = "Option::is_none")]
pub firewall_state: Option<data_lake_store_account_properties::FirewallState>,
#[serde(rename = "firewallAllowAzureIps", default, skip_serializing_if = "Option::is_none")]
pub firewall_allow_azure_ips: Option<data_lake_store_account_properties::FirewallAllowAzureIps>,
#[serde(rename = "trustedIdProviders", default, skip_serializing_if = "Vec::is_empty")]
pub trusted_id_providers: Vec<TrustedIdProvider>,
#[serde(rename = "trustedIdProviderState", default, skip_serializing_if = "Option::is_none")]
pub trusted_id_provider_state: Option<data_lake_store_account_properties::TrustedIdProviderState>,
#[serde(rename = "newTier", default, skip_serializing_if = "Option::is_none")]
pub new_tier: Option<data_lake_store_account_properties::NewTier>,
#[serde(rename = "currentTier", default, skip_serializing_if = "Option::is_none")]
pub current_tier: Option<data_lake_store_account_properties::CurrentTier>,
}
pub mod data_lake_store_account_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EncryptionState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EncryptionProvisioningState {
Creating,
Succeeded,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FirewallState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FirewallAllowAzureIps {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TrustedIdProviderState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NewTier {
Consumption,
#[serde(rename = "Commitment_1TB")]
Commitment1tb,
#[serde(rename = "Commitment_10TB")]
Commitment10tb,
#[serde(rename = "Commitment_100TB")]
Commitment100tb,
#[serde(rename = "Commitment_500TB")]
Commitment500tb,
#[serde(rename = "Commitment_1PB")]
Commitment1pb,
#[serde(rename = "Commitment_5PB")]
Commitment5pb,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CurrentTier {
Consumption,
#[serde(rename = "Commitment_1TB")]
Commitment1tb,
#[serde(rename = "Commitment_10TB")]
Commitment10tb,
#[serde(rename = "Commitment_100TB")]
Commitment100tb,
#[serde(rename = "Commitment_500TB")]
Commitment500tb,
#[serde(rename = "Commitment_1PB")]
Commitment1pb,
#[serde(rename = "Commitment_5PB")]
Commitment5pb,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataLakeStoreAccountPropertiesBasic {
#[serde(rename = "accountId", default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<data_lake_store_account_properties_basic::ProvisioningState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<data_lake_store_account_properties_basic::State>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
}
pub mod data_lake_store_account_properties_basic {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Failed,
Creating,
Running,
Succeeded,
Patching,
Suspending,
Resuming,
Deleting,
Deleted,
Undeleting,
Canceled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Active,
Suspended,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataLakeStoreAccountListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DataLakeStoreAccountBasic>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncryptionIdentity {
#[serde(rename = "type")]
pub type_: encryption_identity::Type,
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
pub mod encryption_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncryptionConfig {
#[serde(rename = "type")]
pub type_: encryption_config::Type,
#[serde(rename = "keyVaultMetaInfo", default, skip_serializing_if = "Option::is_none")]
pub key_vault_meta_info: Option<KeyVaultMetaInfo>,
}
pub mod encryption_config {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
UserManaged,
ServiceManaged,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultMetaInfo {
#[serde(rename = "keyVaultResourceId")]
pub key_vault_resource_id: String,
#[serde(rename = "encryptionKeyName")]
pub encryption_key_name: String,
#[serde(rename = "encryptionKeyVersion")]
pub encryption_key_version: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRule {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<FirewallRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRuleProperties {
#[serde(rename = "startIpAddress", default, skip_serializing_if = "Option::is_none")]
pub start_ip_address: Option<String>,
#[serde(rename = "endIpAddress", default, skip_serializing_if = "Option::is_none")]
pub end_ip_address: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRuleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<FirewallRule>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkRule {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VirtualNetworkRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkRuleProperties {
#[serde(rename = "subnetId", default, skip_serializing_if = "Option::is_none")]
pub subnet_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkRuleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<VirtualNetworkRule>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrustedIdProvider {
#[serde(flatten)]
pub sub_resource: SubResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<TrustedIdProviderProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrustedIdProviderProperties {
#[serde(rename = "idProvider", default, skip_serializing_if = "Option::is_none")]
pub id_provider: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrustedIdProviderListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<TrustedIdProvider>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplay>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<operation::Origin>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Origin {
#[serde(rename = "user")]
User,
#[serde(rename = "system")]
System,
#[serde(rename = "user,system")]
UserSystem,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CapabilityInformation {
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<capability_information::State>,
#[serde(rename = "maxAccountCount", default, skip_serializing_if = "Option::is_none")]
pub max_account_count: Option<i32>,
#[serde(rename = "accountCount", default, skip_serializing_if = "Option::is_none")]
pub account_count: Option<i32>,
#[serde(rename = "migrationState", default, skip_serializing_if = "Option::is_none")]
pub migration_state: Option<bool>,
}
pub mod capability_information {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Registered,
Suspended,
Deleted,
Unregistered,
Warned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageName {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Usage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<usage::Unit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")]
pub current_value: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<UsageName>,
}
pub mod usage {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Unit {
Count,
Bytes,
Seconds,
Percent,
CountsPerSecond,
BytesPerSecond,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Usage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameAvailabilityInformation {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateDataLakeStoreAccountParameters {
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<EncryptionIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CreateDataLakeStoreAccountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateDataLakeStoreAccountProperties {
#[serde(rename = "defaultGroup", default, skip_serializing_if = "Option::is_none")]
pub default_group: Option<String>,
#[serde(rename = "encryptionConfig", default, skip_serializing_if = "Option::is_none")]
pub encryption_config: Option<EncryptionConfig>,
#[serde(rename = "encryptionState", default, skip_serializing_if = "Option::is_none")]
pub encryption_state: Option<create_data_lake_store_account_properties::EncryptionState>,
#[serde(rename = "firewallRules", default, skip_serializing_if = "Vec::is_empty")]
pub firewall_rules: Vec<CreateFirewallRuleWithAccountParameters>,
#[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_network_rules: Vec<CreateVirtualNetworkRuleWithAccountParameters>,
#[serde(rename = "firewallState", default, skip_serializing_if = "Option::is_none")]
pub firewall_state: Option<create_data_lake_store_account_properties::FirewallState>,
#[serde(rename = "firewallAllowAzureIps", default, skip_serializing_if = "Option::is_none")]
pub firewall_allow_azure_ips: Option<create_data_lake_store_account_properties::FirewallAllowAzureIps>,
#[serde(rename = "trustedIdProviders", default, skip_serializing_if = "Vec::is_empty")]
pub trusted_id_providers: Vec<CreateTrustedIdProviderWithAccountParameters>,
#[serde(rename = "trustedIdProviderState", default, skip_serializing_if = "Option::is_none")]
pub trusted_id_provider_state: Option<create_data_lake_store_account_properties::TrustedIdProviderState>,
#[serde(rename = "newTier", default, skip_serializing_if = "Option::is_none")]
pub new_tier: Option<create_data_lake_store_account_properties::NewTier>,
}
pub mod create_data_lake_store_account_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EncryptionState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FirewallState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FirewallAllowAzureIps {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TrustedIdProviderState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NewTier {
Consumption,
#[serde(rename = "Commitment_1TB")]
Commitment1tb,
#[serde(rename = "Commitment_10TB")]
Commitment10tb,
#[serde(rename = "Commitment_100TB")]
Commitment100tb,
#[serde(rename = "Commitment_500TB")]
Commitment500tb,
#[serde(rename = "Commitment_1PB")]
Commitment1pb,
#[serde(rename = "Commitment_5PB")]
Commitment5pb,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateDataLakeStoreAccountParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateDataLakeStoreAccountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateDataLakeStoreAccountProperties {
#[serde(rename = "defaultGroup", default, skip_serializing_if = "Option::is_none")]
pub default_group: Option<String>,
#[serde(rename = "encryptionConfig", default, skip_serializing_if = "Option::is_none")]
pub encryption_config: Option<UpdateEncryptionConfig>,
#[serde(rename = "firewallRules", default, skip_serializing_if = "Vec::is_empty")]
pub firewall_rules: Vec<UpdateFirewallRuleWithAccountParameters>,
#[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_network_rules: Vec<UpdateVirtualNetworkRuleWithAccountParameters>,
#[serde(rename = "firewallState", default, skip_serializing_if = "Option::is_none")]
pub firewall_state: Option<update_data_lake_store_account_properties::FirewallState>,
#[serde(rename = "firewallAllowAzureIps", default, skip_serializing_if = "Option::is_none")]
pub firewall_allow_azure_ips: Option<update_data_lake_store_account_properties::FirewallAllowAzureIps>,
#[serde(rename = "trustedIdProviders", default, skip_serializing_if = "Vec::is_empty")]
pub trusted_id_providers: Vec<UpdateTrustedIdProviderWithAccountParameters>,
#[serde(rename = "trustedIdProviderState", default, skip_serializing_if = "Option::is_none")]
pub trusted_id_provider_state: Option<update_data_lake_store_account_properties::TrustedIdProviderState>,
#[serde(rename = "newTier", default, skip_serializing_if = "Option::is_none")]
pub new_tier: Option<update_data_lake_store_account_properties::NewTier>,
}
pub mod update_data_lake_store_account_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FirewallState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FirewallAllowAzureIps {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TrustedIdProviderState {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NewTier {
Consumption,
#[serde(rename = "Commitment_1TB")]
Commitment1tb,
#[serde(rename = "Commitment_10TB")]
Commitment10tb,
#[serde(rename = "Commitment_100TB")]
Commitment100tb,
#[serde(rename = "Commitment_500TB")]
Commitment500tb,
#[serde(rename = "Commitment_1PB")]
Commitment1pb,
#[serde(rename = "Commitment_5PB")]
Commitment5pb,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateEncryptionConfig {
#[serde(rename = "keyVaultMetaInfo", default, skip_serializing_if = "Option::is_none")]
pub key_vault_meta_info: Option<UpdateKeyVaultMetaInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateKeyVaultMetaInfo {
#[serde(rename = "encryptionKeyVersion", default, skip_serializing_if = "Option::is_none")]
pub encryption_key_version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateOrUpdateFirewallRuleParameters {
pub properties: CreateOrUpdateFirewallRuleProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateFirewallRuleWithAccountParameters {
pub name: String,
pub properties: CreateOrUpdateFirewallRuleProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateOrUpdateFirewallRuleProperties {
#[serde(rename = "startIpAddress")]
pub start_ip_address: String,
#[serde(rename = "endIpAddress")]
pub end_ip_address: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateFirewallRuleParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateFirewallRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateFirewallRuleWithAccountParameters {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateFirewallRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateFirewallRuleProperties {
#[serde(rename = "startIpAddress", default, skip_serializing_if = "Option::is_none")]
pub start_ip_address: Option<String>,
#[serde(rename = "endIpAddress", default, skip_serializing_if = "Option::is_none")]
pub end_ip_address: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateOrUpdateVirtualNetworkRuleParameters {
pub properties: CreateOrUpdateVirtualNetworkRuleProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateVirtualNetworkRuleWithAccountParameters {
pub name: String,
pub properties: CreateOrUpdateVirtualNetworkRuleProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateOrUpdateVirtualNetworkRuleProperties {
#[serde(rename = "subnetId")]
pub subnet_id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateVirtualNetworkRuleParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateVirtualNetworkRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateVirtualNetworkRuleWithAccountParameters {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateVirtualNetworkRuleProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateVirtualNetworkRuleProperties {
#[serde(rename = "subnetId", default, skip_serializing_if = "Option::is_none")]
pub subnet_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateOrUpdateTrustedIdProviderParameters {
pub properties: CreateOrUpdateTrustedIdProviderProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateTrustedIdProviderWithAccountParameters {
pub name: String,
pub properties: CreateOrUpdateTrustedIdProviderProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateOrUpdateTrustedIdProviderProperties {
#[serde(rename = "idProvider")]
pub id_provider: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateTrustedIdProviderParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateTrustedIdProviderProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateTrustedIdProviderWithAccountParameters {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<UpdateTrustedIdProviderProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateTrustedIdProviderProperties {
#[serde(rename = "idProvider", default, skip_serializing_if = "Option::is_none")]
pub id_provider: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityParameters {
pub name: String,
#[serde(rename = "type")]
pub type_: check_name_availability_parameters::Type,
}
pub mod check_name_availability_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "Microsoft.DataLakeStore/accounts")]
MicrosoftDataLakeStoreAccounts,
}
}
|
// avro.rs
//
// Avro Codec for primitive types
// and Avro arrays (as vectors) and Avro maps
// (as HashMap<String, T>)
// (c) 2016 James Crooks
use std::iter::Iterator;
use std::collections::HashMap;
use std::mem;
pub type ByteStream = Iterator<Item = u8>;
pub trait AvroCodec: Sized {
fn encode(&self) -> Vec<u8>;
fn decode(&mut ByteStream) -> Option<Self>;
}
impl AvroCodec for i32 {
#[inline]
fn encode(&self) -> Vec<u8> {
if *self == 0 {
return vec![0u8];
}
let mut vint = ((*self << 1) ^ (*self >> 31)) as u32;
let mut encoded = Vec::new();
while vint != 0 {
let byte = (vint | 0x80) as u8;
encoded.push(byte);
vint = vint >> 7;
}
if let Some(last) = encoded.pop() {
encoded.push(last ^ 0x80);
}
encoded
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<Self> {
let mut vint: u32 = 0;
let mut count = 0;
loop {
if let Some(byte) = bytes.next() {
vint = vint | (((byte & 0x7F) as u32) << (7 * count));
count += 1;
if byte & 0x80 == 0 {
break;
}
} else {
return None;
}
}
if vint & 0x1 == 1 {
// LSB is set => negative number
Some((vint >> 1) as i32 ^ -1i32) // flip last bit and two's complement
} else {
Some((vint >> 1) as i32)
}
}
}
impl AvroCodec for i64 {
fn encode(&self) -> Vec<u8> {
if *self == 0 {
return vec![0u8];
}
let mut vint = ((*self << 1) ^ (*self >> 63)) as u64;
let mut encoded = Vec::new();
while vint != 0 {
let byte = (vint | 0x80) as u8;
encoded.push(byte);
vint = vint >> 7;
}
if let Some(last) = encoded.pop() {
encoded.push(last ^ 0x80);
}
encoded
}
fn decode(bytes: &mut ByteStream) -> Option<i64> {
let mut vint: u64 = 0;
let mut count = 0;
loop {
if let Some(byte) = bytes.next() {
vint = vint | (((byte & 0x7F) as u64) << (7 * count));
count += 1;
if byte & 0x80 == 0 {
break;
}
} else {
return None;
}
}
if vint & 0x1 == 1 {
// LSB is set => negative number
Some((vint >> 1) as i64 ^ -1i64)
} else {
Some((vint >> 1) as i64)
}
}
}
impl AvroCodec for usize {
#[inline]
fn encode(&self) -> Vec<u8> {
(*self as i64).encode()
/*
if *self == 0 {
return vec![0u8];
}
let mut vint = *self << 1; // This drops the MSB. Better keep collections under 2^63 items!
let mut encoded = Vec::new();
while vint != 0 {
let byte = (vint | 0x80) as u8;
encoded.push(byte);
vint = vint >> 7;
}
if let Some(last) = encoded.pop() {
encoded.push(last ^ 0x80);
}
encoded
*/
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<Self> {
i32::decode(bytes).map(|x| x.abs() as usize)
}
}
impl AvroCodec for f32 {
#[inline]
fn encode(&self) -> Vec<u8> {
// Unsafe for performance
// This use is safe, since we are just turning a 4-byte
// object into an array of exactly 4 bytes
unsafe { mem::transmute::<f32, [u8; 4]>(*self).to_vec() }
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<f32> {
match (bytes.next(), bytes.next(), bytes.next(), bytes.next()) {
(Some(b1), Some(b2), Some(b3), Some(b4)) =>
Some(unsafe { mem::transmute::<[u8; 4], f32>([b1, b2, b3, b4]) }),
_ => None
}
}
}
impl AvroCodec for f64 {
#[inline]
fn encode(&self) -> Vec<u8> {
// Unsafe for performance
// This use is safe, since we are just turning an 8-byte
// object into an array of exactly 8 bytes
unsafe { mem::transmute::<f64, [u8; 8]>(*self).to_vec() }
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<f64> {
match (bytes.next(), bytes.next(), bytes.next(), bytes.next(),
bytes.next(), bytes.next(), bytes.next(), bytes.next()) {
(Some(b1), Some(b2), Some(b3), Some(b4),
Some(b5), Some(b6), Some(b7), Some(b8)) => {
Some(unsafe
{ mem::transmute::<[u8; 8], f64>([b1, b2, b3, b4, b5, b6, b7, b8])
})
},
_ => None
}
}
}
impl AvroCodec for String {
#[inline]
fn encode(&self) -> Vec<u8> {
let mut bytes = self.as_bytes().to_vec();
let mut len = bytes.len().encode();
let mut encoded: Vec<u8> = Vec::with_capacity(bytes.len() + len.len());
encoded.append(&mut len);
encoded.append(&mut bytes);
encoded
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<Self> {
let len = if let Some(len) = usize::decode(bytes) {
len
} else {
return None;
};
let strdata: Vec<u8> = bytes.take(len).collect();
if strdata.len() < len {
return None;
}
String::from_utf8(strdata).ok()
}
}
impl AvroCodec for bool {
fn encode(&self) -> Vec<u8> {
match *self {
true => vec![0x1],
false => vec![0x0]
}
}
fn decode(bytes: &mut ByteStream) -> Option<bool> {
match bytes.next() {
Some(0u8) => Some(false),
Some(1u8) => Some(true),
_ => None
}
}
}
impl AvroCodec for u8 {
fn encode(&self) -> Vec<u8> {
vec![*self]
}
fn decode(bytes: &mut ByteStream) -> Option<u8> {
bytes.next()
}
}
impl<T> AvroCodec for Vec<T> where T: AvroCodec {
#[inline]
fn encode(&self) -> Vec<u8> {
let mut encoded = Vec::new();
encoded.append(&mut self.len().encode());
self.iter().fold(encoded, |mut acc, item| {
let mut encoded = item.encode();
acc.append(&mut encoded);
acc
})
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<Self> {
let mut len = if let Some(len) = usize::decode(bytes) {
len
} else {
return None;
};
let mut ret = Vec::with_capacity(len);
while len > 0 {
if let Some(elem) = T::decode(bytes) {
ret.push(elem);
} else {
return None;
}
len -= 1;
}
Some(ret)
}
}
impl <T> AvroCodec for HashMap<String, T> where T: AvroCodec {
#[inline]
fn encode(&self) -> Vec<u8> {
if self.is_empty() {
return vec![0x0];
}
let mut encoded = Vec::new();
encoded.append(&mut self.len().encode());
for (key, value) in self.iter() {
encoded.append(&mut key.encode());
encoded.append(&mut value.encode());
}
encoded.push(0x0u8);
encoded
}
#[inline]
fn decode(bytes: &mut ByteStream) -> Option<Self> {
let mut len = match usize::decode(bytes) {
Some(0) => return Some(HashMap::new()),
Some(len) => len,
None => return None,
};
let mut decoded = HashMap::with_capacity(len);
while len > 0 {
match (String::decode(bytes), T::decode(bytes)) {
(Some(key), Some(value)) => decoded.insert(key, value),
_ => return None,
};
len -= 1;
}
Some(decoded)
}
}
#[cfg(test)]
mod tests {
pub use super::AvroCodec;
use std::{f32, f64};
use std::collections::HashMap;
#[test]
fn test_i32_codec() {
assert_eq!(0i32.encode(), vec![0u8]);
assert_eq!(1i32.encode(), vec![2u8]);
assert_eq!((-1i32).encode(), vec![1u8]);
assert_eq!(i32::max_value().encode(),
vec![0xFE, 0xFF, 0xFF, 0xFF, 0x0F]);
assert_eq!(i32::min_value().encode(),
vec![0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
assert_eq!(i32::max_value(),
i32::decode(&mut i32::max_value()
.encode()
.into_iter()).unwrap());
assert_eq!(i32::min_value(),
i32::decode(&mut i32::min_value()
.encode()
.into_iter()).unwrap());
}
#[test]
fn test_i64_codec() {
assert_eq!(0i64.encode(), vec![0u8]);
assert_eq!(1i64.encode(), vec![2u8]);
assert_eq!((-1i64).encode(), vec![1u8]);
assert_eq!(i64::max_value().encode(),
vec![0xFE, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x01]);
assert_eq!(i64::min_value().encode(),
vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x01]);
assert_eq!(i64::max_value(),
i64::decode(&mut i64::max_value()
.encode()
.into_iter()).unwrap());
assert_eq!(i64::min_value(),
i64::decode(&mut i64::min_value()
.encode()
.into_iter()).unwrap());
}
#[test]
fn test_usize_codec() {
assert_eq!(2usize.encode(), vec![4u8]);
assert_eq!(2usize, usize::decode(&mut vec![4u8]
.into_iter()).unwrap());
assert_eq!(2usize, usize::decode(&mut vec![3u8]
.into_iter()).unwrap());
}
#[test]
fn test_f32_codec() {
assert_eq!(0f32, f32::decode(&mut 0f32.encode()
.into_iter()).unwrap());
assert_eq!(f32::MIN,
f32::decode(&mut f32::MIN.encode()
.into_iter()).unwrap());
assert_eq!(f32::MAX,
f32::decode(&mut f32::MAX.encode()
.into_iter()).unwrap());
}
#[test]
fn test_f64_codec() {
assert_eq!(0f64, f64::decode(&mut 0f64.encode()
.into_iter()).unwrap());
assert_eq!(f64::MIN,
f64::decode(&mut f64::MIN.encode()
.into_iter()).unwrap());
assert_eq!(f64::MAX,
f64::decode(&mut f64::MAX.encode()
.into_iter()).unwrap());
}
#[test]
fn test_vec_i32_codec() {
assert_eq!(Vec::<i32>::new().encode(), vec![0x0]);
assert_eq!(vec![2i32].encode(), vec![0x2, 0x4]);
assert_eq!(Vec::<i32>::decode(&mut vec![0x2, 0x4]
.into_iter()).unwrap(),
vec![2i32]);
assert_eq!(Vec::<i32>::decode(&mut vec![0x0]
.into_iter()).unwrap(),
vec![]);
assert_eq!(Vec::<i32>::decode(&mut vec![0x1, 0x1]
.into_iter()).unwrap(),
vec![-1i32]);
}
#[test]
fn test_vec_f32_codec() {
assert_eq!(Vec::<f32>::new().encode(), vec![0x0]);
assert_eq!(vec![0f32, f32::MAX, f32::MIN],
Vec::<f32>::decode(&mut vec![0f32, f32::MAX, f32::MIN]
.encode()
.into_iter()).unwrap())
}
#[test]
fn test_string_codec() {
assert_eq!(String::from("abcde").encode(),
vec![0x0A, 0x61, 0x62, 0x63, 0x64, 0x65]);
assert_eq!(String::from("abcde"),
String::decode(&mut vec![0x0A, 0x61, 0x62, 0x63, 0x64, 0x65]
.into_iter()).unwrap());
assert_eq!(String::from(""),
String::decode(&mut vec![0x0].into_iter()).unwrap());
}
#[test]
fn test_vec_string_codec() {
assert_eq!(Vec::<String>::new().encode(), vec![0x0]);
assert_eq!(vec![String::from("This"), String::from("is"),
String::from("a"), String::from("test.")],
Vec::<String>::decode(&mut vec![
String::from("This"),
String::from("is"),
String::from("a"),
String::from("test.")]
.encode()
.into_iter()).unwrap());
}
#[test]
fn test_bool_codec() {
assert_eq!(true.encode(), vec![0x1]);
assert_eq!(false.encode(), vec![0x0]);
assert_eq!(true, bool::decode(&mut vec![0x1].into_iter()).unwrap());
assert_eq!(false, bool::decode(&mut vec![0x0].into_iter()).unwrap());
assert_eq!(None, bool::decode(&mut vec![0x2].into_iter()));
}
#[test]
fn test_byte_codec() {
assert_eq!(0xFFu8.encode(), vec![0xFFu8]);
assert_eq!(0xFFu8, u8::decode(&mut vec![0xFFu8].into_iter()).unwrap());
assert_eq!(0xFFu8, u8::decode(&mut 0xFFu8.encode().into_iter()).unwrap());
}
#[test]
fn test_byte_vec_codec() {
assert_eq!(vec![0xFFu8].encode(), vec![0x02, 0xFFu8]);
assert_eq!(Vec::<u8>::new().encode(), vec![0x0]);
assert_eq!(vec![0xFFu8], Vec::<u8>::decode(&mut vec![0x02, 0xFFu8].into_iter()).unwrap());
assert_eq!(vec![0xFFu8, 0xAF, 0x0],
Vec::<u8>::decode(&mut vec![0xFFu8, 0xAF, 0x0].encode().into_iter()).unwrap());
}
#[test]
fn test_map_codec() {
assert_eq!(HashMap::<String, i32>::new().encode(), vec![0x0]);
assert_eq!(HashMap::<String, i32>::decode(
&mut HashMap::<String, i32>::new().encode().into_iter())
.unwrap(),
HashMap::<String, i32>::new());
let mut test_map = HashMap::<String, i32>::new();
test_map.insert(String::from("test"), 1);
assert_eq!(test_map, HashMap::<String, i32>::decode(
&mut test_map.encode().into_iter()).unwrap());
}
}
|
use argh::FromArgs;
#[derive(FromArgs)]
/// dd writer goes drrrrrrrr
pub struct AppArgs {
/// the file to read
#[argh(option)]
pub input: String,
/// the file to write
#[argh(option)]
pub output: String,
/// set the blocksize, default is 1MiB
#[argh(option)]
pub blocksize: Option<usize>,
/// amount of blocks to write, default is to write until EOF
#[argh(option)]
pub count: Option<usize>,
/// show the progress of the OS sync operation, might give invalid numbers
#[argh(switch)]
pub sync_progress: bool,
}
use async_std::fs::{File, OpenOptions};
use async_std::io::prelude::*;
use std::sync::mpsc::{channel, Sender};
use std::thread;
use std::time::Instant;
// const CLEAR_LINE: &str = "\r\x1b[K";
fn main() {
async_std::task::block_on(_main()).unwrap();
}
async fn _main() -> Result<(), std::io::Error> {
let args: AppArgs = argh::from_env();
let block_size = args.blocksize.unwrap_or(1024 * 1024);
let total = if let Some(count) = args.count {
count * block_size
} else {
std::fs::metadata(&args.input)
.expect("Could not read input file")
.len() as usize
};
if let Ok(meta) = std::fs::metadata(&args.output) {
if meta.is_dir() {
println!("The output file is a directory. Aborting");
std::process::exit(0);
}
}
let source = File::open(&args.input).await?;
let target = OpenOptions::new()
.write(true)
.create(true)
.open(&args.output)
.await
.expect("Could not open output file");
let (tx, rx) = channel();
let t = Instant::now();
let handle = thread::spawn(move || {
async_std::task::block_on(writer_thread(tx, block_size, args.count, source, target))
.unwrap()
});
println!("Writing file to OS buffer");
let mut last_written = 0;
for written in rx.iter() {
std::thread::sleep(std::time::Duration::from_millis(100));
println!(
"Progress {}% ({}MiB of {}MiB, {:.1}MiB/s)",
((written as f32 / total as f32) * 100.0).floor(),
written / 1_000_000,
total / 1_000_000,
(written as f32 - last_written as f32) / 1_000_000.0
);
last_written = written;
if written == total {
println!("Syncing filesystem");
break;
};
}
let mut last_written = 0;
loop {
if let Ok(signal) = rx.try_recv() {
if signal == 0 {
let elapsed = t.elapsed();
println!(
"Finished in {:?}, {:.1}MiB/s",
elapsed,
(total as f32 / elapsed.as_secs() as f32) / 1_000_000.0
);
return Ok(());
}
}
let meminfo = async_std::fs::read_to_string("/proc/meminfo").await?;
let line = meminfo
.split('\n')
.filter(|s| s.contains("Dirty"))
.nth(0)
.unwrap();
let dirty = line.split(":").nth(1).unwrap().replace("kB", "");
let dirty: usize = dirty.trim().parse().unwrap();
let progress = total - dirty * 1000;
println!(
"Progress {}% ({}MiB of {}MiB, {:.1}MiB/s)",
((progress as f32 / total as f32) * 100.0).floor(),
progress / 1_000_000,
total / 1_000_000,
(progress as f32 - last_written as f32) / 1_000_000.0
);
last_written = progress;
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
async fn writer_thread(
tx: Sender<usize>,
block_size: usize,
count: Option<usize>,
mut source: File,
mut target: File,
) -> Result<(), std::io::Error> {
let mut count = count.unwrap_or(usize::max_value());
let mut written = 0;
let mut buf = vec![0; block_size];
let mut last_print = Instant::now();
let mut read = 1;
while read != 0 && count > 0 {
read = source.read(&mut buf).await?;
target.write(&mut buf).await?;
written += read;
count -= 1;
if last_print.elapsed().as_millis() > 500 {
tx.send(written).unwrap();
last_print = Instant::now();
}
}
tx.send(written).unwrap();
target.sync_data().await.unwrap_or_default();
tx.send(0).unwrap();
Ok(())
}
|
use rand::{seq::SliceRandom, thread_rng, Rng};
use vek::Rgb;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Body {
pub race: Race,
pub body_type: BodyType,
pub chest: Chest,
pub belt: Belt,
pub pants: Pants,
pub hand: Hand,
pub foot: Foot,
pub shoulder: Shoulder,
pub hair_style: u8,
pub beard: u8,
pub eyebrows: Eyebrows,
pub accessory: u8,
pub hair_color: u8,
pub skin: u8,
pub eye_color: u8,
}
impl Body {
pub fn random() -> Self {
let mut rng = thread_rng();
let race = *(&ALL_RACES).choose(&mut rng).unwrap();
let body_type = *(&ALL_BODY_TYPES).choose(&mut rng).unwrap();
Self {
race,
body_type,
chest: *(&ALL_CHESTS).choose(&mut rng).unwrap(),
belt: *(&ALL_BELTS).choose(&mut rng).unwrap(),
pants: *(&ALL_PANTS).choose(&mut rng).unwrap(),
hand: *(&ALL_HANDS).choose(&mut rng).unwrap(),
foot: *(&ALL_FEET).choose(&mut rng).unwrap(),
shoulder: *(&ALL_SHOULDERS).choose(&mut rng).unwrap(),
hair_style: rng.gen_range(0, race.num_hair_styles(body_type)),
beard: rng.gen_range(0, race.num_beards(body_type)),
eyebrows: *(&ALL_EYEBROWS).choose(&mut rng).unwrap(),
accessory: rng.gen_range(0, race.num_accessories(body_type)),
hair_color: rng.gen_range(0, race.num_hair_colors()) as u8,
skin: rng.gen_range(0, race.num_skin_colors()) as u8,
eye_color: rng.gen_range(0, race.num_eye_colors()) as u8,
}
}
pub fn validate(&mut self) {
self.hair_style = self
.hair_style
.min(self.race.num_hair_styles(self.body_type) - 1);
self.beard = self.beard.min(self.race.num_beards(self.body_type) - 1);
self.hair_color = self.hair_color.min(self.race.num_hair_colors() - 1);
self.skin = self.skin.min(self.race.num_skin_colors() - 1);
self.eye_color = self.hair_style.min(self.race.num_eye_colors() - 1);
self.accessory = self
.accessory
.min(self.race.num_accessories(self.body_type) - 1);
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Race {
Danari,
Dwarf,
Elf,
Human,
Orc,
Undead,
}
pub const ALL_RACES: [Race; 6] = [
Race::Danari,
Race::Dwarf,
Race::Elf,
Race::Human,
Race::Orc,
Race::Undead,
];
// Hair Colors
pub const DANARI_HAIR_COLORS: [(u8, u8, u8); 16] = [
(198, 169, 113), // Philosopher's Grey
(245, 232, 175), // Cream Blonde
(228, 208, 147), // Gold Blonde
(228, 223, 141), // Platinum Blonde
(199, 131, 58), // Summer Blonde
(107, 76, 51), // Oak Brown
(203, 154, 98), // Light Brown
(64, 32, 18), // Chocolate Brown
(86, 72, 71), // Ash Brown
(57, 56, 61), // Raven Black
(101, 83, 95), // Matte Purple
(101, 57, 90), // Witch Purple
(107, 32, 60), // Grape Purple
(135, 38, 39), // Dark Red
(88, 26, 29), // Wine Red
(146, 32, 32), // Autumn Red
];
pub const DWARF_HAIR_COLORS: [(u8, u8, u8); 20] = [
(245, 232, 175), // Cream Blonde
(228, 208, 147), // Gold Blonde
(228, 223, 141), // Platinum Blonde
(199, 131, 58), // Summer Blonde
(107, 76, 51), // Oak Brown
(203, 154, 98), // Light Brown
(64, 32, 18), // Chocolate Brown
(86, 72, 71), // Ash Brown
(57, 56, 61), // Raven Black
(101, 83, 95), // Matte Purple
(101, 57, 90), // Witch Purple
(135, 38, 39), // Dark Red
(88, 26, 29), // Wine Red
(191, 228, 254), // Ice NobleBlue
(92, 80, 144), // Kingfisher Blue
(146, 198, 238), // Lagoon Blue
(174, 148, 161), // Matte Pink
(163, 186, 192), // Matte Green
(84, 139, 107), // Grass Green
(48, 61, 52), // Dark Green
];
pub const ELF_HAIR_COLORS: [(u8, u8, u8); 23] = [
(66, 83, 113), // Mysterious Blue
(13, 76, 41), // Rainforest Green
(245, 232, 175), // Cream Blonde
(228, 208, 147), // Gold Blonde
(228, 223, 141), // Platinum Blonde
(199, 131, 58), // Summer Blonde
(107, 76, 51), // Oak Brown
(203, 154, 98), // Light Brown
(64, 32, 18), // Chocolate Brown
(86, 72, 71), // Ash Brown
(57, 56, 61), // Raven Black
(101, 83, 95), // Matte Purple
(101, 57, 90), // Witch Purple
(135, 38, 39), // Dark Red
(88, 26, 29), // Wine Red
(191, 228, 254), // Ice Blue
(92, 80, 144), // Kingfisher Blue
(146, 198, 238), // Lagoon Blue
(224, 182, 184), // Candy Pink
(174, 148, 161), // Matte Pink
(163, 186, 192), // Matte Green
(84, 139, 107), // Grass Green
(48, 61, 52), // Dark Green
];
pub const HUMAN_HAIR_COLORS: [(u8, u8, u8); 21] = [
(245, 232, 175), // Cream Blonde
(228, 208, 147), // Gold Blonde
(228, 223, 141), // Platinum Blonde
(199, 131, 58), // Summer Blonde
(107, 76, 51), // Oak Brown
(203, 154, 98), // Light Brown
(64, 32, 18), // Chocolate Brown
(86, 72, 71), // Ash Brown
(57, 56, 61), // Raven Black
(101, 83, 95), // Matte Purple
(101, 57, 90), // Witch Purple
(135, 38, 39), // Dark Red
(88, 26, 29), // Wine Red
(191, 228, 254), // Ice Blue
(92, 80, 144), // Kingfisher Blue
(146, 198, 238), // Lagoon Blue
(224, 182, 184), // Candy Pink
(174, 148, 161), // Matte Pink
(163, 186, 192), // Matte Green
(84, 139, 107), // Grass Green
(48, 61, 52), // Dark Green
];
pub const ORC_HAIR_COLORS: [(u8, u8, u8); 12] = [
(66, 66, 59), // Wise Grey
(107, 76, 51), // Oak Brown
(203, 154, 98), // Light Brown
(64, 32, 18), // Chocolate Brown
(54, 30, 26), // Dark Chocolate
(86, 72, 71), // Ash Brown
(57, 56, 61), // Raven Black
(101, 83, 95), // Matte Purple
(101, 57, 90), // Witch Purple
(135, 38, 39), // Dark Red
(88, 26, 29), // Wine Red
(66, 83, 113), // Mysterious Blue
];
pub const UNDEAD_HAIR_COLORS: [(u8, u8, u8); 24] = [
(245, 232, 175), // Cream Blonde
(228, 208, 147), // Gold Blonde
(228, 223, 141), // Platinum Blonde
(199, 131, 58), // Summer Blonde
(107, 76, 51), // Oak Brown
(203, 154, 98), // Light Brown
(64, 32, 18), // Chocolate Brown
(86, 72, 71), // Ash Brown
(57, 56, 61), // Raven Black
(101, 83, 95), // Matte Purple
(101, 57, 90), // Witch Purple
(111, 54, 117), // Punky Purple
(135, 38, 39), // Dark Red
(88, 26, 29), // Wine Red
(191, 228, 254), // Ice Blue
(92, 80, 144), // Kingfisher Blue
(146, 198, 238), // Lagoon Blue
(66, 66, 59), // Decayed Grey
(224, 182, 184), // Candy Pink
(174, 148, 161), // Matte Pink
(0, 131, 122), // Rotten Green
(163, 186, 192), // Matte Green
(84, 139, 107), // Grass Green
(48, 61, 52), // Dark Green
];
// Skin colors
pub const DANARI_SKIN_COLORS: [Skin; 4] = [
Skin::DanariOne,
Skin::DanariTwo,
Skin::DanariThree,
Skin::DanariFour,
];
pub const DWARF_SKIN_COLORS: [Skin; 5] = [
Skin::Pale,
Skin::White,
Skin::Tanned,
Skin::Iron,
Skin::Steel,
];
pub const ELF_SKIN_COLORS: [Skin; 7] = [
Skin::Pale,
Skin::ElfOne,
Skin::ElfTwo,
Skin::ElfThree,
Skin::White,
Skin::Tanned,
Skin::TannedBrown,
];
pub const HUMAN_SKIN_COLORS: [Skin; 5] = [
Skin::Pale,
Skin::White,
Skin::Tanned,
Skin::TannedBrown,
Skin::TannedDarkBrown,
];
pub const ORC_SKIN_COLORS: [Skin; 4] = [Skin::OrcOne, Skin::OrcTwo, Skin::OrcThree, Skin::Brown];
pub const UNDEAD_SKIN_COLORS: [Skin; 3] = [Skin::UndeadOne, Skin::UndeadTwo, Skin::UndeadThree];
// Eye colors
pub const DANARI_EYE_COLORS: [EyeColor; 3] = [
EyeColor::CuriousGreen,
EyeColor::LoyalBrown,
EyeColor::ViciousRed,
];
pub const DWARF_EYE_COLORS: [EyeColor; 3] = [
EyeColor::CuriousGreen,
EyeColor::LoyalBrown,
EyeColor::NobleBlue,
];
pub const ELF_EYE_COLORS: [EyeColor; 3] = [
EyeColor::NobleBlue,
EyeColor::CuriousGreen,
EyeColor::LoyalBrown,
];
pub const HUMAN_EYE_COLORS: [EyeColor; 3] = [
EyeColor::NobleBlue,
EyeColor::CuriousGreen,
EyeColor::LoyalBrown,
];
pub const ORC_EYE_COLORS: [EyeColor; 2] = [EyeColor::LoyalBrown, EyeColor::ExoticPurple];
pub const UNDEAD_EYE_COLORS: [EyeColor; 5] = [
EyeColor::ViciousRed,
EyeColor::PumpkinOrange,
EyeColor::GhastlyYellow,
EyeColor::MagicPurple,
EyeColor::ToxicGreen,
];
impl Race {
fn hair_colors(self) -> &'static [(u8, u8, u8)] {
match self {
Race::Danari => &DANARI_HAIR_COLORS,
Race::Dwarf => &DWARF_HAIR_COLORS,
Race::Elf => &ELF_HAIR_COLORS,
Race::Human => &HUMAN_HAIR_COLORS,
Race::Orc => &ORC_HAIR_COLORS,
Race::Undead => &UNDEAD_HAIR_COLORS,
}
}
fn skin_colors(self) -> &'static [Skin] {
match self {
Race::Danari => &DANARI_SKIN_COLORS,
Race::Dwarf => &DWARF_SKIN_COLORS,
Race::Elf => &ELF_SKIN_COLORS,
Race::Human => &HUMAN_SKIN_COLORS,
Race::Orc => &ORC_SKIN_COLORS,
Race::Undead => &UNDEAD_SKIN_COLORS,
}
}
fn eye_colors(self) -> &'static [EyeColor] {
match self {
Race::Danari => &DANARI_EYE_COLORS,
Race::Dwarf => &DWARF_EYE_COLORS,
Race::Elf => &ELF_EYE_COLORS,
Race::Human => &HUMAN_EYE_COLORS,
Race::Orc => &ORC_EYE_COLORS,
Race::Undead => &UNDEAD_EYE_COLORS,
}
}
pub fn hair_color(self, val: u8) -> Rgb<u8> {
self.hair_colors()
.get(val as usize)
.copied()
.unwrap_or((0, 0, 0))
.into()
}
pub fn num_hair_colors(self) -> u8 {
self.hair_colors().len() as u8
}
pub fn skin_color(self, val: u8) -> Skin {
self.skin_colors()
.get(val as usize)
.copied()
.unwrap_or(Skin::Tanned)
}
pub fn num_skin_colors(self) -> u8 {
self.skin_colors().len() as u8
}
pub fn eye_color(self, val: u8) -> EyeColor {
self.eye_colors()
.get(val as usize)
.copied()
.unwrap_or(EyeColor::NobleBlue)
}
pub fn num_eye_colors(self) -> u8 {
self.eye_colors().len() as u8
}
pub fn num_hair_styles(self, body_type: BodyType) -> u8 {
match (self, body_type) {
(Race::Danari, BodyType::Female) => 1,
(Race::Danari, BodyType::Male) => 1,
(Race::Dwarf, BodyType::Female) => 1,
(Race::Dwarf, BodyType::Male) => 3,
(Race::Elf, BodyType::Female) => 21,
(Race::Elf, BodyType::Male) => 2,
(Race::Human, BodyType::Female) => 19,
(Race::Human, BodyType::Male) => 4,
(Race::Orc, BodyType::Female) => 1,
(Race::Orc, BodyType::Male) => 2,
(Race::Undead, BodyType::Female) => 4,
(Race::Undead, BodyType::Male) => 3,
}
}
pub fn num_accessories(self, body_type: BodyType) -> u8 {
match (self, body_type) {
(Race::Danari, BodyType::Female) => 1,
(Race::Danari, BodyType::Male) => 1,
(Race::Dwarf, BodyType::Female) => 1,
(Race::Dwarf, BodyType::Male) => 1,
(Race::Elf, BodyType::Female) => 2,
(Race::Elf, BodyType::Male) => 1,
(Race::Human, BodyType::Female) => 1,
(Race::Human, BodyType::Male) => 1,
(Race::Orc, BodyType::Female) => 3,
(Race::Orc, BodyType::Male) => 5,
(Race::Undead, BodyType::Female) => 1,
(Race::Undead, BodyType::Male) => 1,
}
}
pub fn num_beards(self, body_type: BodyType) -> u8 {
match (self, body_type) {
(Race::Danari, BodyType::Female) => 1,
(Race::Danari, BodyType::Male) => 1,
(Race::Dwarf, BodyType::Female) => 1,
(Race::Dwarf, BodyType::Male) => 20,
(Race::Elf, BodyType::Female) => 1,
(Race::Elf, BodyType::Male) => 1,
(Race::Human, BodyType::Female) => 1,
(Race::Human, BodyType::Male) => 3,
(Race::Orc, BodyType::Female) => 1,
(Race::Orc, BodyType::Male) => 2,
(Race::Undead, BodyType::Female) => 1,
(Race::Undead, BodyType::Male) => 1,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BodyType {
Female,
Male,
}
pub const ALL_BODY_TYPES: [BodyType; 2] = [BodyType::Female, BodyType::Male];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Chest {
Blue,
Brown,
Dark,
Green,
Orange,
Midnight,
}
pub const ALL_CHESTS: [Chest; 6] = [
Chest::Blue,
Chest::Brown,
Chest::Dark,
Chest::Green,
Chest::Orange,
Chest::Midnight,
];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Belt {
Dark,
}
pub const ALL_BELTS: [Belt; 1] = [
//Belt::Default,
Belt::Dark,
];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Pants {
Blue,
Brown,
Dark,
Green,
Orange,
}
pub const ALL_PANTS: [Pants; 5] = [
Pants::Blue,
Pants::Brown,
Pants::Dark,
Pants::Green,
Pants::Orange,
];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Hand {
Bare,
Dark,
}
pub const ALL_HANDS: [Hand; 2] = [Hand::Bare, Hand::Dark];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Foot {
Bare,
Dark,
}
pub const ALL_FEET: [Foot; 2] = [Foot::Bare, Foot::Dark];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Shoulder {
None,
Brown1,
}
pub const ALL_SHOULDERS: [Shoulder; 2] = [Shoulder::None, Shoulder::Brown1];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Eyebrows {
Yup,
}
pub const ALL_EYEBROWS: [Eyebrows; 1] = [Eyebrows::Yup];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EyeColor {
VigorousBlack,
NobleBlue,
CuriousGreen,
LoyalBrown,
ViciousRed,
PumpkinOrange,
GhastlyYellow,
MagicPurple,
ToxicGreen,
ExoticPurple,
}
impl EyeColor {
pub fn light_rgb(self) -> Rgb<u8> {
match self {
EyeColor::VigorousBlack => Rgb::new(71, 59, 49),
EyeColor::NobleBlue => Rgb::new(75, 158, 191),
EyeColor::CuriousGreen => Rgb::new(110, 167, 113),
EyeColor::LoyalBrown => Rgb::new(73, 42, 36),
EyeColor::ViciousRed => Rgb::new(182, 0, 0),
EyeColor::PumpkinOrange => Rgb::new(220, 156, 19),
EyeColor::GhastlyYellow => Rgb::new(221, 225, 31),
EyeColor::MagicPurple => Rgb::new(137, 4, 177),
EyeColor::ToxicGreen => Rgb::new(1, 223, 1),
EyeColor::ExoticPurple => Rgb::new(95, 32, 111),
}
}
pub fn dark_rgb(self) -> Rgb<u8> {
match self {
EyeColor::VigorousBlack => Rgb::new(32, 32, 32),
EyeColor::NobleBlue => Rgb::new(62, 130, 159),
EyeColor::CuriousGreen => Rgb::new(81, 124, 84),
EyeColor::LoyalBrown => Rgb::new(54, 30, 26),
EyeColor::ViciousRed => Rgb::new(148, 0, 0),
EyeColor::PumpkinOrange => Rgb::new(209, 145, 18),
EyeColor::GhastlyYellow => Rgb::new(205, 212, 29),
EyeColor::MagicPurple => Rgb::new(110, 3, 143),
EyeColor::ToxicGreen => Rgb::new(1, 185, 1),
EyeColor::ExoticPurple => Rgb::new(69, 23, 80),
}
}
pub fn white_rgb(self) -> Rgb<u8> {
Rgb::new(255, 255, 255)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Accessory {
Nothing,
Some,
}
pub const ALL_ACCESSORIES: [Accessory; 2] = [Accessory::Nothing, Accessory::Some];
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Skin {
Pale,
White,
Tanned,
Brown,
TannedBrown,
TannedDarkBrown,
Iron,
Steel,
DanariOne,
DanariTwo,
DanariThree,
DanariFour,
ElfOne,
ElfTwo,
ElfThree,
OrcOne,
OrcTwo,
OrcThree,
UndeadOne,
UndeadTwo,
UndeadThree,
}
impl Skin {
pub fn rgb(self) -> Rgb<u8> {
let color = match self {
Self::Pale => (252, 211, 179),
Self::White => (253, 195, 164),
Self::Tanned => (222, 181, 151),
Self::Brown => (123, 80, 45),
Self::TannedBrown => (135, 70, 50),
Self::TannedDarkBrown => (116, 61, 43),
Self::Iron => (135, 113, 95),
Self::Steel => (108, 94, 86),
Self::DanariOne => (104, 168, 196),
Self::DanariTwo => (30, 149, 201),
Self::DanariThree => (57, 120, 148),
Self::DanariFour => (40, 85, 105),
Self::ElfOne => (178, 164, 186),
Self::ElfTwo => (132, 139, 161),
Self::ElfThree => (148, 128, 202),
Self::OrcOne => (61, 130, 42),
Self::OrcTwo => (82, 117, 36),
Self::OrcThree => (71, 94, 42),
Self::UndeadOne => (240, 243, 239),
Self::UndeadTwo => (178, 178, 178),
Self::UndeadThree => (145, 135, 121),
};
Rgb::from(color)
}
pub fn light_rgb(self) -> Rgb<u8> {
let color = match self {
Self::Pale => (255, 227, 193),
Self::White => (255, 210, 180),
Self::Tanned => (239, 197, 164),
Self::Brown => (150, 104, 68),
Self::TannedBrown => (148, 85, 64),
Self::TannedDarkBrown => (132, 74, 56),
Self::Iron => (144, 125, 106),
Self::Steel => (120, 107, 99),
Self::DanariOne => (116, 176, 208),
Self::DanariTwo => (42, 158, 206),
Self::DanariThree => (70, 133, 160),
Self::DanariFour => (53, 96, 116),
Self::ElfOne => (190, 176, 199), //178, 164, 186
Self::ElfTwo => (137, 144, 167),
Self::ElfThree => (156, 138, 209),
Self::OrcOne => (83, 165, 56),
Self::OrcTwo => (92, 132, 46),
Self::OrcThree => (84, 110, 54),
Self::UndeadOne => (254, 252, 251),
Self::UndeadTwo => (190, 192, 191),
Self::UndeadThree => (160, 151, 134),
};
Rgb::from(color)
}
pub fn dark_rgb(self) -> Rgb<u8> {
let color = match self {
Self::Pale => (229, 192, 163),
Self::White => (239, 179, 150),
Self::Tanned => (208, 167, 135),
Self::Brown => (106, 63, 30),
Self::TannedBrown => (122, 58, 40),
Self::TannedDarkBrown => (100, 47, 32),
Self::Iron => (124, 99, 82),
Self::Steel => (96, 81, 72),
Self::DanariOne => (92, 155, 183),
Self::DanariTwo => (25, 142, 192),
Self::DanariThree => (52, 115, 143),
Self::DanariFour => (34, 80, 99),
Self::ElfOne => (170, 155, 175), //170, 157, 179
Self::ElfTwo => (126, 132, 153),
Self::ElfThree => (137, 121, 194),
Self::OrcOne => (55, 114, 36),
Self::OrcTwo => (70, 104, 29),
Self::OrcThree => (60, 83, 32),
Self::UndeadOne => (229, 231, 230),
Self::UndeadTwo => (165, 166, 164),
Self::UndeadThree => (130, 122, 106),
};
Rgb::from(color)
}
}
|
struct Point <T,U>{
x:T,
y:U,
}
impl <T,U> Point <T,U>{
fn mixup <V,W> (self,other: Point<V,W>) -> Point<T,W>{
Point {
x:self.x,
y:other.y,
}
}
}
fn main() {
let p1 = Point {x:6,y:7.0};
let p2 = Point {x:"Areeb",y:'c'};
let p3 = p1.mixup(p2);
println!("p3.x:{},p3.y:{}",p3.x,p3.y);
}
|
use crate::arch::interrupt::TrapFrame;
use bcm2837::interrupt::Controller;
use spin::RwLock;
pub use bcm2837::interrupt::Interrupt;
lazy_static! {
static ref IRQ_HANDLERS: RwLock<[Option<fn()>; 64]> = RwLock::new([None; 64]);
}
pub fn is_timer_irq() -> bool {
super::timer::is_pending()
}
pub fn handle_irq(_tf: &mut TrapFrame) {
for int in Controller::new().pending_interrupts() {
if let Some(handler) = IRQ_HANDLERS.read()[int] {
handler();
}
}
}
pub fn register_irq(int: Interrupt, handler: fn()) {
IRQ_HANDLERS.write()[int as usize] = Some(handler);
Controller::new().enable(int);
}
|
use crate::*;
#[derive(Debug, Clone, Copy, Default)]
pub struct BodyJson<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for BodyJson<T>
where
T: serde::de::DeserializeOwned,
B: http_body::Body + Send,
B::Data: Send,
B::Error: Into<tower::BoxError>,
{
type Rejection = JsonRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
use bytes::Buf;
if has_content_type(req, "application/json")? {
let body = req.take_body().ok_or(JsonRejection::BodyAlreadyExtracted)?;
//let body = axum::extract::take_body(req)?;
let buf = hyper::body::aggregate(body)
.await
.map_err(|_| JsonRejection::InvalidJsonBody)?;
let value = serde_json::from_reader(buf.reader())
.map_err(|_| JsonRejection::InvalidJsonBody)?;
Ok(BodyJson(value))
} else {
Err(JsonRejection::MissingJsonContentType(""))
}
}
}
impl<T> core::ops::Deref for BodyJson<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn has_content_type<B>(
req: &RequestParts<B>,
expected_content_type: &str,
) -> Result<bool, JsonRejection> {
let content_type = if let Some(content_type) = req
.headers()
.ok_or(JsonRejection::HeadersAlreadyExtracted)?
.get(http::header::CONTENT_TYPE)
{
content_type
} else {
return Ok(false);
};
let content_type = if let Ok(content_type) = content_type.to_str() {
content_type
} else {
return Ok(false);
};
Ok(content_type.starts_with(expected_content_type))
}
|
extern crate askama;
use askama::Template;
use actix_files as fs;
use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result};
use listenfd::ListenFd;
use http::StatusCode;
use std::clone::Clone;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use handlebars::Handlebars;
use serde::{Deserialize, Serialize};
#[derive(Template)]
#[template(path = "signin.html")]
struct SigninTemplate {
error: String,
}
#[derive(Debug, Clone)]
struct User {
email: String,
password: md5::Digest,
}
#[derive(Serialize, Deserialize, Debug)]
struct UserToValidate {
email: String,
password: String,
confirm_password: String,
}
struct Session {
token: String,
expired_at: Instant,
}
impl Session {
fn is_valid(&self) -> bool {
if self.expired_at > Instant::now() {
return true;
} else {
//TODO: remove user session
return false;
}
}
}
#[derive(Clone, Debug)]
struct State {
users: HashMap<String, User>,
// the key of sessions HashMap is the session's token.
sessions: HashMap<String, User>,
}
impl State {
pub fn new() -> State {
State {
users: HashMap::new(),
sessions: HashMap::new(),
}
}
pub fn register_user(&mut self, user: &User) {
self.users.insert(String::from(&user.email), user.clone());
}
fn log_user() {
// TODO: create user session
}
fn create_user_session() {}
fn remove_user_session() {}
}
fn home(_req: HttpRequest) -> Result<fs::NamedFile> {
let path = PathBuf::from("templates/home.html");
Ok(fs::NamedFile::open(path)?)
}
fn get_login(_req: HttpRequest) -> Result<fs::NamedFile, std::io::Error> {
let mut path = PathBuf::new();
// Generally the html files are saved inside static directory.
path.push("templates");
let filename: PathBuf = _req.match_info().query("filename").parse().unwrap();
path.push(filename);
// Uncomment the following line in the case filename does not include the extention.
// path.set_extension("html");
println!("path complete: {:?}", path);
let result = fs::NamedFile::open(path);
match result {
Ok(_) => result,
Err(_) => fs::NamedFile::open(PathBuf::from("templates/404_not_found.html")),
}
}
fn get_siginin() -> Result<HttpResponse> {
let mut signin_template = SigninTemplate {
error: String::new(),
};
signin_template.error = String::from("");
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(signin_template.render().unwrap()))
}
fn post_siginin(
form: web::Form<UserToValidate>,
state: web::Data<Arc<Mutex<State>>>,
req: HttpRequest,
hb: web::Data<Handlebars>,
_payload: web::Payload,
) -> Result<HttpResponse> {
println!("req {:?}", req.uri());
let mut signin_template = SigninTemplate {
error: String::new(),
};
let mut data = state.lock().unwrap();
if data.users.contains_key(&form.email.to_string()) {
signin_template.error =
String::from("This email is used by another user. Try with different email.");
return Ok(HttpResponse::Created()
.content_type("text/html")
.body(signin_template.render().unwrap()));
}
if form.password.to_string() != form.confirm_password.to_string() {
signin_template.error = String::from("Passwords don't match");
return Ok(HttpResponse::Created()
.content_type("text/html")
.body(signin_template.render().unwrap()));
}
let crypt_password = md5::compute(form.password.to_string());
println!("password {:x}", crypt_password);
let user = User {
email: form.email.to_string(),
password: crypt_password,
};
data.register_user(&user);
println!("users {:?}", data.users);
return Ok(HttpResponse::MovedPermanently()
.header(http::header::LOCATION, "/login.html")
.finish()
);
}
fn post_login(_req: HttpRequest) -> impl Responder {
"[login] Post request"
}
fn main() {
let mut listenfd = ListenFd::from_env();
let state = Arc::new(Mutex::new(State::new()));
// Is an extensible templating solution
let mut handlebars = Handlebars::new();
// We registered the directory that contains our html files.
handlebars
.register_templates_directory(".html", "./templates")
.unwrap();
let handlebars_ref = web::Data::new(handlebars);
let mut server = HttpServer::new(move || {
App::new()
// Invoking clone on Arc produces a new Arc instance, which points to the same value on the heap as the source Arc,
// while increasing a reference count.
.data(state.clone())
.register_data(handlebars_ref.clone())
.route("/", web::get().to(home))
.route("/signin.html", web::get().to(get_siginin))
.route("/signin.html", web::post().to(post_siginin))
.route("/{filename:.*}", web::get().to(get_login)) // In this case with filename we specify the extention too.
.route("/login.html", web::post().to(post_login))
});
server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
server.listen(l).unwrap()
} else {
server.bind("127.0.0.1:8088").expect("Connection failed.")
};
server.run().unwrap();
}
|
extern crate num_cpus;
extern crate pretty_env_logger;
use std::os::raw::c_void;
use std::sync::{Arc, Mutex};
use cfile;
use log::Level::Debug;
use ffi;
use common::memory::SOCKET_ID_ANY;
use eal::{self, ProcType};
use launch;
use lcore;
use mbuf;
use memory::AsMutRef;
use mempool::{self, MemoryPool, MemoryPoolFlags};
use utils::AsRaw;
#[test]
fn test_eal() {
let _ = pretty_env_logger::try_init_timed();
assert_eq!(
eal::init(&vec![
String::from("test"),
String::from("-c"),
format!("{:x}", (1 << num_cpus::get()) - 1),
String::from("--log-level"),
String::from("8")
])
.unwrap(),
4
);
assert_eq!(eal::process_type(), ProcType::Primary);
assert!(!eal::primary_proc_alive());
assert!(eal::has_hugepages());
assert_eq!(lcore::socket_id(), 0);
// test_config();
test_lcore();
test_launch();
test_mempool();
test_mbuf();
}
// fn test_config() {
// let eal_cfg = eal::config();
// assert_eq!(eal_cfg.master_lcore(), 0);
// assert_eq!(eal_cfg.lcore_count(), num_cpus::get());
// assert_eq!(eal_cfg.process_type(), ProcType::Primary);
// assert_eq!(
// eal_cfg.lcore_roles(),
// &[lcore::Role::Rte, lcore::Role::Rte, lcore::Role::Rte, lcore::Role::Rte]
// );
// let mem_cfg = eal_cfg.memory_config();
// assert_eq!(mem_cfg.nchannel(), 0);
// assert_eq!(mem_cfg.nrank(), 0);
// let memzones = mem_cfg.memzones();
// assert!(memzones.len() > 0);
// }
fn test_lcore() {
assert_eq!(lcore::current().unwrap(), 0);
let lcore_id = lcore::current().unwrap();
assert_eq!(lcore_id.role(), lcore::Role::Rte);
assert_eq!(lcore_id.socket_id(), 0);
assert!(lcore_id.is_enabled());
assert_eq!(lcore::main(), 0);
assert_eq!(lcore::count(), num_cpus::get());
assert_eq!(lcore::enabled().len(), num_cpus::get());
assert_eq!(lcore::index(256), None);
assert_eq!(lcore::Id::any().index(), 0);
assert_eq!(lcore::id(0).index(), 0);
}
fn test_launch() {
fn slave_main(mutex: Option<Arc<Mutex<usize>>>) -> i32 {
debug!("lcore {} is running", lcore::current().unwrap());
let mutex = mutex.unwrap();
let mut data = mutex.lock().unwrap();
*data += 1;
debug!("lcore {} finished, data={}", lcore::current().unwrap(), *data);
0
}
let mutex = Arc::new(Mutex::new(0));
let slave_id = lcore::id(1);
assert_eq!(slave_id.state(), launch::State::Wait);
{
let data = mutex.lock().unwrap();
assert_eq!(*data, 0);
debug!("remote launch lcore {}", slave_id);
launch::remote_launch(slave_main, Some(mutex.clone()), slave_id).unwrap();
assert_eq!(slave_id.state(), launch::State::Running);
}
debug!("waiting lcore {} ...", slave_id);
assert_eq!(slave_id.wait(), launch::JobState::Wait);
{
let data = mutex.lock().unwrap();
assert_eq!(*data, 1);
debug!("remote lcore {} finished", slave_id);
assert_eq!(slave_id.state(), launch::State::Wait);
}
{
let _ = mutex.lock().unwrap();
debug!("remote launch lcores");
launch::mp_remote_launch(slave_main, Some(mutex.clone()), true).unwrap();
}
launch::mp_wait_lcore();
{
let data = mutex.lock().unwrap();
debug!("remote lcores finished");
assert_eq!(*data, num_cpus::get());
}
}
fn test_mempool() {
let mut p = mempool::create_empty::<_, ()>(
"test",
16,
128,
0,
SOCKET_ID_ANY,
MemoryPoolFlags::MEMPOOL_F_SP_PUT | MemoryPoolFlags::MEMPOOL_F_SC_GET,
)
.unwrap();
assert_eq!(p.name(), "test");
assert_eq!(p.size, 16);
assert_eq!(p.cache_size, 0);
assert_eq!(p.elt_size, 128);
assert_eq!(p.header_size, 64);
assert_eq!(p.trailer_size, 0);
assert_eq!(p.private_data_size, 64);
assert_eq!(p.avail_count(), 16);
assert_eq!(p.in_use_count(), 0);
assert!(p.is_full());
assert!(!p.is_empty());
p.audit();
if log_enabled!(Debug) {
let stdout = cfile::tmpfile().unwrap();
p.dump(&*stdout);
}
let mut elements: Vec<(usize, *mut ())> = Vec::new();
fn walk_element(
_pool: &mempool::MemoryPool,
elements: Option<&mut Vec<(usize, *mut ())>>,
obj: &mut (),
idx: usize,
) {
elements.unwrap().push((idx, obj as *mut _));
}
assert_eq!(p.walk(walk_element, Some(&mut elements)), 4);
assert_eq!(elements.len(), 4);
let raw_ptr = p.as_raw_mut();
assert_eq!(raw_ptr, mempool::lookup("test").unwrap());
let mut pools: Vec<mempool::RawMemoryPoolPtr> = Vec::new();
fn walk_mempool(pool: &mempool::MemoryPool, pools: Option<&mut Vec<mempool::RawMemoryPoolPtr>>) {
pools.unwrap().push(pool.as_raw_mut());
}
mempool::walk(walk_mempool, Some(&mut pools));
assert!(pools.contains(&raw_ptr));
if log_enabled!(Debug) {
let stdout = cfile::tmpfile().unwrap();
mempool::list_dump(&*stdout);
}
}
fn test_mbuf() {
const NB_MBUF: u32 = 1024;
const CACHE_SIZE: u32 = 32;
const PRIV_SIZE: u32 = 0;
const MBUF_SIZE: u32 = 128;
let p = mbuf::pool_create(
"mbuf_pool",
NB_MBUF,
CACHE_SIZE,
PRIV_SIZE as u16,
mbuf::RTE_MBUF_DEFAULT_BUF_SIZE as u16,
lcore::socket_id() as i32,
)
.unwrap();
assert_eq!(p.name(), "mbuf_pool");
assert_eq!(p.size, NB_MBUF);
assert_eq!(p.cache_size, CACHE_SIZE);
assert_eq!(p.elt_size, mbuf::RTE_MBUF_DEFAULT_BUF_SIZE + PRIV_SIZE + MBUF_SIZE);
assert_eq!(p.header_size, 64);
assert_eq!(p.trailer_size, 0);
assert_eq!(p.private_data_size, 64);
assert_eq!(p.avail_count(), NB_MBUF as usize);
assert_eq!(p.in_use_count(), 0);
assert!(p.is_full());
assert!(!p.is_empty());
p.audit();
}
|
//! Multi Media eXtensions (MMX)
use mem::transmute;
use sealed::*;
use simd::*;
/// Instantiate zero-initialized vector
///
/// # Instruction
///
/// This intrinsic maps to different instructions depending on how the vector is
/// used:
///
/// * [`pxor mm, mm`](http://www.felixcloutier.com/x86/PXOR.html)
/// * [`xorps xmm, xmm`](https://www.felixcloutier.com/x86/XORPS.html)
///
/// amongst others.
///
/// # Examples
///
/// ```
/// let a: i8x8 = _mm_setzero_si64();
/// assert_eq!(transmute(a), 0_i64);
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_setzero_si64<T: Any64>() -> T {
T::from_m64(::arch::_mm_setzero_si64())
}
/// Add packed integers
///
/// When an individual result is too large to be represented in 8 bits
/// (overflow), the result is wrapped around and the low 8 bits are written to
/// the destination operand (that is, the carry is ignored).
///
/// # Instruction
///
/// [`paddb mm, mm`](http://www.felixcloutier.com/x86/PADDB:PADDW:PADDD:PADDQ.html)
///
/// # Examples
///
/// ```
/// let min = i8::min_value();
/// let max = i8::max_value();
/// let a = i8x8::new(0, 1, 0, 42, 42, -42, max, -1);
/// let b = i8x8::new(0, 0, 1, 3, -3, 3, 1, min);
/// let e = i8x8::new(0, 1, 0, 45, 39, -39, min, max);
/// assert_eq!(e, _mm_add_pi8(a, b));
///
/// let max = i8::max_value();
/// let a = u8x8::new(0, 1, 0, 1, 1, max, 1, 42);
/// let b = u8x8::new(0, 0, 1, 254, max, 1, 1, 3);
/// let e = u8x8::new(0, 1, 1, max, 0, 0, 2, 45);
/// assert_eq!(e, _mm_add_pi8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_add_pi8<T: IU8x8>(a: T, b: T) -> T {
T::from_m64(::arch::_mm_add_pi8(a.as_m64(), b.as_m64()))
}
/// Add packed integers
///
/// When an individual result is too large to be represented in 8 bits
/// (overflow), the result is wrapped around and the low 8 bits are written to
/// the destination operand (that is, the carry is ignored).
///
/// # Instruction
///
/// [`paddb mm, mm`](http://www.felixcloutier.com/x86/PADDB:PADDW:PADDD:PADDQ.html)
///
/// # Examples
///
/// ```
/// let min = i8::min_value();
/// let max = i8::max_value();
/// let a = i8x8::new(0, 1, 0, 42, 42, -42, max, -1);
/// let b = i8x8::new(0, 0, 1, 3, -3, 3, 1, min);
/// let e = i8x8::new(0, 1, 0, 45, 39, -39, min, max);
/// assert_eq!(e, _mm_add_pi8(a, b));
///
/// let max = i8::max_value();
/// let a = u8x8::new(0, 1, 0, 1, 1, max, 1, 42);
/// let b = u8x8::new(0, 0, 1, 254, max, 1, 1, 3);
/// let e = u8x8::new(0, 1, 1, max, 0, 0, 2, 45);
/// assert_eq!(e, _mm_add_pi8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddb<T: IU8x8>(a: T, b: T) -> T {
_mm_add_pi8(a, b)
}
/// Add packed integers
///
/// When an individual result is too large to be represented in 16 bits
/// (overflow), the result is wrapped around and the low 16 bits are written to
/// the destination operand (that is, the carry is ignored).
///
/// # Instruction
///
/// [`paddw mm, mm`](http://www.felixcloutier.com/x86/PADDB:PADDW:PADDD:PADDQ.html)
///
/// # Examples
///
/// ```
/// let min = i16::min_value();
/// let max = i16::max_value();
/// let a = i16x4::new(max, min, 32, 32);
/// let b = i16x4::new( 1, -1, 3, -3);
/// let e = i16x4::new(min, max, 35, 29);
/// assert_eq!(e, _mm_add_pi16(a, b));
///
/// let max = u16::max_value();
/// let a = u16x4::new(42, 42, 1, max);
/// let b = u16x4::new(10, -2, max, 1);
/// let e = u16x4::new(52, 40, 0, 0);
/// assert_eq!(e, _mm_add_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_add_pi16<T: IU16x4>(a: T, b: T) -> T {
T::from_m64(::arch::_mm_add_pi16(a.as_m64(), b.as_m64()))
}
/// Add packed integers
///
/// When an individual result is too large to be represented in 16 bits
/// (overflow), the result is wrapped around and the low 16 bits are written to
/// the destination operand (that is, the carry is ignored).
///
/// # Instruction
///
/// [`paddw mm, mm`](http://www.felixcloutier.com/x86/PADDB:PADDW:PADDD:PADDQ.html)
///
/// # Examples
///
/// ```
/// let min = i16::min_value();
/// let max = i16::max_value();
/// let a = i16x4::new(max, min, 32, 32);
/// let b = i16x4::new( 1, -1, 3, -3);
/// let e = i16x4::new(min, max, 35, 29);
/// assert_eq!(e, _mm_add_pi16(a, b));
///
/// let max = u16::max_value();
/// let a = u16x4::new(42, 42, 1, max);
/// let b = u16x4::new(10, -2, max, 1);
/// let e = u16x4::new(52, 40, 0, 0);
/// assert_eq!(e, _mm_add_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddw<T: IU16x4>(a: T, b: T) -> T {
_mm_add_pi16(a, b)
}
/// Add packed integers
///
/// When an individual result is too large to be represented in 32 bits
/// (overflow), the result is wrapped around and the low 32 bits are written to
/// the destination operand (that is, the carry is ignored).
///
/// # Instruction
///
/// [`paddd mm, mm`](http://www.felixcloutier.com/x86/PADDB:PADDW:PADDD:PADDQ.html)
///
/// # Examples
///
/// ```
/// let min = i32::min_value();
/// let max = i32::max_value();
/// let a = i32x2::new(max, min);
/// let b = i32x2::new( 1, -1);
/// let e = i32x2::new(min, max);
/// assert_eq!(e, _mm_add_pi32(a, b));
///
/// let max = u32::max_value();
/// let a = u32x2::new(42, max);
/// let b = u32x2::new(10, 1);
/// let e = u32x2::new(52, 0);
/// assert_eq!(e, _mm_add_pi32(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_add_pi32<T: IU32x2>(a: T, b: T) -> T {
T::from_m64(::arch::_mm_add_pi32(a.as_m64(), b.as_m64()))
}
/// Add packed integers
///
/// When an individual result is too large to be represented in 32 bits
/// (overflow), the result is wrapped around and the low 32 bits are written to
/// the destination operand (that is, the carry is ignored).
///
/// # Instruction
///
/// [`paddd mm, mm`](http://www.felixcloutier.com/x86/PADDB:PADDW:PADDD:PADDQ.html)
///
/// # Examples
///
/// ```
/// let min = i32::min_value();
/// let max = i32::max_value();
/// let a = i32x2::new(max, min);
/// let b = i32x2::new( 1, -1);
/// let e = i32x2::new(min, max);
/// assert_eq!(e, _mm_add_pi32(a, b));
///
/// let max = u32::max_value();
/// let a = u32x2::new(42, max);
/// let b = u32x2::new(10, 1);
/// let e = u32x2::new(52, 0);
/// assert_eq!(e, _mm_add_pi32(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddd<T: IU32x2>(a: T, b: T) -> T {
_mm_add_pi32(a, b)
}
/// Add packed signed integers with signed saturation
///
/// When an individual byte result is beyond the range of a signed byte integer
/// (that is, greater than `7FH` or less than `80H`), the saturated value of
/// `7FH` or `80H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddsb mm, mm`](https://www.felixcloutier.com/x86/PADDSB:PADDSW.html)
///
/// # Examples
///
/// ```
/// let min = i8::min_value();
/// let max = i8::max_value();
/// let a = i8x8::new(-100, -1, 1, 100, -1, 0, 1, 0);
/// let b = i8x8::new(-100, 1, -1, 100, 0, -1, 0, 1);
/// let e = i8x8::new( min, 0, 0, max, -1, -1, 1, 1);
/// assert_eq!(e, _mm_adds_pi8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_adds_pi8(a: i8x8, b: i8x8) -> i8x8 {
transmute(::arch::_mm_adds_pi8(transmute(a), transmute(b)))
}
/// Add packed signed integers with signed saturation
///
/// When an individual byte result is beyond the range of a signed byte integer
/// (that is, greater than `7FH` or less than `80H`), the saturated value of
/// `7FH` or `80H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddsb mm, mm`](https://www.felixcloutier.com/x86/PADDSB:PADDSW.html)
///
/// # Examples
///
/// ```
/// let min = i8::min_value();
/// let max = i8::max_value();
/// let a = i8x8::new(-100, -1, 1, 100, -1, 0, 1, 0);
/// let b = i8x8::new(-100, 1, -1, 100, 0, -1, 0, 1);
/// let e = i8x8::new( min, 0, 0, max, -1, -1, 1, 1);
/// assert_eq!(e, _m_paddsb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddsb(a: i8x8, b: i8x8) -> i8x8 {
transmute(::arch::_m_paddsb(transmute(a), transmute(b)))
}
/// Add packed signed integers with signed saturation
///
/// When an individual word result is beyond the range of a signed word integer
/// (that is, greater than `7FFFH` or less than `8000H`), the saturated value of
/// `7FFFH` or `8000H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddsw mm, mm`](https://www.felixcloutier.com/x86/PADDSB:PADDSW.html)
///
/// # Examples
///
/// ```
/// let min = i16::min_value();
/// let max = i16::max_value();
/// let a = i16x4::new(-32_000, 32_000, 4, 0);
/// let b = i16x4::new(-32_000, 32_000, -5, 1);
/// let e = i16x4::new(min, max, -1, 1);
/// assert_eq!(e, _mm_adds_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_adds_pi16(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_mm_adds_pi16(
transmute(a),
transmute(b),
))
}
/// Add packed signed integers with signed saturation
///
/// When an individual word result is beyond the range of a signed word integer
/// (that is, greater than `7FFFH` or less than `8000H`), the saturated value of
/// `7FFFH` or `8000H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddsw mm, mm`](https://www.felixcloutier.com/x86/PADDSB:PADDSW.html)
///
/// # Examples
///
/// ```
/// let min = i16::min_value();
/// let max = i16::max_value();
/// let a = i16x4::new(-32_000, 32_000, 4, 0);
/// let b = i16x4::new(-32_000, 32_000, -5, 1);
/// let e = i16x4::new(min, max, -1, 1);
/// assert_eq!(e, _m_paddsw(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddsw(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_m_paddsw(transmute(a), transmute(b)))
}
/// Add packed unsigned integers with unsigned saturation
///
/// When an individual byte result is beyond the range of a signed byte integer
/// (that is, greater than `7FH` or less than `80H`), the saturated value of
/// `7FH` or `80H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddusb mm, mm`](http://www.felixcloutier.com/x86/PADDUSB:PADDUSW.html)
///
/// # Examples
///
/// ```
/// let max = u8::max_value();
/// let a = u8x8::new(0, 1, 2, 3, 4, 5, 6, 200);
/// let b = u8x8::new(0, 10, 20, 30, 40, 50, 60, 200);
/// let e = u8x8::new(0, 11, 22, 33, 44, 55, 66, max);
/// assert_eq!(e, _mm_adds_pu8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_adds_pu8(a: u8x8, b: u8x8) -> u8x8 {
transmute(::arch::_mm_adds_pu8(transmute(a), transmute(b)))
}
/// Add packed unsigned integers with unsigned saturation
///
/// When an individual byte result is beyond the range of a signed byte integer
/// (that is, greater than `7FH` or less than `80H`), the saturated value of
/// `7FH` or `80H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddusb mm, mm`](http://www.felixcloutier.com/x86/PADDUSB:PADDUSW.html)
///
/// # Examples
///
/// ```
/// let max = u8::max_value();
/// let a = u8x8::new(0, 1, 2, 3, 4, 5, 6, 200);
/// let b = u8x8::new(0, 10, 20, 30, 40, 50, 60, 200);
/// let e = u8x8::new(0, 11, 22, 33, 44, 55, 66, max);
/// assert_eq!(e, _m_paddusb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddusb(a: u8x8, b: u8x8) -> u8x8 {
transmute(::arch::_m_paddusb(transmute(a), transmute(b)))
}
/// Add packed unsigned integers with unsigned saturation
///
/// When an individual word result is beyond the range of a signed word integer
/// (that is, greater than `7FFFH` or less than `8000H`), the saturated value of
/// `7FFFH` or `8000H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddusw mm, mm`](http://www.felixcloutier.com/x86/PADDUSB:PADDUSW.html)
///
/// # Examples
///
/// ```
/// let max = u16::max_value();
/// let a = u16x4::new(0, 1, 2, 60_000);
/// let b = u16x4::new(0, 10, 20, 60_000);
/// let e = u16x4::new(0, 11, 22, max);
/// assert_eq!(e, _m_paddusb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_adds_pu16(a: u16x4, b: u16x4) -> u16x4 {
transmute(::arch::_mm_adds_pu16(
transmute(a),
transmute(b),
))
}
/// Add packed unsigned integers with unsigned saturation
///
/// When an individual word result is beyond the range of a signed word integer
/// (that is, greater than `7FFFH` or less than `8000H`), the saturated value of
/// `7FFFH` or `8000H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`paddusw mm, mm`](http://www.felixcloutier.com/x86/PADDUSB:PADDUSW.html)
///
/// # Examples
///
/// ```
/// let max = u16::max_value();
/// let a = u16x4::new(0, 1, 2, 60_000);
/// let b = u16x4::new(0, 10, 20, 60_000);
/// let e = u16x4::new(0, 11, 22, max);
/// assert_eq!(e, _m_paddusb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_paddusw(a: u16x4, b: u16x4) -> u16x4 {
transmute(::arch::_m_paddusw(transmute(a), transmute(b)))
}
/// Subtract packed integers
///
/// When an individual result is too large or too small to be represented in a
/// byte, the result is wrapped around and the low 8 bits are written to the
/// destination element.
///
/// # Instruction
///
/// [`psubb mm, mm`](http://www.felixcloutier.com/x86/PSUBB:PSUBW:PSUBD.html)
///
/// # Examples
///
/// ```
/// let max = i8::max_value();
/// let min = i8::min_value();
/// let a = i8x8::new( 0, 0, 1, 1, -1, -1, 0, 0);
/// let b = i8x8::new(-1, 1, -2, 2, 100, -100, min, max);
/// let e = i8x8::new( 1, -1, 3, -1, -101, 99, max, min);
/// assert_eq!(e, _mm_sub_pi8(a, b));
///
/// let max = u8::max_value();
/// let a = u8x8::new( 0, 1, 1, 2, 1, 100, 0, max);
/// let b = u8x8::new( 1, 0, 2, 1, 100, 1, max, 0);
/// let e = u8x8::new(max, 1, max, 1, max-100, 99, max, max);
/// assert_eq!(e, _mm_sub_pi8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_sub_pi8<T: IU8x8>(a: T, b: T) -> T {
T::from_m64(::arch::_mm_sub_pi8(a.as_m64(), b.as_m64()))
}
/// Subtract packed integers
///
/// When an individual result is too large or too small to be represented in a
/// byte, the result is wrapped around and the low 8 bits are written to the
/// destination element.
///
/// # Instruction
///
/// [`psubb mm, mm`](http://www.felixcloutier.com/x86/PSUBB:PSUBW:PSUBD.html)
///
/// # Examples
///
/// ```
/// let max = i8::max_value();
/// let min = i8::min_value();
/// let a = i8x8::new( 0, 0, 1, 1, -1, -1, 0, 0);
/// let b = i8x8::new(-1, 1, -2, 2, 100, -100, min, max);
/// let e = i8x8::new( 1, -1, 3, -1, -101, 99, max, min);
/// assert_eq!(e, _m_psubb(a, b));
///
/// let max = u8::max_value();
/// let a = u8x8::new( 0, 1, 1, 2, 1, 100, 0, max);
/// let b = u8x8::new( 1, 0, 2, 1, 100, 1, max, 0);
/// let e = u8x8::new(max, 1, max, 1, max-100, 99, max, max);
/// assert_eq!(e, _m_psubb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubb<T: IU8x8>(a: T, b: T) -> T {
_mm_sub_pi8(a, b)
}
/// Subtract packed integers
///
/// When an individual result is too large or too small to be represented in a
/// byte, the result is wrapped around and the low 16 bits are written to the
/// destination element.
///
/// # Instruction
///
/// [`psubw mm, mm`](http://www.felixcloutier.com/x86/PSUBB:PSUBW:PSUBD.html)
///
/// # Examples
///
/// ```
/// let max = i16::max_value();
/// let min = i16::min_value();
/// let a = i16x4::new( 0, 0, 0, 0);
/// let b = i16x4::new(-1, 1, min, max);
/// let e = i16x4::new( 1, -1, max, min);
/// assert_eq!(e, _mm_sub_pi16(a, b));
///
/// let max = u16::max_value();
/// let a = u16x4::new( 1, 1, 0, 0 );
/// let b = u16x4::new( 2, 0, 1, max );
/// let e = u16x4::new(max, 1, max, max - 1);
/// assert_eq!(e, _mm_sub_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_sub_pi16<T: IU16x4>(a: T, b: T) -> T {
T::from_m64(::arch::_mm_sub_pi16(a.as_m64(), b.as_m64()))
}
/// Subtract packed integers
///
/// When an individual result is too large or too small to be represented in a
/// byte, the result is wrapped around and the low 16 bits are written to the
/// destination element.
///
/// # Instruction
///
/// [`psubw mm, mm`](http://www.felixcloutier.com/x86/PSUBB:PSUBW:PSUBD.html)
///
/// # Examples
///
/// ```
/// let max = i16::max_value();
/// let min = i16::min_value();
/// let a = i16x4::new( 0, 0, 0, 0);
/// let b = i16x4::new(-1, 1, min, max);
/// let e = i16x4::new( 1, -1, max, min);
/// assert_eq!(e, _m_psubw(a, b));
///
/// let max = u16::max_value();
/// let a = u16x4::new( 1, 1, 0, 0 );
/// let b = u16x4::new( 2, 0, 1, max );
/// let e = u16x4::new(max, 1, max, max - 1);
/// assert_eq!(e, _m_psubw(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubw(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_m_psubw(transmute(a), transmute(b)))
}
/// Subtract packed integers
///
/// When an individual result is too large or too small to be represented in a
/// byte, the result is wrapped around and the low 32 bits are written to the
/// destination element.
///
/// # Instruction
///
/// [`psubd mm, mm`](http://www.felixcloutier.com/x86/PSUBB:PSUBW:PSUBD.html)
///
/// # Examples
///
/// ```
/// let max = i32::max_value();
/// let min = i32::min_value();
/// let a = i32x2::new(0, 0);
/// let b = i32x2::new(min, max);
/// let e = i32x2::new(max, min);
/// assert_eq!(e, _mm_sub_pi32(a, b));
///
/// let max = u32::max_value();
/// let a = u32x2::new( 1, 0);
/// let b = u32x2::new( 2, max);
/// let e = u32x2::new(max, max - 1);
/// assert_eq!(e, _mm_sub_pi32(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_sub_pi32(a: i32x2, b: i32x2) -> i32x2 {
transmute(::arch::_mm_sub_pi32(transmute(a), transmute(b)))
}
/// Subtract packed integers
///
/// When an individual result is too large or too small to be represented in a
/// byte, the result is wrapped around and the low 32 bits are written to the
/// destination element.
///
/// # Instruction
///
/// [`psubd mm, mm`](http://www.felixcloutier.com/x86/PSUBB:PSUBW:PSUBD.html)
///
/// # Examples
///
/// ```
/// let max = i32::max_value();
/// let min = i32::min_value();
/// let a = i32x2::new(0, 0);
/// let b = i32x2::new(min, max);
/// let e = i32x2::new(max, min);
/// assert_eq!(e, _m_psubd(a, b));
///
/// let max = u32::max_value();
/// let a = u32x2::new( 1, 0);
/// let b = u32x2::new( 2, max);
/// let e = u32x2::new(max, max - 1);
/// assert_eq!(e, _m_psubd(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubd(a: i32x2, b: i32x2) -> i32x2 {
transmute(::arch::_m_psubd(transmute(a), transmute(b)))
}
/// Subtract packed signed integers with signed saturation
///
/// When an individual byte result is beyond the range of a signed byte integer
/// (that is, greater than `7FH` or less than `80H`), the saturated value of `7FH` or
/// `80H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`psubsb mm, mm`](https://www.felixcloutier.com/x86/PSUBSB:PSUBSW.html)
///
/// # Examples
///
/// ```
/// let max = i8::max_value();
/// let min = i8::min_value();
/// let a = i8x8::new(-100, 100, 0, 0, 0, 0, -5, 5);
/// let b = i8x8::new( 100, -100, min, 127, -1, 1, 3, -3);
/// let e = i8x8::new( min, max, max, -127, 1, -1, -8, 8);
/// assert_eq!(e, _mm_subs_pi8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_subs_pi8(a: i8x8, b: i8x8) -> i8x8 {
transmute(::arch::_mm_subs_pi8(transmute(a), transmute(b)))
}
/// Subtract packed signed integers with signed saturation
///
/// When an individual byte result is beyond the range of a signed byte integer
/// (that is, greater than `7FH` or less than `80H`), the saturated value of `7FH` or
/// `80H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`psubsb mm, mm`](https://www.felixcloutier.com/x86/PSUBSB:PSUBSW.html)
///
/// # Examples
///
/// ```
/// let max = i8::max_value();
/// let min = i8::min_value();
/// let a = i8x8::new(-100, 100, 0, 0, 0, 0, -5, 5);
/// let b = i8x8::new( 100, -100, min, 127, -1, 1, 3, -3);
/// let e = i8x8::new( min, max, max, -127, 1, -1, -8, 8);
/// assert_eq!(e, _m_psubsb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubsb(a: i8x8, b: i8x8) -> i8x8 {
transmute(::arch::_m_psubsb(transmute(a), transmute(b)))
}
/// Subtract packed signed integers with signed saturation
///
/// When an individual word result is beyond the range of a signed word integer
/// (that is, greater than `7FFFH` or less than `8000H`), the saturated value of
/// `7FFFH` or `8000H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`psubsw mm, mm`](https://www.felixcloutier.com/x86/PSUBSB:PSUBSW.html)
///
/// # Examples
///
/// ```
/// let max = i16::max_value();
/// let min = i16::min_value();
/// let a = i16x4::new(-20_000, 20_000, 0, 1);
/// let b = i16x4::new( 20_000, -20_000, min, 127);
/// let e = i16x4::new( min, max, max, -126);
/// assert_eq!(e, _mm_subs_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_subs_pi16(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_mm_subs_pi16(
transmute(a),
transmute(b),
))
}
/// Subtract packed signed integers with signed saturation
///
/// When an individual word result is beyond the range of a signed word integer
/// (that is, greater than `7FFFH` or less than `8000H`), the saturated value of
/// `7FFFH` or `8000H`, respectively, is written to the destination operand.
///
/// # Instruction
///
/// [`psubsw mm, mm`](https://www.felixcloutier.com/x86/PSUBSB:PSUBSW.html)
///
/// # Examples
///
/// ```
/// let max = i16::max_value();
/// let min = i16::min_value();
/// let a = i16x4::new(-20_000, 20_000, 0, 1);
/// let b = i16x4::new( 20_000, -20_000, min, 127);
/// let e = i16x4::new( min, max, max, -126);
/// assert_eq!(e, _m_psubsw(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubsw(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_m_psubsw(transmute(a), transmute(b)))
}
/// Subtract packed unsigned integers with unsigned saturation
///
/// When an individual byte result is less than zero, the saturated value of
/// `00H` is written to the destination operand.
///
/// # Instruction
///
/// [`psubusb mm, mm`](https://www.felixcloutier.com/x86/PSUBUSB:PSUBUSW.html)
///
/// # Examples
///
/// ```
/// let max = u8::max_value();
/// let a = u8x8::new(50, 10, 20, 30, 40, 60, 70, 80);
/// let b = u8x8::new(60, 20, 30, 40, 30, 20, 10, 0);
/// let e = u8x8::new( 0, 0, 0, 0, 10, 40, 60, 80);
/// assert_eq!(e, _mm_subs_pu8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_subs_pu8(a: u8x8, b: u8x8) -> u8x8 {
transmute(::arch::_mm_subs_pu8(transmute(a), transmute(b)))
}
/// Subtract packed unsigned integers with unsigned saturation
///
/// When an individual byte result is less than zero, the saturated value of
/// `00H` is written to the destination operand.
///
/// # Instruction
///
/// [`psubusb mm, mm`](https://www.felixcloutier.com/x86/PSUBUSB:PSUBUSW.html)
///
/// # Examples
///
/// ```
/// let max = u8::max_value();
/// let a = u8x8::new(50, 10, 20, 30, 40, 60, 70, 80);
/// let b = u8x8::new(60, 20, 30, 40, 30, 20, 10, 0);
/// let e = u8x8::new( 0, 0, 0, 0, 10, 40, 60, 80);
/// assert_eq!(e, _m_psubusb(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubusb(a: u8x8, b: u8x8) -> u8x8 {
transmute(::arch::_m_psubusb(transmute(a), transmute(b)))
}
/// Subtract packed unsigned integers with unsigned saturation
///
/// When an individual word result is less than zero, the saturated value of
/// `0000H` is written to the destination operand.
///
/// # Instruction
///
/// [`psubusw mm, mm`](https://www.felixcloutier.com/x86/PSUBUSB:PSUBUSW.html)
///
/// # Examples
///
/// ```
/// let max = u16::max_value();
/// let a = u16x4::new(10000, 200, 0, 44444);
/// let b = u16x4::new(20000, 300, 1, 11111);
/// let e = u16x4::new( 0, 0, 0, 33333);
/// assert_eq!(e, _mm_subs_pu16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_subs_pu16(a: u16x4, b: u16x4) -> u16x4 {
transmute(::arch::_mm_subs_pu16(
transmute(a),
transmute(b),
))
}
/// Subtract packed unsigned integers with unsigned saturation
///
/// When an individual word result is less than zero, the saturated value of
/// `0000H` is written to the destination operand.
///
/// # Instruction
///
/// [`psubusw mm, mm`](https://www.felixcloutier.com/x86/PSUBUSB:PSUBUSW.html)
///
/// # Examples
///
/// ```
/// let max = u16::max_value();
/// let a = u16x4::new(10000, 200, 0, 44444);
/// let b = u16x4::new(20000, 300, 1, 11111);
/// let e = u16x4::new( 0, 0, 0, 33333);
/// assert_eq!(e, _m_psubusw(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _m_psubusw(a: u16x4, b: u16x4) -> u16x4 {
transmute(::arch::_m_psubusw(transmute(a), transmute(b)))
}
/// Pack with signed saturation
///
/// Converts packed signed word integers in `a` and `b` into packed signed byte
/// integers using signed saturation to handle overflow conditions beyond the
/// range of signed byte integers. If the signed doubleword value is beyond the
/// range of an unsigned word (i.e. greater than `7FH` or less than `80H`), the
/// saturated signed byte integer value of `7FH` or `80H`, respectively, is
/// stored in the destination.
///
/// # Instruction
///
/// [`packsswb mm, mm`](https://www.felixcloutier.com/x86/PACKSSWB:PACKSSDW.html)
///
/// # Examples
///
/// ```
/// let min = i8::min_value();
/// let max = i8::max_value();
/// let a = i16x4::new(-1, 2, -200, 4);
/// let b = i16x4::new(-5, 200, -7, 8);
/// let e = i8x8::new(-1, 2, min, 4, -5, max, -7, 8);
/// assert_eq!(e, _mm_packs_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_packs_pi16(a: i16x4, b: i16x4) -> i8x8 {
transmute(::arch::_mm_packs_pi16(
transmute(a),
transmute(b),
))
}
/// Pack with signed saturation
///
/// Converts packed signed word integers in `a` and `b` into packed signed byte
/// integers using signed saturation to handle overflow conditions beyond the
/// range of signed byte integers. If the signed doubleword value is beyond the
/// range of an unsigned word (i.e. greater than `7FFFH` or less than `8000H`),
/// the saturated signed byte integer value of `7FFFH` or `8000H`, respectively,
/// is stored in the destination.
///
/// # Instruction
///
/// [`packssdw mm, mm`](https://www.felixcloutier.com/x86/PACKSSWB:PACKSSDW.html)
///
/// # Examples
///
/// ```
/// let min = i16::min_value();
/// let max = i16::max_value();
/// let a = i32x2::new(-1, 40_000);
/// let b = i32x2::new(-5, -40_000);
/// let e = i16x4::new(-1, max, -5, min);
/// assert_eq!(e, _mm_packs_pi32(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_packs_pi32(a: i32x2, b: i32x2) -> i16x4 {
transmute(::arch::_mm_packs_pi32(
transmute(a),
transmute(b),
))
}
/// Compare packed signed integers for greater than
///
/// If an element in `a` is greater than the corresponding element in `b`, the
/// corresponding element of the result is set to all `1`s; otherwise, it is set
/// to all `0`s.
///
/// # Instruction
///
/// [`pcmpgtb mm, mm`](http://www.felixcloutier.com/x86/PCMPGTB:PCMPGTW:PCMPGTD.html)
///
/// # Examples
///
/// ```
/// let f = 0_i8;
/// let t = -1_i8;
/// let a = i8x8::new(0, 1, 2, 3, 4, 5, 6, 7);
/// let b = i8x8::new(8, 7, 6, 5, 4, 3, 2, 1);
/// let e = i8x8::new(f, f, f, f, f, t, t, t);
/// assert_eq!(e, _mm_cmpgt_pi8(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_cmpgt_pi8(a: i8x8, b: i8x8) -> i8x8 {
// FIXME: return m8x8
transmute(::arch::_mm_cmpgt_pi8(
transmute(a),
transmute(b),
))
}
/// Compare packed signed integers for greater than
///
/// If an element in `a` is greater than the corresponding element in `b`, the
/// corresponding element of the result is set to all `1`s; otherwise, it is set
/// to all `0`s.
///
/// # Instruction
///
/// [`pcmpgtw mm, mm`](http://www.felixcloutier.com/x86/PCMPGTB:PCMPGTW:PCMPGTD.html)
///
/// # Examples
///
/// ```
/// let f = 0_i16;
/// let t = -1_i16;
/// let a = i16x4::new(0, 1, 5, 6);
/// let b = i16x4::new(8, 7, 3, 2);
/// let e = i16x4::new(f, f, t, t);
/// assert_eq!(e, _mm_cmpgt_pi16(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_cmpgt_pi16(a: i16x4, b: i16x4) -> i16x4 {
// FIXME: return m16x4
transmute(::arch::_mm_cmpgt_pi16(
transmute(a),
transmute(b),
))
}
/// Compare packed signed integers for greater than
///
/// If an element in `a` is greater than the corresponding element in `b`, the
/// corresponding element of the result is set to all `1`s; otherwise, it is set
/// to all `0`s.
///
/// # Instruction
///
/// [`pcmpgtd mm, mm`](http://www.felixcloutier.com/x86/PCMPGTB:PCMPGTW:PCMPGTD.html)
///
/// # Examples
///
/// ```
/// let f = 0_i32;
/// let t = -1_i32;
/// let a = i32x2::new(0, 5);
/// let b = i32x2::new(8, 3);
/// let e = i32x2::new(f, t);
/// assert_eq!(e, _mm_cmpgt_pi32(a, b));
/// ```
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_cmpgt_pi32(a: i32x2, b: i32x2) -> i32x2 {
// FIXME: return m32x2
transmute(::arch::_mm_cmpgt_pi32(
transmute(a),
transmute(b),
))
}
/// Unpack high interleaved: `[a.2, b.2, a.3, b.3]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_unpackhi_pi16(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_mm_unpackhi_pi16(
transmute(a),
transmute(b),
))
}
/// Unpack higher elements interleaved: `[a.4, b.4, a.5, b.5, a.6, b.6, a.7, b.7]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_unpackhi_pi8(a: i8x8, b: i8x8) -> i8x8 {
transmute(::arch::_mm_unpackhi_pi8(
transmute(a),
transmute(b),
))
}
/// Unpack lower elements interleaved: `[a.0, b.0, a.1, b.1, a.2, b.2, a.3, b.3]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_unpacklo_pi8(a: i8x8, b: i8x8) -> i8x8 {
transmute(::arch::_mm_unpacklo_pi8(
transmute(a),
transmute(b),
))
}
/// Unpack lower elements interleaved: `[a.0 b.0 a.1 b.1]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_unpacklo_pi16(a: i16x4, b: i16x4) -> i16x4 {
transmute(::arch::_mm_unpacklo_pi16(
transmute(a),
transmute(b),
))
}
/// Unpack higher elements interleaved: `[a.1, b.1]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_unpackhi_pi32(a: i32x2, b: i32x2) -> i32x2 {
transmute(::arch::_mm_unpackhi_pi32(
transmute(a),
transmute(b),
))
}
/// Unpack lower elements interleaved: [a.0, b.0]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_unpacklo_pi32(a: i32x2, b: i32x2) -> i32x2 {
transmute(::arch::_mm_unpacklo_pi32(
transmute(a),
transmute(b),
))
}
/// Instantiate: `[e0, e1, e2, e3]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_set_pi16(e0: i16, e1: i16, e2: i16, e3: i16) -> i16x4 {
transmute(::arch::_mm_set_pi16(
transmute(e0),
transmute(e1),
transmute(e2),
transmute(e3),
))
}
/// Instantiate: `[e0, e1]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_set_pi32(e0: i32, e1: i32) -> i32x2 {
transmute(::arch::_mm_set_pi32(
transmute(e0),
transmute(e1),
))
}
/// Instantiate: `[e0, e1, e2, e3, e4, e5, e6, e7]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_set_pi8(
e0: i8, e1: i8, e2: i8, e3: i8, e4: i8, e5: i8, e6: i8, e7: i8
) -> i8x8 {
transmute(::arch::_mm_set_pi8(
transmute(e0),
transmute(e1),
transmute(e2),
transmute(e3),
transmute(e4),
transmute(e5),
transmute(e6),
transmute(e7),
))
}
/// Broadcast: `[a, a, a, a]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_set1_pi16(a: i16) -> i16x4 {
transmute(::arch::_mm_set1_pi16(transmute(a)))
}
/// Broadcast: `[a, a]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_set1_pi32(a: i32) -> i32x2 {
transmute(::arch::_mm_set1_pi32(transmute(a)))
}
/// Broadcast: `[a, a, a, a, a, a, a, a]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_set1_pi8(a: i8) -> i8x8 {
transmute(::arch::_mm_set1_pi8(transmute(a)))
}
/// Instantiate reverse: `[e3, e2, e1, e0]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_setr_pi16(e0: i16, e1: i16, e2: i16, e3: i16) -> i16x4 {
transmute(::arch::_mm_setr_pi16(
transmute(e0),
transmute(e1),
transmute(e2),
transmute(e3),
))
}
/// Instantiate reverse: `[e1, e0]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_setr_pi32(e0: i32, e1: i32) -> i32x2 {
transmute(::arch::_mm_setr_pi32(
transmute(e0),
transmute(e1),
))
}
/// Instantiate reverse: `[e7, e6, e5, e4, e3, e2, e1, e0]`
#[inline]
#[target_feature(enable = "mmx")]
pub unsafe fn _mm_setr_pi8(
e0: i8, e1: i8, e2: i8, e3: i8, e4: i8, e5: i8, e6: i8, e7: i8
) -> i8x8 {
transmute(::arch::_mm_setr_pi8(
transmute(e0),
transmute(e1),
transmute(e2),
transmute(e3),
transmute(e4),
transmute(e5),
transmute(e6),
transmute(e7),
))
}
|
//! Module contains a list of backends for pretty print tables.
pub mod compact;
#[cfg(feature = "std")]
pub mod iterable;
#[cfg(feature = "std")]
pub mod peekable;
|
use std::sync::mpsc::SyncSender;
use std::thread;
use crate::mechatronics::commands::RobotCommand;
/// The controller module contains the `RobotController` struct.
/// The `RobotController` struct owns instances of the `DriveTrain` and the `MaterialHandler`.
pub mod controller;
pub mod commands;
/// The drive_train module contains the `DriveTrain` struct.
/// That structure is used to manage the physical drive train and perform operations on it.
pub mod drive_train;
pub mod dumper;
pub mod bucket_ladder;
#[cfg(test)]
mod tests;
pub struct RobotMessenger {
channel: SyncSender<Box<RobotCommand>>,
}
impl RobotMessenger {
pub fn new(channel: SyncSender<Box<RobotCommand>>) -> Self {
Self {
channel,
}
}
#[inline]
pub fn send_command(&self, command: Box<RobotCommand>) {
self.channel.send(command).unwrap();
thread::yield_now()
}
} |
pub use crate::core::{
clients::{AsStorageClient, StorageAccountClient, StorageClient},
shared_access_signature::{
account_sas::{
AccountSasPermissions, AccountSasResource, AccountSasResourceType,
ClientAccountSharedAccessSignature, SasExpirySupport, SasPermissionsSupport,
SasProtocolSupport, SasResourceSupport, SasResourceTypeSupport, SasStartSupport,
},
service_sas::{BlobSasPermissions, BlobSignedResource},
SasProtocol, SasToken,
},
{ConsistencyCRC64, ConsistencyMD5, CopyId, IPRange},
};
|
use std::fmt;
use std::time::Duration;
/// Represents parameters of "gameover" command.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum GameOverKind {
Win,
Lose,
Draw,
}
impl fmt::Display for GameOverKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GameOverKind::Win => write!(f, "win"),
GameOverKind::Lose => write!(f, "lose"),
GameOverKind::Draw => write!(f, "draw"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MateParam {
Timeout(Duration),
Infinite,
}
/// Represents parameters of "go" command.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct ThinkParams {
ponder: bool,
btime: Option<Duration>,
wtime: Option<Duration>,
byoyomi: Option<Duration>,
binc: Option<Duration>,
winc: Option<Duration>,
infinite: bool,
mate: Option<MateParam>,
}
impl ThinkParams {
pub fn new() -> Self {
ThinkParams::default()
}
#[must_use]
pub fn ponder(mut self) -> Self {
self.ponder = true;
self
}
#[must_use]
pub fn btime(mut self, t: Duration) -> Self {
self.btime = Some(t);
self
}
#[must_use]
pub fn wtime(mut self, t: Duration) -> Self {
self.wtime = Some(t);
self
}
#[must_use]
pub fn byoyomi(mut self, t: Duration) -> Self {
self.byoyomi = Some(t);
self
}
#[must_use]
pub fn binc(mut self, t: Duration) -> Self {
self.binc = Some(t);
self
}
#[must_use]
pub fn winc(mut self, t: Duration) -> Self {
self.winc = Some(t);
self
}
#[must_use]
pub fn infinite(mut self) -> Self {
self.infinite = true;
self
}
#[must_use]
pub fn mate(mut self, t: MateParam) -> Self {
self.mate = Some(t);
self
}
}
impl fmt::Display for ThinkParams {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.ponder {
write!(f, " ponder")?;
}
if let Some(t) = self.btime {
write!(f, " btime {}", to_ms(t))?;
}
if let Some(t) = self.wtime {
write!(f, " wtime {}", to_ms(t))?;
}
if let Some(t) = self.byoyomi {
write!(f, " byoyomi {}", to_ms(t))?;
}
if let Some(t) = self.binc {
write!(f, " binc {}", to_ms(t))?;
}
if let Some(t) = self.winc {
write!(f, " winc {}", to_ms(t))?;
}
if self.infinite {
write!(f, " infinite")?;
}
if let Some(mate_opts) = &self.mate {
match *mate_opts {
MateParam::Timeout(t) => write!(f, " mate {}", to_ms(t))?,
MateParam::Infinite => write!(f, " mate infinite")?,
}
}
Ok(())
}
}
/// Represents a USI command sent from the GUI.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use usi::{GuiCommand, ThinkParams};
///
/// let params = ThinkParams::new().btime(Duration::from_secs(1)).wtime(Duration::from_secs(2));
/// let cmd = GuiCommand::Go(params);
///
/// assert_eq!("go btime 1000 wtime 2000", cmd.to_string());
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum GuiCommand {
GameOver(GameOverKind),
Go(ThinkParams),
IsReady,
Ponderhit,
Position(String),
SetOption(String, Option<String>),
Stop,
Usi,
UsiNewGame,
Quit,
}
impl fmt::Display for GuiCommand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GuiCommand::GameOver(ref r) => write!(f, "gameover {r}"),
GuiCommand::Go(ref opt) => write!(f, "go{opt}"),
GuiCommand::IsReady => write!(f, "isready"),
GuiCommand::Ponderhit => write!(f, "ponderhit"),
GuiCommand::Position(ref s) => write!(f, "position sfen {s}"),
GuiCommand::SetOption(ref n, None) => write!(f, "setoption name {n}"),
GuiCommand::SetOption(ref n, Some(ref v)) => {
write!(f, "setoption name {n} value {v}")
}
GuiCommand::Stop => write!(f, "stop"),
GuiCommand::Usi => write!(f, "usi"),
GuiCommand::UsiNewGame => write!(f, "usinewgame"),
GuiCommand::Quit => write!(f, "quit"),
}
}
}
fn to_ms(t: Duration) -> u64 {
1000 * t.as_secs() + (t.subsec_nanos() as u64) / 1_000_000
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_string() {
let cases = [
("gameover win", GuiCommand::GameOver(GameOverKind::Win)),
("gameover draw", GuiCommand::GameOver(GameOverKind::Draw)),
("gameover lose", GuiCommand::GameOver(GameOverKind::Lose)),
(
"go btime 60000 wtime 50000 byoyomi 10000",
GuiCommand::Go(
ThinkParams::new()
.btime(Duration::from_secs(60))
.wtime(Duration::from_secs(50))
.byoyomi(Duration::from_secs(10)),
),
),
(
"go btime 40000 wtime 50000 binc 10000 winc 10000",
GuiCommand::Go(
ThinkParams::new()
.btime(Duration::from_secs(40))
.wtime(Duration::from_secs(50))
.binc(Duration::from_secs(10))
.winc(Duration::from_secs(10)),
),
),
("go infinite", GuiCommand::Go(ThinkParams::new().infinite())),
(
"go mate 60000",
GuiCommand::Go(
ThinkParams::new().mate(MateParam::Timeout(Duration::from_secs(60))),
),
),
(
"go mate infinite",
GuiCommand::Go(ThinkParams::new().mate(MateParam::Infinite)),
),
("go ponder", GuiCommand::Go(ThinkParams::new().ponder())),
("isready", GuiCommand::IsReady),
("ponderhit", GuiCommand::Ponderhit),
(
"position sfen lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1",
GuiCommand::Position(
"lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL \
w - 1"
.to_string(),
),
),
(
"setoption name foo",
GuiCommand::SetOption("foo".to_string(), None),
),
(
"setoption name foo value bar",
GuiCommand::SetOption("foo".to_string(), Some("bar".to_string())),
),
("stop", GuiCommand::Stop),
("usi", GuiCommand::Usi),
("usinewgame", GuiCommand::UsiNewGame),
("quit", GuiCommand::Quit),
];
for c in &cases {
assert_eq!(c.0, c.1.to_string());
}
}
}
|
use json::{JsonValue};
use v2::V2;
pub struct MyV2(pub V2);
use gamestate::{GameState, Player, Pickup, PickupType};
impl<'a> From<&'a PickupType> for JsonValue {
fn from(v : &'a PickupType) -> JsonValue {
format!("{:?}", v).into()
}
}
impl<'a> From<&'a MyV2> for JsonValue {
fn from(v : &'a MyV2) -> JsonValue {
object!{
"x" => v.0.x,
"y" => v.0.y,
}
}
}
impl<'a> From<&'a Pickup> for JsonValue {
fn from(o : &'a Pickup) -> JsonValue {
object!{
"uuid" => o.uuid,
"pos" => &MyV2(o.pos),
"time" => o.time,
"pickupType" => &o.pickup_type,
}
}
}
impl<'a> From<&'a Player> for JsonValue {
fn from(o : &'a Player) -> JsonValue {
object!{
"uuid" => o.uuid,
"pos" => &MyV2(o.pos),
"vel" => &MyV2(o.vel),
"scale" => o.scale,
"score" => o.score,
"name" => o.name.clone(),
}
}
}
impl<'a > From<&'a GameState> for JsonValue {
fn from(o : &'a GameState) -> JsonValue {
let players : Vec<&'a Player> = o.players.iter().map(|(_k,v)| v).collect();
let pickups : Vec<&'a Pickup> = o.pickups.iter().map(|(_k,v)| v).collect();
let ret = object!{
"objs" => pickups,
"time" => 0,
"players" => players
};
ret
}
}
|
use super::lock::spin::SpinMutex;
use super::memory::{Page, PAGE_SIZE};
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr::NonNull;
use utils::prelude::*;
use linked_list_allocator::Heap;
pub struct KernelHeap {
heap: SpinMutex<Heap>,
}
unsafe impl GlobalAlloc for KernelHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.heap
.lock()
.allocate_first_fit(layout)
.unwrap()
.as_ptr()
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
debug_assert!(!ptr.is_null());
self.heap
.lock()
.deallocate(NonNull::new_unchecked(ptr), layout);
}
}
impl KernelHeap {
pub unsafe fn init(&self, start: usize, size: usize) {
self.heap.lock().init(start, size);
}
pub unsafe fn extend(&self, size: usize) {
self.heap.lock().extend(size);
}
}
#[global_allocator]
static HEAP: KernelHeap = KernelHeap {
heap: SpinMutex::new("kheap", Heap::empty()),
};
#[alloc_error_handler]
fn alloc_error_handler(layout: Layout) -> ! {
panic!("allocation error: {:?}", layout)
}
/// Initialization happens in two phases.
/// 1. main() calls kalloc::init1() while still using entry_page_dir to place just
/// the pages mapped by entry_page_dir on free list.
/// 2. main() calls kalloc::init2() with the rest of the physical pages
/// after installing a full page table that maps them on all cores.
pub fn init1(start: VAddr<u8>, end: VAddr<u8>) {
let size = end.raw() - start.raw();
unsafe { HEAP.init(start.raw(), size) };
}
pub fn init2(start: VAddr<u8>, end: VAddr<u8>) {
let size = end.raw() - start.raw();
unsafe { HEAP.extend(size) };
}
/// Free the page of physical memory pointed at by page,
/// which normally should have been returned by a call to kalloc().
pub fn kfree(page: NonNull<Page>) {
let layout = Layout::from_size_align(PAGE_SIZE, PAGE_SIZE).unwrap();
unsafe { HEAP.dealloc(page.as_ptr() as *mut u8, layout) };
}
/// Allocate one 4096-byte page of physical memory.
/// Returns a pointer that the kernel can use.
/// Returns None if the memory cannot be allocated.
pub fn kalloc() -> Option<NonNull<Page>> {
let layout = Layout::from_size_align(PAGE_SIZE, PAGE_SIZE).unwrap();
let page = unsafe { HEAP.alloc(layout) };
NonNull::new(page as *mut Page)
}
|
use std::collections::HashMap;
/*
There is a mathematical solution to this -- it's very similar to an older
problem I've seen, which wanted people to solve for the values at the corner
of this spiral square.
But to make this a better Rust problem, I'm gonna try a state-machiney thing.
*/
#[derive(Hash, Eq, PartialEq, Clone)]
struct Pair {
x: i32,
y: i32,
}
struct Spiral {
i: i32, // current index
cur: Pair, // current coordinate
dir: Pair, // direction vector
max: Pair, // top right corner
min: Pair, // bottom left corner
value: i32, // value of current cell
values: HashMap<Pair,i32>,
}
impl Default for Spiral {
fn default() -> Spiral {
Spiral {
i: 1,
value: 1,
cur: Pair { x: 0, y: 0 },
dir: Pair { x: 1, y: 0 },
max: Pair { x: 0, y: 0 },
min: Pair { x: 0, y: 0 },
values: HashMap::new(),
}
}
}
impl Spiral {
fn manhattan_distance(&self) -> i32 {
return self.cur.x.abs() + self.cur.y.abs();
}
}
fn advance_spiral(spiral: &mut Spiral, calculate_values: bool) -> () {
let new = Pair {
x: spiral.cur.x + spiral.dir.x,
y: spiral.cur.y + spiral.dir.y,
};
// always turn left
if new.x > spiral.max.x { // was going right; turn up
spiral.dir = Pair { x: 0, y: 1 };
spiral.max.x = new.x;
}
else if new.x < spiral.min.x { // was going left; turn down
spiral.dir = Pair { x: 0, y: -1 };
spiral.min.x = new.x;
}
else if new.y > spiral.max.y { // was going up; turn left
spiral.dir = Pair { x: -1, y: 0 };
spiral.max.y = new.y;
}
else if new.y < spiral.min.y { // was going down; turn right
spiral.dir = Pair { x: 1, y: 0 };
spiral.min.y = new.y;
}
if calculate_values {
// sum all adjacent values
let adjacent_pairs = [
Pair { x: new.x, y: new.y },
Pair { x: new.x, y: new.y+1 },
Pair { x: new.x, y: new.y-1 },
Pair { x: new.x+1, y: new.y },
Pair { x: new.x+1, y: new.y+1 },
Pair { x: new.x+1, y: new.y-1 },
Pair { x: new.x-1, y: new.y },
Pair { x: new.x-1, y: new.y+1 },
Pair { x: new.x-1, y: new.y-1 },
];
spiral.value = adjacent_pairs
.iter()
.flat_map(|pair| spiral.values.get(pair))
.sum();
spiral.values.insert(new.clone(), spiral.value);
}
spiral.cur = new;
spiral.i += 1;
}
// Returns the ith spiral.
fn get_spiral_at_index(i: i32) -> Spiral {
let mut spiral = Spiral { ..Default::default() };
while spiral.i < i { advance_spiral(&mut spiral, false); }
return spiral;
}
// Returns the first spiral whose current cell has a value above `value`.
fn get_next_spiral_after_value(value: i32) -> Spiral {
let mut spiral = Spiral { ..Default::default() };
// would love to move this line into the default() implementation,
// but I can't figure out how
spiral.values.insert(spiral.cur.clone(), spiral.value);
while spiral.value < value { advance_spiral(&mut spiral, true); }
return spiral;
}
fn main() {
let input = 368078;
println!("Part 1 answer: {}", get_spiral_at_index(input).manhattan_distance());
println!("Part 2 answer: {}", get_next_spiral_after_value(input).value);
}
|
extern crate futures;
extern crate tokio_core;
extern crate tokio_timer;
extern crate env_logger;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
pub mod codec;
pub mod message;
use codec::TplinkSmartHomeCodec;
use message::*;
use std::io;
use std::time::Duration;
use std::net::SocketAddr;
use futures::{Future, Stream, Sink};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
use tokio_timer::Timer;
fn make_request_wait_for_response(request: Message, device_addr: SocketAddr, wait: Duration, count: u64) -> Result<Message, io::Error> {
drop(env_logger::init());
let mut core = Core::new().unwrap();
let handle = core.handle();
let src: SocketAddr = "0.0.0.0:0".parse().unwrap();
let sock = UdpSocket::bind(&src, &handle)?;
sock.set_broadcast(true)?;
let (mut sink, stream) = sock.framed(TplinkSmartHomeCodec).split();
let timer = Timer::default();
let timeout = timer.sleep(wait);
println!("<<<<<<<<<<<\n{}", serde_json::to_string(&request).unwrap());
sink.start_send((device_addr,Some(request)))?;
let mut response = None;
{
let stream = stream.take(count).map(|(addr, msg)| {
println!(">>>>>>>>>>>>\n{}", serde_json::to_string(&msg).unwrap());
response = Some(msg.unwrap());
(addr, None)
});
let sock = sink.send_all(stream);
let sock = sock.select2(timeout);
drop(core.run(sock));
}
response.ok_or(io::Error::new(io::ErrorKind::TimedOut, "timeout waiting for response"))
}
pub fn get_sysinfo(device_addr: SocketAddr) -> Result<Message, io::Error> {
let request = Message::get_sys_info();
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
pub fn get_details(device_addr: SocketAddr) -> Result<Message, io::Error> {
let request = Message::get_details();
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
pub fn on(device_addr: SocketAddr) -> Result<Message, io::Error> {
let request = Message::on();
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
pub fn off(device_addr: SocketAddr) -> Result<Message, io::Error> {
let request = Message::off();
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
pub fn hsv(device_addr: SocketAddr, h: u16, s:u8, v: u8) -> Result<Message, io::Error> {
let request = Message::hsv(h, s, v);
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
pub fn temp(device_addr: SocketAddr, t: u16, b: u8) -> Result<Message, io::Error> {
let request = Message::temp(t, b);
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
pub fn circadian(device_addr: SocketAddr) -> Result<Message, io::Error> {
let request = Message::circadian();
make_request_wait_for_response(request, device_addr, Duration::from_secs(3), 1)
}
|
pub mod encode;
pub mod decode;
pub mod endian;
pub mod buffer;
|
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
if n < 4 {
if n == 1 {
return vec![vec!["Q".to_string()]]
}
return vec![]
}
let n = n as usize;
let mut result = vec![];
fn core(index: usize, v: &mut Vec<usize>, r: &mut Vec<Vec<usize>>, push_two: bool) {
let n = v.len();
if index == n {
r.push(v.clone());
if push_two {
r.push(v.into_iter().map(|x| n-1-*x).collect());
}
return
}
'outer: for i in 0..n {
for j in 0..index {
if v[j] == i || v[j] + j == i + index || v[j] + index == i + j {
continue 'outer
}
}
v[index] = i;
core(index+1, v, r, push_two)
}
}
for i in 0..n/2 {
let mut v = vec![0; n];
v[0] = i;
core(1, &mut v, &mut result, true);
}
if n % 2 == 1 {
let mut v = vec![0; n];
v[0] = n/2;
core(1, &mut v, &mut result, false);
}
result.iter().map(|v| {
let template = vec!['.'; n];
let mut r = vec![];
for i in 0..n {
let mut tmp = template.clone();
tmp[v[i]] = 'Q';
r.push(tmp.iter().collect())
}
r
}).collect()
}
#[test]
fn test_solve_n_queens() {
assert_eq!(solve_n_queens(4).len(), 2);
assert_eq!(solve_n_queens(8).len(), 92);
assert_eq!(solve_n_queens(9).len(), 352);
}
|
// if let
//
// 变量赋值时把`if`作为一个表达式。
//
// 表达式的值是任何被选择的分支的最后一个表达式的值。
//
fn main() {
sample1();
no_else();
}
fn sample1() {
// 普通的if in let表达式
let x = if true { 1 } else { 0 };
assert_eq!(x, 1);
// 不会执行的分支内加上宏定义, 没有返回值, 也能编译通过.
let x = if true { 1 } else { unreachable!() };
assert_eq!(x, 1);
}
// 如果表达式只用if没有else, 则必须返回一个空元祖`()`
fn no_else() {
let x = if true {
// 这里不能返回任何`()`以外的值, 否则编译报错
};
assert_eq!(x, ());
// `if`条件不成立的时候, 同样返回`()`
let x = if false {};
assert_eq!(x, ());
}
/* NOTE: 分支内变量类型必须一致, 否则导致编译报错, 如:
* let x = if true { 1 } else { "hello" };
*/
|
use std::collections::HashSet;
use std::fs;
use std::path::Path;
fn main() {
let data = read_file("./input/input.txt").unwrap();
// data.sort();
println!("{:?}", data);
println!("{:?}", part1(data.clone()));
println!("{:?}", part2(data.clone()));
}
fn part1(data: Vec<i64>) -> std::result::Result<i64, String> {
// let mut processed_data = data.clone();
// for (idx, val_a) in data.iter().enumerate() {
// let (_left, right) = processed_data.split_at_mut(idx);
// for val_b in right.iter() {
// if val_a + val_b > 2020 {
// break;
// }
// if val_a + val_b == 2020 {
// println!("found val_a: {:?} val_b: {:?}", val_a, val_b);
// return Ok(val_a * val_b);
// }
// }
// }
let mut set: HashSet<i64> = HashSet::new();
for val_b in data.iter() {
if set.contains(&(2020 - val_b)) {
println!("found valA: {:?} valB: {:?}", (2020 - val_b), val_b);
return Ok((2020 - val_b) * val_b);
}
set.insert(*val_b);
}
Err("Not found double".to_string())
}
fn part2(data: Vec<i64>) -> std::result::Result<i64, String> {
let mut processed_data = data.clone();
for (idx, val_a) in data.iter().enumerate() {
let mut set: HashSet<i64> = HashSet::new();
let sum = 2020 - val_a;
let (_left, right) = processed_data.split_at_mut(idx);
for val_b in right.iter() {
if set.contains(&(sum - val_b)) {
println!(
"found valA: {:?} val_b: {:?}, val_c: {:?}",
val_a,
val_b,
sum - val_b
);
return Ok(val_a * val_b * (sum - val_b));
}
set.insert(*val_b);
}
}
Err("Not found triplet".to_string())
}
fn read_file<P>(filename: P) -> std::result::Result<Vec<i64>, ::std::num::ParseIntError>
where
P: AsRef<Path>,
{
fs::read_to_string(filename)
.expect("Failed to load file")
.lines()
.flat_map(|l| l.split_whitespace())
.map(|int| int.parse::<i64>())
.collect()
}
|
// MESSAGES FROM HANDLERS TO THE APPLICATION
use actix::prelude::*;
use crate::game_folder::game::Game;
/// Check if a game exists
/// ```
/// #[rtype(bool)]
/// pub struct DoesGameExist {
/// pub game_id: String,
/// }
/// ```
#[derive(Message)]
#[rtype(bool)]
pub struct DoesGameExist {
pub game_id: String,
}
/// Check if a game is open to players joining
/// ```
/// #[rtype(bool)]
/// pub struct IsGameOpen {
/// pub game_id: String,
/// }
/// ```
#[derive(Message)]
#[rtype(bool)]
pub struct IsGameOpen {
pub game_id: String,
}
/// Check if this is the Right Director Password
/// ```
/// #[rtype(bool)]
/// pub struct IsRightPswd {
/// pub pswd: String,
/// }
/// ```
#[derive(Message)]
#[rtype(bool)]
pub struct IsRightPswd {
pub pswd: String,
}
/// Register a new player's ID in a game
/// ```
/// #[rtype(String)]
/// pub struct NewPlayer {
/// pub user_id: String,
/// pub game_id: String,
/// pub username: String,
/// }
/// ```
#[derive(Message)]
#[rtype(String)]
pub struct NewPlayer {
pub user_id: String,
pub game_id: String,
pub username: String,
}
/// Register ANOTHER director in a game
/// ```
/// #[rtype(result="()")]
/// pub struct NewDirector {
/// pub user_id: String,
/// pub game_id: String,
/// pub username: String,
/// }
/// ```
#[derive(Message)]
#[rtype(result = "()")]
pub struct NewDirector {
pub user_id: String,
pub game_id: String,
pub username: String,
}
#[derive(Message)]
#[rtype(bool)]
pub struct NewViewer {
pub user_id: String,
pub game_id: String,
pub username: String,
}
/// Create a new game
/// ```
/// #[rtype(result="()")]
/// pub struct NewGame {
/// pub user_id: String,
/// pub game_id: String,
/// pub username: String,
/// }
/// ```
#[derive(Message)]
#[rtype(result = "()")]
pub struct NewGame {
pub user_id: String,
pub username: String,
pub game_id: String,
}
/// Prevent main directors from joining other games
/// ```
/// #[rtype(result="()")]
/// pub struct NewGame {
/// pub user_id: String,
/// pub game_id: String,
/// pub username: String,
/// }
/// ```
#[derive(Message)]
#[rtype(bool)]
pub struct IsMainDirector {
pub game_id: String,
pub user_id: String,
}
/// See if a director with this ID was previously authenticated and if so, return the correct game address and username
#[derive(Message)]
#[rtype(result = "Option<(Addr<Game>, String)>")]
pub struct IsRegisteredDirector {
pub user_id: String,
pub game_id: String,
}
/// See if producer or consumer with this ID was previously authenticated and if so, return the correct game address and username
#[derive(Message)]
#[rtype(result = "Option<(Addr<Game>, String)>")]
pub struct IsRegisteredPlayer {
pub user_id: String,
pub game_id: String,
}
#[derive(Message)]
#[rtype(result = "Option<(Addr<Game>, String)>")]
pub struct IsRegisteredViewer {
pub user_id: String,
pub game_id: String,
}
|
#![deny(unsafe_op_in_unsafe_fn)]
use parking_lot::Mutex;
use pymemprofile_api::memorytracking::LineNumberInfo::LineNumber;
use pymemprofile_api::memorytracking::{
AllocationTracker, CallSiteId, Callstack, FunctionId, IdentityCleaner, VecFunctionLocations,
PARENT_PROCESS,
};
use pymemprofile_api::oom::{InfiniteMemory, OutOfMemoryEstimator, RealMemoryInfo};
use std::cell::RefCell;
use std::ffi::CStr;
use std::os::raw::{c_char, c_int, c_void};
use std::path::Path;
#[macro_use]
extern crate lazy_static;
#[cfg(target_os = "linux")]
use tikv_jemallocator::Jemalloc;
#[cfg(target_os = "linux")]
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
thread_local!(static THREAD_CALLSTACK: RefCell<Callstack> = RefCell::new(Callstack::new()));
struct TrackerState {
oom: OutOfMemoryEstimator,
allocations: AllocationTracker<VecFunctionLocations>,
}
lazy_static! {
static ref TRACKER_STATE: Mutex<TrackerState> = Mutex::new(TrackerState {
allocations: AllocationTracker::new("/tmp".to_string(), VecFunctionLocations::new()),
oom: OutOfMemoryEstimator::new(
if std::env::var("__FIL_DISABLE_OOM_DETECTION") == Ok("1".to_string()) {
Box::new(InfiniteMemory {})
} else {
Box::new(RealMemoryInfo::default())
}
),
});
}
/// Register a new function/filename location.
fn add_function(filename: String, function_name: String) -> FunctionId {
let tracker_state = TRACKER_STATE.try_lock();
if let Some(mut tracker_state) = tracker_state {
tracker_state
.allocations
.functions
.add_function(filename, function_name)
} else {
// This will help in SIGUSR2 handler: dumping calls into Python, we
// can't really acquire lock since it's in the middle of dumping. So
// just give up.
FunctionId::UNKNOWN
}
}
/// Add to per-thread function stack:
fn start_call(call_site: FunctionId, parent_line_number: u16, line_number: u16) {
THREAD_CALLSTACK.with(|cs| {
cs.borrow_mut().start_call(
parent_line_number as u32,
CallSiteId::new(call_site, LineNumber(line_number as u32)),
);
});
}
/// Finish off (and move to reporting structure) current function in function
/// stack.
fn finish_call() {
THREAD_CALLSTACK.with(|cs| {
cs.borrow_mut().finish_call();
});
}
/// Get the current thread's callstack.
fn get_current_callstack() -> Callstack {
THREAD_CALLSTACK.with(|cs| (*cs.borrow()).clone())
}
/// Set the current callstack. Typically should only be used when starting up
/// new threads.
fn set_current_callstack(callstack: &Callstack) {
THREAD_CALLSTACK.with(|cs| {
*cs.borrow_mut() = callstack.clone();
})
}
extern "C" {
fn _exit(exit_code: std::os::raw::c_int);
fn free(address: *mut c_void);
}
/// Add a new allocation based off the current callstack.
///
/// This can fail if the thread local with the Python stack is not available.
/// This only happens during thread exit where an allocation can sometimes be
/// triggered during thread-local cleanup for some reason.
fn add_allocation(
address: usize,
size: usize,
line_number: u16,
is_mmap: bool,
) -> Result<(), std::thread::AccessError> {
let mut tracker_state = TRACKER_STATE.lock();
let current_allocated_bytes = tracker_state.allocations.get_current_allocated_bytes();
// Check if we're out of memory:
let oom = (address == 0)
|| tracker_state
.oom
.too_big_allocation(size, current_allocated_bytes);
// If we're out-of-memory, we're not going to exit this function or ever
// free() anything ever again, so we should clear some memory in order to
// reduce chances of running out as part of OOM reporting. We can also free
// the allocation that just happened, cause it's never going to be used.
if oom {
if address == 0 {
eprintln!(
"=fil-profile= WARNING: Allocation of size {} failed (mmap()? {})",
size, is_mmap
);
} else {
unsafe {
let address = address as *mut c_void;
if is_mmap {
(pymemprofile_api::ffi::LIBC.munmap)(address, size);
} else {
free(address);
}
}
}
tracker_state.allocations.oom_break_glass();
eprintln!("=fil-profile= WARNING: Detected out-of-memory condition, exiting soon.");
tracker_state.oom.print_info();
}
let allocations = &mut tracker_state.allocations;
// Will fail during thread shutdown, but not much we can do at that point.
let callstack_id = THREAD_CALLSTACK.try_with(|tcs| {
let mut callstack = tcs.borrow_mut();
callstack.id_for_new_allocation(line_number as u32, |callstack| {
allocations.get_callstack_id(callstack)
})
})?;
if is_mmap {
allocations.add_anon_mmap(PARENT_PROCESS, address, size, callstack_id);
} else {
allocations.add_allocation(PARENT_PROCESS, address, size, callstack_id);
}
if oom {
// Uh-oh, we're out of memory.
eprintln!(
"=fil-profile= We'll try to dump out SVGs. Note that no HTML file will be written."
);
let default_path = allocations.default_path.clone();
// Release the lock, since dumping the flamegraph will reacquire it:
drop(tracker_state);
dump_to_flamegraph(
&default_path,
false,
"out-of-memory",
"Current allocations at out-of-memory time",
false,
);
unsafe {
_exit(53);
}
};
Ok(())
}
/// Free an existing allocation.
fn free_allocation(address: usize) {
let mut tracker_state = TRACKER_STATE.lock();
let allocations = &mut tracker_state.allocations;
allocations.free_allocation(PARENT_PROCESS, address);
}
/// Get the size of an allocation, or 0 if it's not tracked.
fn get_allocation_size(address: usize) -> usize {
let tracker_state = TRACKER_STATE.lock();
let allocations = &tracker_state.allocations;
allocations.get_allocation_size(PARENT_PROCESS, address)
}
/// Reset internal state.
fn reset(default_path: String) {
// Make sure we initialize this static, to prevent deadlocks:
pymemprofile_api::ffi::initialize();
let mut tracker_state = TRACKER_STATE.lock();
tracker_state.allocations.reset(default_path);
}
fn dump_to_flamegraph(
path: &str,
peak: bool,
base_filename: &str,
title: &str,
to_be_post_processed: bool,
) {
// In order to render the flamegraph, we want to load source code using
// Python's linecache. That means calling into Python, which might release
// the GIL, allowing another thread to run, and it will try to allocation
// and hit the TRACKER_STATE mutex. And now we're deadlocked. So we make
// sure flamegraph rendering does not require TRACKER_STATE to be locked.
let (allocated_bytes, flamegraph_callstacks_factory) = {
let mut tracker_state = TRACKER_STATE.lock();
let allocations = &mut tracker_state.allocations;
// Print warning if we're missing allocations.
allocations.warn_on_problems(peak);
let allocated_bytes = if peak {
allocations.get_peak_allocated_bytes()
} else {
allocations.get_current_allocated_bytes()
};
let flamegraph_callstacks_factory = allocations.combine_callstacks(peak, IdentityCleaner);
(allocated_bytes, flamegraph_callstacks_factory)
};
let flamegraph_callstacks = flamegraph_callstacks_factory();
eprintln!("=fil-profile= Preparing to write to {}", path);
let directory_path = Path::new(path);
let title = format!(
"{} ({:.1} MiB)",
title,
allocated_bytes as f64 / (1024.0 * 1024.0)
);
let subtitle = r#"Made with the Fil profiler. <a href="https://pythonspeed.com/fil/" style="text-decoration: underline;" target="_parent">Try it on your code!</a>"#;
flamegraph_callstacks.write_flamegraphs(
directory_path,
base_filename,
&title,
subtitle,
"bytes",
to_be_post_processed,
)
}
/// Dump all callstacks in peak memory usage to format used by flamegraph.
fn dump_peak_to_flamegraph(path: &str) {
dump_to_flamegraph(path, true, "peak-memory", "Peak Tracked Memory Usage", true);
}
#[no_mangle]
extern "C" fn pymemprofile_add_allocation(address: usize, size: usize, line_number: u16) {
add_allocation(address, size, line_number, false).unwrap_or(());
}
#[no_mangle]
extern "C" fn pymemprofile_free_allocation(address: usize) {
free_allocation(address);
}
/// Returns allocation size, or 0 if not stored. Useful for tests, mostly.
#[no_mangle]
extern "C" fn pymemprofile_get_allocation_size(address: usize) -> usize {
get_allocation_size(address)
}
#[no_mangle]
extern "C" fn pymemprofile_add_anon_mmap(address: usize, size: usize, line_number: u16) {
add_allocation(address, size, line_number, true).unwrap_or(());
}
#[no_mangle]
unsafe extern "C" fn pymemprofile_add_function_location(
filename: *const c_char,
filename_length: u64,
function_name: *const c_char,
function_length: u64,
) -> u64 {
let filename = unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
filename as *const u8,
filename_length as usize,
))
};
let function_name = unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
function_name as *const u8,
function_length as usize,
))
};
let function_id = add_function(filename.to_string(), function_name.to_string());
function_id.as_u64()
}
/// # Safety
/// Intended for use from C APIs, what can I say.
#[no_mangle]
unsafe extern "C" fn pymemprofile_start_call(
parent_line_number: u16,
function_id: u64,
line_number: u16,
) {
let function_id = FunctionId::new(function_id);
start_call(function_id, parent_line_number, line_number);
}
#[no_mangle]
extern "C" fn pymemprofile_finish_call() {
finish_call();
}
/// # Safety
/// Intended for use from C.
#[no_mangle]
unsafe extern "C" fn pymemprofile_reset(default_path: *const c_char) {
let path = unsafe { CStr::from_ptr(default_path) }
.to_str()
.expect("Path wasn't UTF-8")
.to_string();
reset(path);
}
/// # Safety
/// Intended for use from C.
#[no_mangle]
unsafe extern "C" fn pymemprofile_dump_peak_to_flamegraph(path: *const c_char) {
let path = unsafe { CStr::from_ptr(path) }
.to_str()
.expect("Path wasn't UTF-8")
.to_string();
dump_peak_to_flamegraph(&path);
}
/// # Safety
/// Intended for use from C.
#[no_mangle]
unsafe extern "C" fn pymemprofile_get_current_callstack() -> *mut c_void {
let callstack = get_current_callstack();
let callstack = Box::new(callstack);
Box::into_raw(callstack) as *mut c_void
}
/// # Safety
/// Intended for use from C.
#[no_mangle]
unsafe extern "C" fn pymemprofile_set_current_callstack(callstack: *mut c_void) {
// The callstack is a Box created via pymemprofile_get_callstack()
let callstack = unsafe { Box::<Callstack>::from_raw(callstack as *mut Callstack) };
set_current_callstack(&callstack);
}
/// # Safety
/// Intended for use from C.
#[no_mangle]
unsafe extern "C" fn pymemprofile_clear_current_callstack() {
let callstack = Callstack::new();
set_current_callstack(&callstack);
}
/// # A start at implementing public API from Rust
/// Convert pointer into Rust closure.
extern "C" fn trampoline<F>(user_data: *mut c_void)
where
F: FnMut(),
{
let user_data = unsafe { &mut *(user_data as *mut F) };
user_data();
}
/// C APIs in _filpreload.c.
type CCallback = extern "C" fn(*mut c_void);
extern "C" {
// Call function conditonally in non-reentrant way.
fn call_if_tracking(f: CCallback, user_data: *mut c_void) -> c_void;
// Return whether C code has initialized.
fn is_initialized() -> c_int;
// Increment/decrement reentrancy counter.
//fn fil_increment_reentrancy();
//fn fil_decrement_reentrancy();
}
struct FilMmapAPI;
impl pymemprofile_api::mmap::MmapAPI for FilMmapAPI {
fn call_if_tracking<F: FnMut()>(&self, mut f: F) {
unsafe { call_if_tracking(trampoline::<F>, &mut f as *mut _ as *mut c_void) };
}
fn remove_mmap(&self, address: usize, length: usize) {
let mut tracker_state = TRACKER_STATE.lock();
let allocations = &mut tracker_state.allocations;
allocations.free_anon_mmap(PARENT_PROCESS, address, length);
}
fn is_initialized(&self) -> bool {
unsafe { is_initialized() == 1 }
}
}
/// On macOS we're using reimplemented_* prefix.
#[cfg(target_os = "macos")]
#[no_mangle]
pub extern "C" fn reimplemented_munmap(addr: *mut c_void, len: usize) -> c_int {
return unsafe { pymemprofile_api::mmap::munmap_wrapper(addr, len, &FilMmapAPI {}) };
}
/// On Linux we're using same name as the API we're replacing.
#[cfg(target_os = "linux")]
#[no_mangle]
pub extern "C" fn munmap(addr: *mut c_void, len: usize) -> c_int {
return unsafe { pymemprofile_api::mmap::munmap_wrapper(addr, len, &FilMmapAPI {}) };
}
|
use std::io::Write;
use std::path::Path;
use super::btmeister::{BuildToolDef, BuildToolDefs};
use super::cli::Format;
use super::BuildTool;
pub trait Formatter {
fn print(&self, out: &mut Box<dyn Write>, base: &Path, vector: Vec<BuildTool>) -> i32 {
self.print_header(out, base);
vector
.iter()
.enumerate()
.for_each(|item| self.print_each(out, item.1, item.0 == 0));
self.print_footer(out);
0
}
fn print_each(&self, out: &mut Box<dyn Write>, result: &BuildTool, first: bool);
fn print_header(&self, _out: &mut Box<dyn Write>, _base: &Path) {}
fn print_footer(&self, _out: &mut Box<dyn Write>) {}
fn print_def(&self, out: &mut Box<dyn Write>, def: &BuildToolDef, first: bool);
fn print_defs(&self, out: &mut Box<dyn Write>, defs: &BuildToolDefs) {
self.print_def_header(out);
defs.iter()
.enumerate()
.for_each(|item| self.print_def(out, item.1, item.0 == 0));
self.print_def_footer(out);
}
fn print_def_header(&self, _out: &mut Box<dyn Write>) {}
fn print_def_footer(&self, _out: &mut Box<dyn Write>) {}
}
impl dyn Formatter {
pub fn build(format: Format) -> Box<dyn Formatter> {
match format {
Format::Json => Box::new(JsonFormatter {}),
Format::Default => Box::new(DefaultFormatter {}),
Format::Xml => Box::new(XmlFormatter {}),
Format::Yaml => Box::new(YamlFormatter {}),
}
}
}
pub struct JsonFormatter {}
pub struct DefaultFormatter {}
pub struct XmlFormatter {}
pub struct YamlFormatter {}
impl Formatter for DefaultFormatter {
fn print_header(&self, out: &mut Box<dyn Write>, base: &Path) {
writeln!(out, "{}", base.display()).unwrap();
}
fn print_each(&self, out: &mut Box<dyn Write>, result: &BuildTool, _first: bool) {
writeln!(out, " {}: {}", result.path.display(), result.def.name).unwrap();
}
fn print_def(&self, out: &mut Box<dyn Write>, def: &BuildToolDef, _first: bool) {
writeln!(out, "{}: {}", def.name, def.build_files.join(", ")).unwrap();
}
}
impl Formatter for JsonFormatter {
fn print_each(&self, out: &mut Box<dyn Write>, result: &BuildTool, first: bool) {
if !first {
write!(out, ",").unwrap();
}
write!(
out,
r#"{{"file-path":"{}","tool-name":"{}"}}"#,
result.path.display(),
result.def.name
)
.unwrap();
}
fn print_header(&self, out: &mut Box<dyn Write>, base: &Path) {
write!(out, r#"{{"base":"{}","build-tools":["#, base.display()).unwrap();
}
fn print_footer(&self, out: &mut Box<dyn Write>) {
writeln!(out, "]}}").unwrap();
}
fn print_def_header(&self, out: &mut Box<dyn Write>) {
write!(out, "[").unwrap();
}
fn print_def_footer(&self, out: &mut Box<dyn Write>) {
writeln!(out, "]").unwrap();
}
fn print_def(&self, out: &mut Box<dyn Write>, def: &BuildToolDef, first: bool) {
if !first {
write!(out, ",").unwrap();
}
write!(
out,
r#"{{"name":"{}","url":"{}","build-files":["#,
def.name, def.url
)
.unwrap();
for (i, element) in def.build_files.iter().enumerate() {
if i != 0 {
write!(out, ",").unwrap();
}
write!(out, r#""{}""#, element).unwrap();
}
write!(out, "]}}").unwrap();
}
}
impl Formatter for XmlFormatter {
fn print_header(&self, out: &mut Box<dyn Write>, base: &Path) {
writeln!(out, "<?xml version=\"1.0\"?>").unwrap();
write!(out, "<build-tools><base>{}</base>", base.display()).unwrap();
}
fn print_footer(&self, out: &mut Box<dyn Write>) {
writeln!(out, "</build-tools>").unwrap();
}
fn print_each(&self, out: &mut Box<dyn Write>, result: &BuildTool, _first: bool) {
write!(
out,
"<build-tool><file-path>{}</file-path><tool-name>{}</tool-name></build-tool>",
result.path.display(),
result.def.name
)
.unwrap();
}
fn print_def_header(&self, out: &mut Box<dyn Write>) {
writeln!(out, "<?xml version=\"1.0\"?>").unwrap();
write!(out, "<build-tool-defs>").unwrap();
}
fn print_def_footer(&self, out: &mut Box<dyn Write>) {
writeln!(out, "</build-tool-defs>").unwrap();
}
fn print_def(&self, out: &mut Box<dyn Write>, def: &BuildToolDef, _first: bool) {
write!(
out,
"<build-tool-def><name>{}</name><url>{}</url><build-files>",
def.name, def.url
)
.unwrap();
def.build_files
.iter()
.for_each(|item| write!(out, "<file-name>{}</file-name>", item).unwrap());
write!(out, "</build-files></build-tool-def>").unwrap();
}
}
impl Formatter for YamlFormatter {
fn print_header(&self, out: &mut Box<dyn Write>, base: &Path) {
writeln!(out, "base: {}", base.display()).unwrap();
}
fn print_each(&self, out: &mut Box<dyn Write>, result: &BuildTool, _first: bool) {
writeln!(out, " - file-path: {}", result.path.display()).unwrap();
writeln!(out, " tool-name: {}", result.def.name).unwrap();
}
fn print_def_header(&self, out: &mut Box<dyn Write>) {
writeln!(out, "build-tools-defs").unwrap();
}
fn print_def(&self, out: &mut Box<dyn Write>, def: &BuildToolDef, _first: bool) {
writeln!(out, " - name: {}", def.name).unwrap();
writeln!(out, " url: {}", def.url).unwrap();
writeln!(out, " file-names:").unwrap();
def.build_files
.iter()
.enumerate()
.for_each(|(index, file_name)| self.print_file_name(out, index, file_name));
}
}
impl YamlFormatter {
fn print_file_name(&self, out: &mut Box<dyn Write>, index: usize, file_name: &str) {
if index == 0 {
write!(out, " - ").unwrap();
} else {
write!(out, " ").unwrap();
};
writeln!(out, "{}", file_name).unwrap();
}
}
#[cfg(test)]
mod test_print_defs {
use super::super::*;
use super::*;
use std::fs::{read_to_string, remove_file, File};
use std::str::FromStr;
fn write_and_read(format: Format, path: &str) -> String {
{
let defs = construct(
Some(PathBuf::from_str("testdata/append_def.json").unwrap()),
None,
)
.unwrap();
let f = <dyn Formatter>::build(format);
let mut dest: Box<dyn Write> = Box::new(BufWriter::new(File::create(path).unwrap()));
f.print_defs(&mut dest, &defs);
}
let r = read_to_string(path).unwrap();
let _ = remove_file(path);
r.trim().to_string()
}
#[test]
fn test_json() {
let result = write_and_read(Format::Json, "dest2.json");
assert_eq!(
r#"[{"name":"go","url":"https://go.dev/","build-files":["go.mod"]},{"name":"webpack","url":"https://webpack.js.org/","build-files":["webpack.config.js"]}]"#,
result
);
}
#[test]
fn test_default() {
let result = write_and_read(Format::Default, "dest2.txt");
assert_eq!(
r#"go: go.mod
webpack: webpack.config.js"#,
result
);
}
#[test]
fn test_xml() {
let result = write_and_read(Format::Xml, "dest2.xml");
assert_eq!(
r#"<?xml version="1.0"?>
<build-tool-defs><build-tool-def><name>go</name><url>https://go.dev/</url><build-files><file-name>go.mod</file-name></build-files></build-tool-def><build-tool-def><name>webpack</name><url>https://webpack.js.org/</url><build-files><file-name>webpack.config.js</file-name></build-files></build-tool-def></build-tool-defs>"#,
result
);
}
#[test]
fn test_yaml() {
let result = write_and_read(Format::Yaml, "dest2.yaml");
assert_eq!(
r#"build-tools-defs
- name: go
url: https://go.dev/
file-names:
- go.mod
- name: webpack
url: https://webpack.js.org/
file-names:
- webpack.config.js"#,
result
);
}
}
#[cfg(test)]
mod test_print_result {
use super::super::*;
use super::*;
use std::fs::{read_to_string, remove_file, File};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::str::FromStr;
fn setup() -> Vec<BuildTool> {
let defs = construct(None, None).unwrap();
let def1 = defs.get(11).unwrap();
let def2 = defs.get(8).unwrap();
let bt1 = BuildTool::new(
PathBuf::from_str("testdata/fibonacci/build.gradle").unwrap(),
def1.clone(),
);
let bt2 = BuildTool::new(
PathBuf::from_str("testdata/hello/Cargo.toml").unwrap(),
def2.clone(),
);
vec![bt1, bt2]
}
fn write_and_read(format: Format, path: &str) -> String {
{
let vec = setup();
let f = <dyn Formatter>::build(format);
let mut dest: Box<dyn Write> = Box::new(BufWriter::new(File::create(path).unwrap()));
f.print(&mut dest, &PathBuf::from_str("testdata").unwrap(), vec);
}
let r = read_to_string(path).unwrap();
let _ = remove_file(path);
r.trim().to_string()
}
#[test]
fn test_json() {
let result = write_and_read(Format::Json, "dest1.json");
assert_eq!(
r#"{"base":"testdata","build-tools":[{"file-path":"testdata/fibonacci/build.gradle","tool-name":"Gradle"},{"file-path":"testdata/hello/Cargo.toml","tool-name":"Cargo"}]}"#,
result
);
}
#[test]
fn test_xml() {
let result = write_and_read(Format::Xml, "dest1.xml");
assert_eq!(
r#"<?xml version="1.0"?>
<build-tools><base>testdata</base><build-tool><file-path>testdata/fibonacci/build.gradle</file-path><tool-name>Gradle</tool-name></build-tool><build-tool><file-path>testdata/hello/Cargo.toml</file-path><tool-name>Cargo</tool-name></build-tool></build-tools>"#,
result
);
}
#[test]
fn test_yaml() {
let result = write_and_read(Format::Yaml, "dest1.yaml");
assert_eq!(
r#"base: testdata
- file-path: testdata/fibonacci/build.gradle
tool-name: Gradle
- file-path: testdata/hello/Cargo.toml
tool-name: Cargo"#,
result
);
}
#[test]
fn test_default() {
let result = write_and_read(Format::Default, "dest1.txt");
assert_eq!(
r#"testdata
testdata/fibonacci/build.gradle: Gradle
testdata/hello/Cargo.toml: Cargo"#,
result
);
}
}
|
struct MinStack {
values: Vec<i32>,
min_values: Vec<i32>,
}
impl MinStack {
fn new() -> Self {
Self {
values: vec![],
min_values: vec![],
}
}
fn push(&mut self, val: i32) {
self.values.push(val);
if self.min_values.len() == 0 {
self.min_values.push(val);
} else {
let min = val.min(self.min_values[self.min_values.len() - 1]);
self.min_values.push(min);
}
}
fn pop(&mut self) {
self.values.pop();
self.min_values.pop();
}
fn top(&self) -> i32 {
self.values[self.values.len() - 1]
}
fn get_min(&self) -> i32 {
self.min_values[self.min_values.len() - 1]
}
}
fn main() {
println!("Hello, world!");
}
|
//
// Copyright 2020 The Project Oak 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 super::*;
use maplit::{hashmap, hashset};
use oak_abi::{
label::{
confidentiality_label, public_key_identity_tag, tls_endpoint_tag,
web_assembly_module_signature_tag, web_assembly_module_tag, Label,
},
proto::oak::application::{
node_configuration::ConfigType, ApplicationConfiguration, GrpcServerConfiguration,
LogConfiguration, NodeConfiguration,
},
};
use std::sync::mpsc;
pub fn init_logging() {
let _ = env_logger::builder().is_test(true).try_init();
}
type NodeBody = dyn Fn(RuntimeProxy) -> Result<(), OakStatus> + Send + Sync;
/// Runs the provided function as if it were the body of a [`Node`] implementation, which is
/// instantiated by the [`Runtime`] with the provided [`Label`].
fn run_node_body(node_label: &Label, node_privilege: &NodePrivilege, node_body: Box<NodeBody>) {
init_logging();
let configuration = ApplicationConfiguration {
wasm_modules: hashmap! {},
initial_node_configuration: None,
module_signatures: vec![],
};
let permissions = crate::permissions::PermissionsConfiguration {
allow_grpc_server_nodes: true,
allow_log_nodes: true,
..Default::default()
};
let signature_table = SignatureTable::default();
info!("Create runtime for test");
let proxy = crate::RuntimeProxy::create_runtime(
&configuration,
&permissions,
&SecureServerConfiguration {
grpc_config: Some(GrpcConfiguration {
grpc_server_tls_identity: Some(Identity::from_pem(
include_str!("../../examples/certs/local/local.pem"),
include_str!("../../examples/certs/local/local.key"),
)),
grpc_client_root_tls_certificate: crate::tls::Certificate::parse(
include_bytes!("../../examples/certs/local/ca.pem").to_vec(),
)
.ok(),
oidc_client_info: None,
}),
http_config: None,
},
&signature_table,
None,
);
struct TestNode {
node_body: Box<NodeBody>,
result_sender: mpsc::SyncSender<Result<(), OakStatus>>,
}
impl crate::node::Node for TestNode {
fn node_type(&self) -> &'static str {
"test"
}
fn isolation(&self) -> NodeIsolation {
// Even though this node is not actually sandboxed, we are simulating a Wasm node during
// testing.
NodeIsolation::Sandboxed
}
fn run(
self: Box<Self>,
runtime: RuntimeProxy,
_handle: oak_abi::Handle,
_notify_receiver: oneshot::Receiver<()>,
) {
// Run the test body.
let result = (self.node_body)(runtime);
// Make the result of the test visible outside of this thread.
self.result_sender.send(result).unwrap();
}
}
let (result_sender, result_receiver) = mpsc::sync_channel(1);
// Create a new Oak node.
let node_instance = TestNode {
node_body,
result_sender,
};
let (_write_handle, read_handle) = proxy
.channel_create("Initial", &Label::public_untrusted())
.expect("Could not create init channel");
proxy
.node_register(
CreatedNode {
instance: Box::new(node_instance),
privilege: node_privilege.clone(),
},
"test",
node_label,
read_handle,
)
.expect("Could not create Oak node!");
// Wait for the test Node to complete execution before terminating the Runtime.
let result_value = result_receiver
.recv()
.expect("test node disconnected, probably due to panic/assert fail in test");
assert_eq!(result_value, Ok(()));
info!("Stop runtime..");
proxy.runtime.stop();
info!("Stop runtime..done");
}
/// Returns a non-trivial label for testing.
fn test_label() -> Label {
Label {
confidentiality_tags: vec![oak_abi::label::public_key_identity_tag(&[1, 1, 1])],
integrity_tags: vec![],
}
}
/// Checks that a panic in the node body actually causes the test case to fail, and does not
/// accidentally get ignored.
#[test]
#[ignore]
#[should_panic]
fn panic_check() {
let label = test_label();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(|_runtime| {
panic!("testing that panic works");
}),
);
}
/// Create a test Node with a non-public confidentiality label and no downgrading privilege that
/// creates a Channel with the same label and fails.
///
/// Only Nodes with a public confidentiality label may create other Nodes and Channels.
#[test]
fn create_channel_same_label_err() {
let label = test_label();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
// Attempt to perform an operation that requires the [`Runtime`] to have created an
// appropriate [`NodeInfo`] instance.
let result = runtime.channel_create("", &label_clone);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
Ok(())
}),
);
}
/// Create a test Node with a non-public confidentiality label and no downgrading privilege that
/// creates a Channel with a less confidential label and fails.
///
/// Only Nodes with a public confidentiality label may create other Nodes and Channels.
#[test]
fn create_channel_less_confidential_label_err() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let tag_1 = oak_abi::label::public_key_identity_tag(&[2, 2, 2]);
let initial_label = Label {
confidentiality_tags: vec![tag_0, tag_1.clone()],
integrity_tags: vec![],
};
let less_confidential_label = Label {
confidentiality_tags: vec![tag_1],
integrity_tags: vec![],
};
run_node_body(
&initial_label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let result = runtime.channel_create("", &less_confidential_label);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
Ok(())
}),
);
}
/// Create a test Node with a non-public confidentiality label and some downgrading privilege that
/// creates a Channel with a less confidential label and fails.
///
/// Only Nodes with a public confidentiality label may create other Nodes and Channels.
#[test]
fn create_channel_less_confidential_label_declassification_err() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let tag_1 = oak_abi::label::public_key_identity_tag(&[2, 2, 2]);
let other_tag = oak_abi::label::public_key_identity_tag(&[3, 3, 3]);
let initial_label = Label {
confidentiality_tags: vec![tag_0.clone(), tag_1.clone()],
integrity_tags: vec![],
};
let less_confidential_label = Label {
confidentiality_tags: vec![tag_1],
integrity_tags: vec![],
};
run_node_body(
&initial_label,
// Grant this node the privilege to declassify `tag_0` and another unrelated tag, and
// endorse another unrelated tag.
&NodePrivilege {
can_declassify_confidentiality_tags: hashset! { tag_0, other_tag.clone() },
can_endorse_integrity_tags: hashset! { other_tag },
},
Box::new(move |runtime| {
let result = runtime.channel_create("", &less_confidential_label);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
Ok(())
}),
);
}
/// Create a test Node with a non-public confidentiality label that creates a Channel with a less
/// confidential label and fails.
///
/// Only Nodes with a public confidentiality label may create other Nodes and Channels.
#[test]
fn create_channel_less_confidential_label_no_privilege_err() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let tag_1 = oak_abi::label::public_key_identity_tag(&[2, 2, 2]);
let initial_label = Label {
confidentiality_tags: vec![tag_0.clone(), tag_1.clone()],
integrity_tags: vec![],
};
let less_confidential_label = Label {
confidentiality_tags: vec![tag_1],
integrity_tags: vec![],
};
run_node_body(
&initial_label,
// Grant this node the privilege to endorse (rather than declassify) `tag_0`, which in this
// case is useless, so it should still fail.
&NodePrivilege {
can_declassify_confidentiality_tags: hashset! {},
can_endorse_integrity_tags: hashset! { tag_0 },
},
Box::new(move |runtime| {
let result = runtime.channel_create("", &less_confidential_label);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
Ok(())
}),
);
}
/// Create a test Node with public confidentiality label and no privilege that:
///
/// - creates a Channel with a more confidential label and succeeds
/// - writes to the newly created channel and succeeds
/// - reads from the newly created channel and fails
///
/// Data is always allowed to flow to more confidential labels.
#[test]
fn create_channel_with_more_confidential_label_from_public_untrusted_node_ok() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let initial_label = &Label::public_untrusted();
let more_confidential_label = Label {
confidentiality_tags: vec![tag_0],
integrity_tags: vec![],
};
run_node_body(
initial_label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let result = runtime.channel_create("", &more_confidential_label);
assert!(result.is_ok());
let (write_handle, read_handle) = result.unwrap();
let message = NodeMessage {
bytes: vec![14, 12, 88],
handles: vec![],
};
{
// Writing to a more confidential Channel is always allowed.
let result = runtime.channel_write(write_handle, message);
assert_eq!(Ok(()), result);
}
{
// Reading from a more confidential Channel is not allowed.
let result = runtime.channel_read(read_handle);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
}
Ok(())
}),
);
}
/// Create a test Node with public confidentiality label and downgrading privilege that:
///
/// - creates a Channel with a more confidential label and succeeds (same as previous test case)
/// - writes to the newly created channel and succeeds (same as previous test case)
/// - reads from the newly created channel and succeeds (different from previous test case, thanks
/// to the newly added privilege)
#[test]
fn create_channel_with_more_confidential_label_from_public_node_with_downgrade_ok() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let initial_label = Label::public_untrusted();
let more_confidential_label = Label {
confidentiality_tags: vec![tag_0.clone()],
integrity_tags: vec![],
};
run_node_body(
&initial_label,
&NodePrivilege {
can_declassify_confidentiality_tags: hashset! { tag_0 },
can_endorse_integrity_tags: hashset! {},
},
Box::new(move |runtime| {
let result = runtime.channel_create("", &more_confidential_label);
assert!(result.is_ok());
let (write_handle, read_handle) = result.unwrap();
let message = NodeMessage {
bytes: vec![14, 12, 88],
handles: vec![],
};
{
// Writing to a more confidential Channel is always allowed.
let result = runtime.channel_write(write_handle, message.clone());
assert_eq!(Ok(()), result);
}
{
// Reading from a more confidential Channel is allowed because of the privilege.
let result = runtime.channel_read_with_downgrade(read_handle);
assert_eq!(Ok(Some(message)), result);
}
Ok(())
}),
);
}
/// Create a test Node with public confidentiality label and infinite privilege that:
///
/// - creates a Channel with a more confidential label and succeeds (same as previous test case)
/// - writes to the newly created channel and succeeds (same as previous test case)
/// - reads from the newly created channel and succeeds (same as previous test case, this time
/// thanks to the infinite privilege)
#[test]
fn create_channel_with_more_confidential_label_from_public_node_with_top_privilege_ok() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let initial_label = Label::public_untrusted();
let more_confidential_label = Label {
confidentiality_tags: vec![tag_0],
integrity_tags: vec![],
};
run_node_body(
&initial_label,
&NodePrivilege::top_privilege(),
Box::new(move |runtime| {
let result = runtime.channel_create("", &more_confidential_label);
assert!(result.is_ok());
let (write_handle, read_handle) = result.unwrap();
let message = NodeMessage {
bytes: vec![14, 12, 88],
handles: vec![],
};
{
// Writing to a more confidential Channel is always allowed.
let result = runtime.channel_write(write_handle, message.clone());
assert_eq!(Ok(()), result);
}
{
// Reading from a more confidential Channel is allowed because of the privilege.
let result = runtime.channel_read_with_downgrade(read_handle);
assert_eq!(Ok(Some(message)), result);
}
Ok(())
}),
);
}
#[test]
fn create_channel_with_more_confidential_label_from_non_public_node_with_downgrade_err() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let tag_1 = oak_abi::label::public_key_identity_tag(&[2, 2, 2]);
let initial_label = Label {
confidentiality_tags: vec![tag_0.clone()],
integrity_tags: vec![],
};
let more_confidential_label = Label {
confidentiality_tags: vec![tag_0, tag_1.clone()],
integrity_tags: vec![],
};
run_node_body(
&initial_label,
&NodePrivilege {
can_declassify_confidentiality_tags: hashset! { tag_1 },
can_endorse_integrity_tags: hashset! {},
},
Box::new(move |runtime| {
let result = runtime.channel_create("", &more_confidential_label);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
Ok(())
}),
);
}
/// Create a test Node that creates a Node with the same public untrusted label and succeeds.
#[test]
fn create_node_same_label_ok() {
let label = Label::public_untrusted();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (_write_handle, read_handle) = runtime.channel_create("", &label_clone)?;
let node_configuration = NodeConfiguration {
config_type: Some(ConfigType::LogConfig(LogConfiguration {})),
};
let result =
runtime.node_create("test", &node_configuration, &label_clone, read_handle);
assert_eq!(Ok(()), result);
Ok(())
}),
);
}
/// Create a test Node that creates a Node with an invalid configuration and fails.
#[test]
fn create_node_invalid_configuration_err() {
let label = Label::public_untrusted();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (_write_handle, read_handle) = runtime.channel_create("", &label_clone)?;
// Node configuration without config type.
let node_configuration = NodeConfiguration { config_type: None };
let result =
runtime.node_create("test", &node_configuration, &label_clone, read_handle);
assert_eq!(Err(OakStatus::ErrInvalidArgs), result);
Ok(())
}),
);
}
/// Create a test Node with a non public_trusted label, which is then unable to create channels
/// of any sort, regardless of label.
#[test]
fn create_channel_by_nonpublic_node_err() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let tag_1 = oak_abi::label::public_key_identity_tag(&[2, 2, 2]);
let initial_label = Label {
confidentiality_tags: vec![tag_0.clone()],
integrity_tags: vec![],
};
let less_confidential_label = Label {
confidentiality_tags: vec![],
integrity_tags: vec![],
};
let more_confidential_label = Label {
confidentiality_tags: vec![tag_0, tag_1],
integrity_tags: vec![],
};
let initial_label_clone = initial_label.clone();
run_node_body(
&initial_label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let result = runtime.channel_create("test-same-label", &initial_label_clone);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
let result = runtime.channel_create("test-less-label", &less_confidential_label);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
let result = runtime.channel_create("test-more-label", &more_confidential_label);
assert_eq!(Err(OakStatus::ErrPermissionDenied), result);
Ok(())
}),
);
}
/// Create a public_untrusted test Node that creates a Node with a more confidential label and
/// succeeds.
#[test]
fn create_node_more_confidential_label_ok() {
let tag_0 = oak_abi::label::public_key_identity_tag(&[1, 1, 1]);
let tag_1 = oak_abi::label::public_key_identity_tag(&[2, 2, 2]);
let initial_label = Label::public_untrusted();
let more_confidential_label = Label {
confidentiality_tags: vec![tag_0.clone()],
integrity_tags: vec![],
};
let even_more_confidential_label = Label {
confidentiality_tags: vec![tag_0, tag_1],
integrity_tags: vec![],
};
let initial_label_clone = initial_label.clone();
run_node_body(
&initial_label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (_write_handle, read_handle) = runtime.channel_create("", &initial_label_clone)?;
let node_configuration = NodeConfiguration {
config_type: Some(ConfigType::GrpcServerConfig(GrpcServerConfiguration {
address: "[::]:6502".to_string(),
})),
};
let result = runtime.node_create(
"test",
&node_configuration,
&more_confidential_label,
read_handle,
);
assert_eq!(Ok(()), result);
let result = runtime.node_create(
"test",
&node_configuration,
&even_more_confidential_label,
read_handle,
);
assert_eq!(Ok(()), result);
Ok(())
}),
);
}
#[test]
fn wait_on_channels_immediately_returns_if_any_channel_is_orphaned() {
let label = Label::public_untrusted();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (write_handle_0, read_handle_0) = runtime.channel_create("", &label_clone)?;
let (_write_handle_1, read_handle_1) = runtime.channel_create("", &label_clone)?;
// Close the write_handle; this should make the channel Orphaned
let result = runtime.channel_close(write_handle_0);
assert_eq!(Ok(()), result);
let result = runtime.wait_on_channels(&[read_handle_0, read_handle_1]);
assert_eq!(
Ok(vec![
ChannelReadStatus::Orphaned,
ChannelReadStatus::NotReady
]),
result
);
Ok(())
}),
);
}
#[test]
fn wait_on_channels_blocks_if_all_channels_have_status_not_ready() {
let label = Label::public_untrusted();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (write_handle, read_handle) = runtime.channel_create("", &label_clone)?;
// Change the status of the channel concurrently, to unpark the waiting thread.
let runtime_copy = runtime.clone();
let start = std::time::Instant::now();
std::thread::spawn(move || {
let ten_millis = std::time::Duration::from_millis(10);
thread::sleep(ten_millis);
// Close the write_handle; this should make the channel Orphaned
let result = runtime_copy.channel_close(write_handle);
assert_eq!(Ok(()), result);
});
let result = runtime.wait_on_channels(&[read_handle]);
assert!(start.elapsed() >= std::time::Duration::from_millis(10));
assert_eq!(Ok(vec![ChannelReadStatus::Orphaned]), result);
Ok(())
}),
);
}
#[test]
fn wait_on_channels_immediately_returns_if_any_channel_is_invalid() {
let label = Label::public_untrusted();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (write_handle, _read_handle) = runtime.channel_create("", &label_clone)?;
let (_write_handle, read_handle) = runtime.channel_create("", &label_clone)?;
let result = runtime.wait_on_channels(&[write_handle, read_handle]);
assert_eq!(
Ok(vec![
ChannelReadStatus::InvalidChannel,
ChannelReadStatus::NotReady
]),
result
);
Ok(())
}),
);
}
#[test]
fn wait_on_channels_immediately_returns_if_the_input_list_is_empty() {
let label = Label::public_untrusted();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(|runtime| {
let result = runtime.wait_on_channels(&[]);
assert_eq!(Ok(Vec::<ChannelReadStatus>::new()), result);
Ok(())
}),
);
}
#[test]
fn handle_clone_cloned_handle_is_distinct() {
let label = Label::public_untrusted();
let label_clone = label.clone();
run_node_body(
&label,
&NodePrivilege::default(),
Box::new(move |runtime| {
let (_write_handle, read_handle) = runtime.channel_create("", &label_clone)?;
let cloned_read_handle = runtime.handle_clone(read_handle)?;
let close1_result = runtime.channel_close(read_handle);
// Sanity check to make sure closing the same handle twice results in an error
let close1_again_result = runtime.channel_close(read_handle);
let close2_result = runtime.channel_close(cloned_read_handle);
assert_eq!(Ok(()), close1_result);
assert_eq!(Err(OakStatus::ErrBadHandle), close1_again_result);
assert_eq!(Ok(()), close2_result);
Ok(())
}),
);
}
#[test]
fn downgrade_multiple_labels_using_top_privilege() {
init_logging();
let top_privilege = NodePrivilege::top_privilege();
let wasm_tag = web_assembly_module_tag(&[1, 2, 3]);
let signature_tag = web_assembly_module_signature_tag(&[1, 2, 3]);
let public_key_identity_tag = public_key_identity_tag(&[1, 2, 3]);
let tls_endpoint_tag = tls_endpoint_tag("google.com");
let wasm_label = confidentiality_label(wasm_tag.clone());
let signature_label = confidentiality_label(signature_tag.clone());
let public_key_identity_label = confidentiality_label(public_key_identity_tag.clone());
let tls_endpoint_label = confidentiality_label(tls_endpoint_tag.clone());
let mixed_label = Label {
confidentiality_tags: vec![
wasm_tag,
signature_tag,
public_key_identity_tag,
tls_endpoint_tag,
],
integrity_tags: vec![],
};
// The top privilege can downgrade any label to "public".
assert!(top_privilege
.downgrade_label(&wasm_label)
.flows_to(&Label::public_untrusted()));
assert!(top_privilege
.downgrade_label(&signature_label)
.flows_to(&Label::public_untrusted()));
assert!(top_privilege
.downgrade_label(&public_key_identity_label)
.flows_to(&Label::public_untrusted()));
assert!(top_privilege
.downgrade_label(&tls_endpoint_label)
.flows_to(&Label::public_untrusted()));
assert!(top_privilege
.downgrade_label(&mixed_label)
.flows_to(&Label::public_untrusted()));
}
#[test]
fn downgrade_tls_label_using_tls_privilege() {
init_logging();
let tls_endpoint_tag_1 = tls_endpoint_tag("google.com");
let tls_endpoint_tag_2 = tls_endpoint_tag("localhost");
let tls_privilege = NodePrivilege {
can_declassify_confidentiality_tags: hashset! { tls_endpoint_tag_1.clone() },
can_endorse_integrity_tags: hashset! {},
};
let tls_endpoint_label_1 = confidentiality_label(tls_endpoint_tag_1.clone());
let tls_endpoint_label_2 = confidentiality_label(tls_endpoint_tag_2.clone());
let mixed_tls_endpoint_label = Label {
confidentiality_tags: vec![tls_endpoint_tag_1, tls_endpoint_tag_2],
integrity_tags: vec![],
};
// Can downgrade the label with the same TLS endpoint tag.
assert!(tls_privilege
.downgrade_label(&tls_endpoint_label_1)
.flows_to(&Label::public_untrusted()));
// Cannot downgrade the label with a different TLS endpoint tag.
assert!(!tls_privilege
.downgrade_label(&tls_endpoint_label_2)
.flows_to(&Label::public_untrusted()));
// Can partially downgrade the combined label.
assert!(tls_privilege
.downgrade_label(&mixed_tls_endpoint_label)
.flows_to(&tls_endpoint_label_2));
assert!(!tls_privilege
.downgrade_label(&mixed_tls_endpoint_label)
.flows_to(&tls_endpoint_label_1));
}
#[test]
fn downgrade_wasm_label_using_signature_privilege_does_not_do_aything() {
init_logging();
let signature_tag = web_assembly_module_signature_tag(&[1, 2, 3]);
let signature_privilege = NodePrivilege {
can_declassify_confidentiality_tags: hashset! { signature_tag },
can_endorse_integrity_tags: hashset! {},
};
let wasm_tag = web_assembly_module_tag(&[1, 2, 3]);
let wasm_label = confidentiality_label(wasm_tag);
// Signature privilege cannot downgrade a Wasm confidentiality label.
assert!(!signature_privilege
.downgrade_label(&wasm_label)
.flows_to(&Label::public_untrusted()));
}
|
use cpu::Core;
/// Execute the opcode and return the number of cycles.
pub fn execute(cpu: &mut Core, opcode: u8) -> usize {
match opcode {
0x4c => jump_abs(cpu),
0x6c => jump_indr(cpu),
_ => 0,
}
}
/// Jump to absolute address (JMP).
///
/// Flags affected: None
fn jump_abs(cpu: &mut Core) -> usize {
cpu.reg.pc = cpu.abs_addr();
3
}
/// Jump to indirect address (JMP).
///
/// Flags affected: None
///
/// An indirect jump must never use a vector beginning on the last byte of a page. If this
/// occurs then the low byte should be as expected, and the high byte should wrap to the start
/// of the page. See http://www.6502.org/tutorials/6502opcodes.html#JMP for details.
fn jump_indr(cpu: &mut Core) -> usize {
cpu.reg.pc = cpu.indr_addr();
5
}
|
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub struct MavlinkCameraInformation {
system_id: u8,
component_id: u8,
// This is necessary since mavlink does not provide a way to have nonblock communication
// So we need the main mavlink loop live while changing the stream uri
// and forcing QGC to request the new uri available
video_stream_uri: Arc<Mutex<String>>,
verbose: bool,
vehicle:
Option<Arc<Box<dyn mavlink::MavConnection<mavlink::common::MavMessage> + Sync + Send>>>,
// Counter used to not emit heartbeats to force QGC update
restart_counter: Arc<Mutex<u8>>,
}
impl Default for MavlinkCameraInformation {
fn default() -> Self {
MavlinkCameraInformation {
system_id: 1,
component_id: mavlink::common::MavComponent::MAV_COMP_ID_CAMERA as u8,
video_stream_uri: Arc::new(Mutex::new(
"rtsp://wowzaec2demo.streamlock.net:554/vod/mp4:BigBuckBunny_115k.mov".to_string(),
)),
verbose: false,
vehicle: Default::default(),
restart_counter: Arc::new(Mutex::new(0)),
}
}
}
impl MavlinkCameraInformation {
pub fn connect(&mut self, connection_string: &str) {
let mut mavlink_connection = mavlink::connect(&connection_string).unwrap();
mavlink_connection.set_protocol_version(mavlink::MavlinkVersion::V2);
self.vehicle = Some(Arc::new(mavlink_connection));
}
pub fn set_video_stream_uri(&self, uri: String) {
*self.video_stream_uri.lock().unwrap() = uri;
*self.restart_counter.lock().unwrap() = 5;
}
pub fn set_verbosity(&mut self, verbose: bool) {
self.verbose = verbose;
}
fn heartbeat_message() -> mavlink::common::MavMessage {
mavlink::common::MavMessage::HEARTBEAT(mavlink::common::HEARTBEAT_DATA {
custom_mode: 0,
mavtype: mavlink::common::MavType::MAV_TYPE_CAMERA,
autopilot: mavlink::common::MavAutopilot::MAV_AUTOPILOT_GENERIC,
base_mode: mavlink::common::MavModeFlag::empty(),
system_status: mavlink::common::MavState::MAV_STATE_STANDBY,
mavlink_version: 0x3,
})
}
fn camera_information(&self) -> mavlink::common::MavMessage {
// Create a fixed size array with the camera name
let name_str = String::from("name");
let mut name: [u8; 32] = [0; 32];
for index in 0..name_str.len() as usize {
name[index] = name_str.as_bytes()[index];
}
// Send path to our camera configuration file
let uri: Vec<char> = format!("{}", "http://0.0.0.0").chars().collect();
// Send fake data
mavlink::common::MavMessage::CAMERA_INFORMATION(mavlink::common::CAMERA_INFORMATION_DATA {
time_boot_ms: 0,
firmware_version: 0,
focal_length: 0.0,
sensor_size_h: 0.0,
sensor_size_v: 0.0,
flags: mavlink::common::CameraCapFlags::CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM,
resolution_h: 0,
resolution_v: 0,
cam_definition_version: 0,
vendor_name: name,
model_name: name,
lens_id: 0,
cam_definition_uri: uri,
})
}
fn camera_settings(&self) -> mavlink::common::MavMessage {
//Send fake data
mavlink::common::MavMessage::CAMERA_SETTINGS(mavlink::common::CAMERA_SETTINGS_DATA {
time_boot_ms: 0,
zoomLevel: 0.0,
focusLevel: 0.0,
mode_id: mavlink::common::CameraMode::CAMERA_MODE_VIDEO,
})
}
fn camera_storage_information(&self) -> mavlink::common::MavMessage {
//Send fake data
mavlink::common::MavMessage::STORAGE_INFORMATION(
mavlink::common::STORAGE_INFORMATION_DATA {
time_boot_ms: 0,
total_capacity: 102400.0,
used_capacity: 0.0,
available_capacity: 102400.0,
read_speed: 1000.0,
write_speed: 1000.0,
storage_id: 0,
storage_count: 0,
status: mavlink::common::StorageStatus::STORAGE_STATUS_READY,
},
)
}
fn camera_capture_status(&self) -> mavlink::common::MavMessage {
//Send fake data
mavlink::common::MavMessage::CAMERA_CAPTURE_STATUS(
mavlink::common::CAMERA_CAPTURE_STATUS_DATA {
time_boot_ms: 0,
image_interval: 0.0,
recording_time_ms: 0,
available_capacity: 10000.0,
image_status: 0,
video_status: 0,
},
)
}
fn video_stream_information(&self) -> mavlink::common::MavMessage {
let name_str = String::from("name");
let mut name: [char; 32] = ['\0'; 32];
for index in 0..name_str.len() as u32 {
name[index as usize] = name_str.as_bytes()[index as usize] as char;
}
let uri: Vec<char> = format!("{}\0", self.video_stream_uri.lock().unwrap())
.chars()
.collect();
//The only important information here is the mavtype and uri variables, everything else is fake
mavlink::common::MavMessage::VIDEO_STREAM_INFORMATION(
mavlink::common::VIDEO_STREAM_INFORMATION_DATA {
framerate: 30.0,
bitrate: 1000,
flags: mavlink::common::VideoStreamStatusFlags::VIDEO_STREAM_STATUS_FLAGS_RUNNING,
resolution_h: 1000,
resolution_v: 1000,
rotation: 0,
hfov: 0,
stream_id: 1, // Starts at 1, 0 is for broadcast
count: 0,
mavtype: mavlink::common::VideoStreamType::VIDEO_STREAM_TYPE_RTSP,
name: name,
uri: uri,
},
)
}
pub fn run_loop(&self) {
let mut header = mavlink::MavHeader::default();
header.system_id = self.system_id;
header.component_id = self.component_id;
// Create heartbeat thread
thread::spawn({
let vehicle = self.vehicle.as_ref().unwrap().clone();
let restart_counter = self.restart_counter.clone();
move || loop {
thread::sleep(Duration::from_secs(1));
let mut restart_counter = restart_counter.lock().unwrap();
if *restart_counter > 0 {
println!("Restarting camera service in {} seconds.", restart_counter);
*restart_counter -= 1;
continue;
}
let res = vehicle.send(&header, &MavlinkCameraInformation::heartbeat_message());
if res.is_err() {
println!("Failed to send heartbeat: {:?}", res);
}
}
});
// Our main loop
loop {
match self.vehicle.as_ref().unwrap().recv() {
Ok((_header, msg)) => {
let vehicle = self.vehicle.as_ref().unwrap();
match msg {
// Check if there is any camera information request from gcs
mavlink::common::MavMessage::COMMAND_LONG(command_long) => {
match command_long.command {
mavlink::common::MavCmd::MAV_CMD_REQUEST_CAMERA_INFORMATION => {
println!("Sending camera_information..");
let res = vehicle.send(&header, &self.camera_information());
if res.is_err() {
println!("Failed to send camera_information: {:?}", res);
}
},
mavlink::common::MavCmd::MAV_CMD_REQUEST_CAMERA_SETTINGS => {
println!("Sending camera_settings..");
let res = vehicle.send(&header, &self.camera_settings());
if res.is_err() {
println!("Failed to send camera_settings: {:?}", res);
}
}
mavlink::common::MavCmd::MAV_CMD_REQUEST_STORAGE_INFORMATION => {
println!("Sending camera_storage_information..");
let res = vehicle.send(&header, &self.camera_storage_information());
if res.is_err() {
println!("Failed to send camera_storage_information: {:?}", res);
}
}
mavlink::common::MavCmd::MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS => {
println!("Sending camera_capture_status..");
let res = vehicle.send(&header, &self.camera_capture_status());
if res.is_err() {
println!("Failed to send camera_capture_status: {:?}", res);
}
}
mavlink::common::MavCmd::MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION => {
println!("Sending video_stream_information..");
let res = vehicle.send(&header, &self.video_stream_information());
if res.is_err() {
println!("Failed to send video_stream_information: {:?}", res);
}
}
_ => {
if self.verbose {
println!("Ignoring command: {:?}", command_long.command);
}
}
}
}
// We receive a bunch of heartbeat messages, we can ignore it
mavlink::common::MavMessage::HEARTBEAT(_) => {}
// Any other message that is not a heartbeat or command_long
_ => {
if self.verbose {
println!("Ignoring: {:?}", msg);
}
}
}
}
Err(e) => {
println!("recv error: {:?}", e);
}
}
}
}
}
|
extern crate glium;
extern crate imgui;
extern crate imgui_glium_renderer;
mod support;
const CLEAR_COLOR: [f32; 4] = [0.2, 0.2, 0.2, 1.0];
fn main() {
support::run("test_window.rs".to_owned(), CLEAR_COLOR, |ui| {
let mut open = true;
ui.show_test_window(&mut open);
open
});
}
|
#![allow(dead_code)]
use hashbrown::HashSet;
use valis_hir::{HirStorage, Identifier};
use valis_source::SourceStorage;
use valis_syntax::SyntaxStorage;
use valis_type::{
binding::{Binder, DebruijnIndex},
FuncTyData, LatticeOpTyData, LatticeOpType, ParamTy, PlaceholderTy, Polarity, RecordTyData, Ty,
TyData, TyDatabase, TyKind, TyStorage,
};
#[salsa::database(TyStorage, HirStorage, SyntaxStorage, SourceStorage)]
#[derive(Default)]
pub struct MockDB {
runtime: salsa::Runtime<MockDB>,
}
impl salsa::Database for MockDB {
fn salsa_runtime(&self) -> &salsa::Runtime<MockDB> {
&self.runtime
}
}
pub fn db() -> MockDB {
MockDB::default()
}
pub fn set_contains_pred(db: &impl TyDatabase, set: &HashSet<Ty>, elem: Ty) -> bool {
set.iter().any(|ty| ty.structual_eq(elem, db))
}
// Coerce polarity
pub fn coerce(db: &MockDB, ty: Ty) -> Ty {
let polarity = db.ty_recompute_overall_polarity(ty);
db.ty_coerce_polarity(ty, polarity)
}
fn from_kind(db: &MockDB, kind: TyKind) -> Ty {
coerce(
db,
db.intern_ty(TyData {
kind,
polarity: Some(Polarity::Either),
}),
)
}
// TYPE BUILDING BLOCKS
pub fn boolean(db: &MockDB) -> Ty {
from_kind(db, TyKind::Boolean)
}
pub fn number(db: &MockDB) -> Ty {
from_kind(db, TyKind::Number)
}
pub fn symbol(db: &MockDB) -> Ty {
from_kind(db, TyKind::Symbol)
}
pub fn top(db: &MockDB) -> Ty {
from_kind(db, TyKind::Top)
}
pub fn bottom(db: &MockDB) -> Ty {
from_kind(db, TyKind::Bottom)
}
pub fn record<S: Into<String>, IT: IntoIterator<Item = (S, Ty)>>(db: &MockDB, it: IT) -> Ty {
let fields = it
.into_iter()
.map(|(raw_ident, ty)| (Identifier::get_ident(raw_ident.into(), db), ty));
let mut labels = Vec::new();
let mut types = Vec::new();
for (ident, ty) in fields {
labels.push(ident);
types.push(ty);
}
let record_ty = db.intern_record_ty(RecordTyData { labels, types });
from_kind(db, TyKind::Record(record_ty))
}
pub fn meet<IT: IntoIterator<Item = Ty>>(db: &MockDB, it: IT) -> Ty {
let components: Vec<_> = it.into_iter().collect();
let lattice_op_ty = db.intern_lattice_op_ty(LatticeOpTyData {
op_type: LatticeOpType::Meet,
components,
});
from_kind(db, TyKind::LatticeOp(lattice_op_ty))
}
pub fn join<IT: IntoIterator<Item = Ty>>(db: &MockDB, it: IT) -> Ty {
let components: Vec<_> = it.into_iter().collect();
let lattice_op_ty = db.intern_lattice_op_ty(LatticeOpTyData {
op_type: LatticeOpType::Join,
components,
});
from_kind(db, TyKind::LatticeOp(lattice_op_ty))
}
pub fn function(db: &MockDB, input: Ty, output: Ty) -> Ty {
let func_ty = db.intern_func_ty(FuncTyData { input, output });
from_kind(db, TyKind::Function(func_ty))
}
pub fn recursive(db: &MockDB, bound: Ty) -> Ty {
from_kind(db, TyKind::Recursive(Binder::bind(bound)))
}
pub fn rec_placeholder<I: Into<DebruijnIndex>>(db: &MockDB, index: I) -> Ty {
from_kind(
db,
TyKind::Placeholder(PlaceholderTy::Recursive(index.into())),
)
}
pub fn uni_placeholder<I: Into<ParamTy>>(db: &MockDB, index: I) -> Ty {
from_kind(
db,
TyKind::Placeholder(PlaceholderTy::Universal(index.into())),
)
}
// EXAMPLE TYPES - MOSTLY BUSINESS LOGICAL
// { x: num, y: num }
pub fn point_2d_ty(db: &MockDB) -> Ty {
let x_ty = number(db);
let y_ty = number(db);
coerce(db, record(db, vec![("x", x_ty), ("y", y_ty)]))
}
// { height: num, width: num, anchor: { x: num, y: num } }
pub fn rectangle_ty(db: &MockDB) -> Ty {
let height_ty = number(db);
let width_ty = number(db);
let top_left_pt_ty = point_2d_ty(db);
coerce(
db,
record(
db,
vec![
("height", height_ty),
("width", width_ty),
("anchor", top_left_pt_ty),
],
),
)
}
// { height: num, width: num, anchor: { x: num, y: num } } -> num
pub fn calc_area_fn_ty(db: &MockDB) -> Ty {
let rect_ty = rectangle_ty(db);
let area_ty = number(db);
function(db, rect_ty, area_ty)
}
// EXAMPLE TYPES - MORE EXOTIC
// { any: top }
// this could store a value of any type
pub fn any_container_ty(db: &MockDB) -> Ty {
record(db, vec![("any", top(db))])
}
// top -> bottom
pub fn anything_to_nothing_fn_ty(db: &MockDB) -> Ty {
function(db, top(db), bottom(db))
}
// (bottom -> top) -> bottom
pub fn nothing_to_anything_to_nothing_fn_ty(db: &MockDB) -> Ty {
function(db, function(db, bottom(db), top(db)), bottom(db))
}
// (top -> bottom) -> bottom
pub fn anything_to_nothing_to_nothing_fn_ty(db: &MockDB) -> Ty {
function(db, function(db, top(db), bottom(db)), bottom(db))
}
// EXAMPLE TYPES - FUNCTIONS
// num -> bottom
pub fn number_to_bottom(db: &MockDB) -> Ty {
function(db, number(db), bottom(db))
}
// top -> num
pub fn top_to_number(db: &MockDB) -> Ty {
function(db, top(db), number(db))
}
// num -> top
pub fn number_to_top(db: &MockDB) -> Ty {
function(db, number(db), top(db))
}
// bottom -> num
pub fn bottom_to_number(db: &MockDB) -> Ty {
function(db, bottom(db), number(db))
}
// EXAMPLE TYPES - MEET & JOIN
// num ⊓ bool
pub fn num_meet_bool(db: &MockDB) -> Ty {
meet(db, vec![number(db), boolean(db)])
}
// num ⊓ (top -> num)
pub fn num_meet_fn_top_to_number(db: &MockDB) -> Ty {
meet(db, vec![number(db), function(db, top(db), number(db))])
}
// num ⊓ (bottom -> num)
pub fn num_meet_fn_bottom_to_number(db: &MockDB) -> Ty {
meet(db, vec![number(db), function(db, bottom(db), number(db))])
}
// num ⊔ bool
pub fn num_join_bool(db: &MockDB) -> Ty {
join(db, vec![number(db), boolean(db)])
}
// num ⊔ (top -> num)
pub fn num_join_fn_top_to_number(db: &MockDB) -> Ty {
join(db, vec![number(db), function(db, top(db), number(db))])
}
// num ⊔ (bottom -> num)
pub fn num_join_fn_bottom_to_number(db: &MockDB) -> Ty {
join(db, vec![number(db), function(db, bottom(db), number(db))])
}
pub fn all_basic_types_meet(db: &MockDB) -> Ty {
meet(
db,
vec![number(db), symbol(db), boolean(db), top(db), bottom(db)],
)
}
pub fn all_basic_types_join(db: &MockDB) -> Ty {
join(
db,
vec![number(db), symbol(db), boolean(db), top(db), bottom(db)],
)
}
// EXAMPLE TYPES - RECURSIVE
// 𝜇𝛼.{ height: num, width: num, anchor: { x: num, y: num } } -> num
pub fn recursive_no_placeholder(db: &MockDB) -> Ty {
recursive(db, calc_area_fn_ty(db))
}
// 𝜇𝛼.𝛽
pub fn recurive_unbound_placeholder(db: &MockDB) -> Ty {
recursive(db, rec_placeholder(db, 2u32))
}
// 𝜇𝛼.{ left: 𝛼, right: 𝛼 }
pub fn infinite_binary_tree_ty(db: &MockDB) -> Ty {
recursive(
db,
record(
db,
vec![
("left", rec_placeholder(db, 1u32)),
("right", rec_placeholder(db, 1u32)),
],
),
)
}
// 𝜇𝛼.({ left: 𝛼, right: 𝛼 }) ⊔ num
pub fn limited_binary_tree_with_num_leaves(db: &MockDB) -> Ty {
recursive(
db,
join(
db,
vec![
record(
db,
vec![
("left", rec_placeholder(db, 1u32)),
("right", rec_placeholder(db, 1u32)),
],
),
number(db),
],
),
)
}
// 𝜇𝛽.(𝜇𝛼.{ left: 𝛼, right: (𝛽 -> num) }) -> 𝛽
pub fn multiple_recursive_record_fn(db: &MockDB) -> Ty {
recursive(
db,
function(
db,
recursive(
db,
record(
db,
vec![
("left", rec_placeholder(db, 1u32)),
("right", function(db, rec_placeholder(db, 2u32), number(db))),
],
),
),
rec_placeholder(db, 1u32),
),
)
}
pub fn recursive_not_guarded(db: &MockDB) -> Ty {
recursive(db, join(db, vec![rec_placeholder(db, 1u32), number(db)]))
}
pub fn recursive_not_covariant(db: &MockDB) -> Ty {
recursive(
db,
function(
db,
function(db, number(db), rec_placeholder(db, 1u32)),
number(db),
),
)
}
// EXAMPLE TYPES - CONTAINING FREE VARIABLES
// { fst: 𝛼, snd: 𝛽 }
pub fn generic_pair_record(db: &MockDB) -> Ty {
record(
db,
vec![
("fst", uni_placeholder(db, 0u32)),
("snd", uni_placeholder(db, 1u32)),
],
)
}
|
use std::fs;
use regex::Regex;
fn find(a: usize, seat: &str, start: usize, end: usize,
lower: usize, upper: usize,
upper_char: char, lower_char: char) -> usize {
match seat.chars().nth(a) {
Some(c) => {
if c == lower_char {
if a == end - 1 {
return lower;
}
return find(a+1, seat, start, end,
lower, (upper + lower) / 2,
upper_char, lower_char);
}
else if c == upper_char {
if a == end - 1 {
return upper;
}
return find(a+1, seat, start, end,
(upper + lower) / 2 + 1, upper,
upper_char, lower_char);
}
else {
println!("Error: invalid input");
return 0;
}
}
None => {
return 0;
}
}
}
fn find_row(s: &str) -> usize {
find(0, s, 0, 7, 0, 127, 'B', 'F')
}
fn find_column(s: &str) -> usize {
find(7, s, 7, 10, 0, 7, 'R', 'L')
}
fn find_rowid(s: &str) -> usize {
find_row(s) * 8 + find_column(s)
}
fn part1(inputstr: &str) -> usize {
*(Regex::new("\n")
.expect("Could not read regex")
.split(inputstr)
.map(|x| find_rowid(x))
.collect::<Vec<usize>>()
.iter()
.max()
.unwrap())
}
fn part2(inputstr: &str) -> usize {
let mut l = Regex::new("\n")
.expect("Could not read regex")
.split(inputstr)
.filter(|x| {
let r = find_row(x);
if r == 0 || r == 127 {
return false;
}
true
})
.map(|x| find_rowid(x))
.collect::<Vec<usize>>();
l.sort();
for a in 0..l.len()-2 {
if l[a] != l.len() - 1 {
if l[a] + 1 != l[a + 1] {
return l[a] + 1;
}
}
}
0
}
fn main() {
let inputfile = fs::read_to_string("input.txt")
.expect("File could not be read");
println!("Part1: {}",
part1(&inputfile));
println!("Part2: {}", part2(&inputfile));
}
|
mod processor;
pub use processor::ProxyProcessor;
use crate::CoreLayer;
use crate::CoreProcessor;
use common::{async_trait::async_trait, tokio};
use std::{
any::Any,
sync::{Arc, Weak},
};
use crate::SipManager;
use models::transport::TransportMsg;
pub struct Proxy<P: CoreProcessor> {
inner: Arc<Inner<P>>,
}
#[async_trait]
impl<P: CoreProcessor> CoreLayer for Proxy<P> {
fn new(sip_manager: Weak<SipManager>) -> Self {
let inner = Arc::new(Inner {
sip_manager: sip_manager.clone(),
processor: Arc::new(P::new(sip_manager)),
});
Self { inner }
}
async fn process_incoming_message(&self, msg: TransportMsg) {
self.inner.process_incoming_message(msg).await
}
async fn send(&self, msg: TransportMsg) {
self.inner.send(msg).await
}
async fn run(&self) {
let inner = self.inner.clone();
tokio::spawn(async move {
inner.run().await;
});
}
fn as_any(&self) -> &dyn Any {
self
}
}
struct Inner<P: CoreProcessor> {
sip_manager: Weak<SipManager>,
processor: Arc<P>,
}
impl<P: CoreProcessor> Inner<P> {
//TODO: remove expect and log instead
async fn process_incoming_message(&self, msg: TransportMsg) {
let processor = self.processor.clone();
tokio::spawn(async move {
match processor.process_incoming_message(msg).await {
Ok(()) => (),
Err(err) => common::log::warn!("failed to process message: {:?}", err),
}
});
}
async fn send(&self, msg: TransportMsg) {
match self.sip_manager().transport.send(msg).await {
Ok(_) => (),
Err(err) => common::log::error!("failed to send message: {:?}", err),
}
}
fn sip_manager(&self) -> Arc<SipManager> {
self.sip_manager.upgrade().expect("sip manager is missing!")
}
async fn run(&self) {}
}
impl<P: CoreProcessor> std::fmt::Debug for Proxy<P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("proxy")
.field("processor", &self.inner.processor)
.finish()
}
}
|
use crossterm::cursor::MoveToColumn;
#[cfg(feature = "sync")]
use crossterm::event::{poll, read, Event};
#[cfg(feature = "async-tokio")]
use crossterm::event::{Event, EventStream};
#[cfg(any(feature = "sync", feature = "async-tokio"))]
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
#[cfg(any(feature = "sync", feature = "async-tokio"))]
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use crossterm::terminal::{Clear, ClearType};
#[cfg(any(feature = "sync", feature = "async-tokio"))]
use crossterm::Result as CrossTermResult;
#[cfg(feature = "sync")]
use flume::{Receiver, Sender};
#[cfg(feature = "async-tokio")]
use futures::StreamExt;
use std::io::stdout;
#[cfg(any(feature = "sync", feature = "async-tokio"))]
use std::io::Write;
#[cfg(feature = "sync")]
use std::time::Duration;
#[cfg(feature = "async-tokio")]
use tokio::runtime::Runtime;
#[cfg(feature = "async-tokio")]
use tokio::sync::mpsc::{UnboundedReceiver as Receiver, UnboundedSender as Sender};
pub type CmdFunc = fn(String);
#[derive(Clone)]
pub struct Config {
pub input_prompt: Option<String>,
pub output_prompt: Option<String>,
pub exit_command: Option<String>,
pub exit_on_esc: bool,
pub exit_on_ctrl_c: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
input_prompt: Some("Input>".into()),
output_prompt: Some("Output>".into()),
exit_command: Some("exit".into()),
exit_on_esc: true,
exit_on_ctrl_c: true,
}
}
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
macro_rules! print_now {
($t:ident) => {
print!("{}", $t);
let _ = stdout().flush();
};
($fmt:expr, $($arg:tt), +) => {
print!($fmt, $($arg), +);
let _ = stdout().flush();
};
}
macro_rules! clear_line {
() => {
let _ = execute!(stdout(), Clear(ClearType::CurrentLine), MoveToColumn(0));
};
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
fn exit_on_key(config: &Config, event: &KeyEvent) -> bool {
use KeyCode::{Char, Esc};
match (event.code, event.modifiers) {
(Esc, _) => config.exit_on_esc,
(Char('c'), m) | (Char('C'), m) => {
config.exit_on_ctrl_c && m.contains(KeyModifiers::CONTROL)
}
_ => false,
}
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
fn output_prompt(prompt: &Option<String>) {
if let Some(s) = prompt {
print_now!("{} ", s);
}
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
fn output_with_prompt(prompt: &Option<String>, command: &str, newline: bool) {
clear_line!();
match (prompt, newline) {
(Some(s), true) => println!("{} {}", s, command),
(None, true) => println!("{}", command),
(Some(s), false) => {
print_now!("{} {}", s, command);
}
(None, false) => {
print_now!(command);
}
}
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
fn output_on_key<F>(cfg: &Config, evt: &KeyEvent, cmd: &mut String, cb: &F) -> bool
where
F: Fn(String),
{
match evt.code {
KeyCode::Enter => {
println!("\r");
if !cmd.is_empty() {
if let Some(exit_command) = &cfg.exit_command {
if cmd == exit_command {
return true;
}
}
cb(cmd.to_string());
cmd.clear();
}
output_prompt(&cfg.input_prompt);
}
KeyCode::Backspace => {
cmd.pop();
clear_line!();
output_with_prompt(&cfg.input_prompt, cmd, false);
}
KeyCode::Char(c) => {
cmd.push(c);
print_now!(c);
}
_ => {}
}
false
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
fn output_on_info(config: &Config, info: &str, cmd: &str) {
output_with_prompt(&config.output_prompt, info, true);
output_with_prompt(&config.input_prompt, cmd, false);
}
pub fn println_clint(info: String) {
clear_line!();
println!("{}", info);
clear_line!();
}
#[cfg(feature = "sync")]
pub fn loop_sync<F>(
config: Config,
interval: Duration,
receiver: Receiver<String>,
callback: F,
) -> CrossTermResult<()>
where
F: Fn(String),
{
enable_raw_mode()?;
let result = loop_sync_internal(config, interval, receiver, callback);
if result.is_err() {
let _ = disable_raw_mode();
return result;
}
disable_raw_mode()
}
#[cfg(feature = "sync")]
fn loop_sync_internal<F>(
config: Config,
interval: Duration,
receiver: Receiver<String>,
callback: F,
) -> CrossTermResult<()>
where
F: Fn(String),
{
// let mut writer = stdout();
let mut cmd = String::new();
println!("\r");
output_prompt(&config.input_prompt);
loop {
if poll(interval)? {
if let Event::Key(keyevent) = read()? {
if exit_on_key(&config, &keyevent) {
println!("\r");
break;
}
if output_on_key(&config, &keyevent, &mut cmd, &callback) {
break;
}
}
} else if let Ok(info) = receiver.try_recv() {
output_on_info(&config, &info, &cmd);
}
}
Ok(())
}
// #[cfg(feature = "async")]
// async fn output(text: String) {
// output_on_info(&config, &info, &cmd);
// }
#[cfg(feature = "async-tokio")]
pub fn loop_async_tokio_blocking<F>(
config: Config,
receiver: Receiver<String>,
callback: F,
) -> CrossTermResult<()>
where
F: Fn(String),
{
enable_raw_mode()?;
// Create the runtime
let rt = Runtime::new().unwrap();
// Execute the future, blocking the current thread until completion
let result =
rt.block_on(async move { loop_async_tokio_internal(config, receiver, callback).await });
if result.is_err() {
let _ = disable_raw_mode();
return result;
}
disable_raw_mode()
}
#[cfg(feature = "async-tokio")]
async fn loop_async_tokio_internal<F>(
config: Config,
mut receiver: Receiver<String>,
callback: F,
) -> CrossTermResult<()>
where
F: Fn(String),
{
let mut reader = EventStream::new();
let mut cmd = String::new();
loop {
let event = reader.next();
let ext_event = receiver.recv();
tokio::select! {
maybe_event = event => {
match maybe_event {
Some(Ok(event)) => {
if let Event::Key(keyevent) = event {
if exit_on_key(&config, &keyevent) {
println!("\r");
break Ok(());
}
if output_on_key(&config, &keyevent, &mut cmd, &callback) {
break Ok(());
}
}
}
Some(Err(e)) => println!("Error: {:?}\r", e),
None => break Ok(()),
}
},
ext = ext_event => {
if let Some(info) = ext{
output_on_info(&config, &info, &cmd);
}
}
};
}
}
pub struct ClintLogger {
#[cfg(any(feature = "sync", feature = "async-tokio"))]
sender: Sender<String>,
}
impl ClintLogger {
#[cfg(any(feature = "sync", feature = "async-tokio"))]
pub fn init(sender: Sender<String>) {
ClintLogger::init_logger(ClintLogger { sender });
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
fn init_logger(logger: ClintLogger) {
log::set_max_level(log::LevelFilter::Info);
let _ = log::set_boxed_logger(Box::new(logger));
}
}
impl log::Log for ClintLogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
#[cfg(any(feature = "sync", feature = "async-tokio"))]
self.sender
.send(format!(
"[{}]:[{}] -- {}",
record.level(),
record.target(),
record.args()
))
.unwrap();
}
fn flush(&self) {}
}
|
pub mod header_component;
pub mod homepage_component;
pub mod item_wrapper_component;
pub mod todo_item_component;
pub mod add_item_component;
|
use crate::{
gui::{BuildContext, Ui, UiMessage, UiNode},
scene::EditorScene,
settings::{
debugging::{DebuggingSection, DebuggingSettings},
graphics::{GraphicsSection, GraphicsSettings},
move_mode::{MoveInteractionModeSettings, MoveModeSection},
},
GameEngine, Message, CONFIG_DIR,
};
use rg3d::gui::formatted_text::WrapMode;
use rg3d::{
core::{pool::Handle, scope_profile},
gui::{
border::BorderBuilder,
button::ButtonBuilder,
check_box::CheckBoxBuilder,
grid::{Column, GridBuilder, Row},
message::{
ButtonMessage, MessageDirection, TreeRootMessage, UiMessageData, WidgetMessage,
WindowMessage,
},
numeric::NumericUpDownBuilder,
stack_panel::StackPanelBuilder,
text::TextBuilder,
tree::{TreeBuilder, TreeRootBuilder},
widget::WidgetBuilder,
window::{WindowBuilder, WindowTitle},
HorizontalAlignment, Orientation, Thickness, VerticalAlignment,
},
};
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use std::{fs::File, path::PathBuf, sync::mpsc::Sender};
pub mod debugging;
pub mod graphics;
pub mod move_mode;
struct SwitchEntry {
tree_item: Handle<UiNode>,
section: Handle<UiNode>,
kind: SettingsSectionKind,
}
pub struct SettingsWindow {
window: Handle<UiNode>,
ok: Handle<UiNode>,
default: Handle<UiNode>,
sender: Sender<Message>,
graphics_section: GraphicsSection,
move_mode_section: MoveModeSection,
debugging_section: DebuggingSection,
section_switches: Vec<SwitchEntry>,
sections_root: Handle<UiNode>,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum SettingsSectionKind {
Graphics,
Debugging,
MoveModeSettings,
}
#[derive(Deserialize, Serialize, PartialEq, Clone, Default)]
pub struct Settings {
pub graphics: GraphicsSettings,
pub debugging: DebuggingSettings,
pub move_mode_settings: MoveInteractionModeSettings,
}
#[derive(Debug)]
pub enum SettingsError {
Io(std::io::Error),
Ron(ron::Error),
}
impl From<std::io::Error> for SettingsError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl From<ron::Error> for SettingsError {
fn from(e: ron::Error) -> Self {
Self::Ron(e)
}
}
impl Settings {
const FILE_NAME: &'static str = "settings.ron";
fn full_path() -> PathBuf {
CONFIG_DIR.lock().unwrap().join(Self::FILE_NAME)
}
pub fn load() -> Result<Self, SettingsError> {
let file = File::open(Self::full_path())?;
Ok(ron::de::from_reader(file)?)
}
pub fn save(&self) -> Result<(), SettingsError> {
let file = File::create(Self::full_path())?;
ron::ser::to_writer_pretty(file, self, PrettyConfig::default())?;
Ok(())
}
}
fn make_text_mark(ctx: &mut BuildContext, text: &str, row: usize) -> Handle<UiNode> {
TextBuilder::new(
WidgetBuilder::new()
.with_vertical_alignment(VerticalAlignment::Center)
.with_margin(Thickness::left(4.0))
.on_row(row)
.on_column(0),
)
.with_text(text)
.build(ctx)
}
fn make_bool_input_field(ctx: &mut BuildContext, row: usize, value: bool) -> Handle<UiNode> {
CheckBoxBuilder::new(
WidgetBuilder::new()
.on_row(row)
.with_margin(Thickness::uniform(1.0))
.on_column(1),
)
.checked(Some(value))
.build(ctx)
}
fn make_f32_input_field(
ctx: &mut BuildContext,
row: usize,
value: f32,
min: f32,
) -> Handle<UiNode> {
NumericUpDownBuilder::new(
WidgetBuilder::new()
.on_column(1)
.on_row(row)
.with_margin(Thickness::uniform(1.0)),
)
.with_value(value)
.with_min_value(min)
.with_min_value(min)
.build(ctx)
}
impl SettingsWindow {
pub fn new(engine: &mut GameEngine, sender: Sender<Message>, settings: &Settings) -> Self {
let ok;
let default;
let ctx = &mut engine.user_interface.build_ctx();
let text =
"Here you can select graphics settings to improve performance and/or to understand how \
you scene will look like with different graphics settings. Please note that these settings won't be saved \
with scene!";
let graphics_section = GraphicsSection::new(ctx, &settings.graphics);
let debugging_section = DebuggingSection::new(ctx, &settings.debugging);
let move_mode_section = MoveModeSection::new(ctx, &settings.move_mode_settings);
let sections_root;
let graphics_section_item;
let debugging_section_item;
let move_mode_section_item;
let section = GridBuilder::new(
WidgetBuilder::new()
.on_row(1)
.with_child({
sections_root =
TreeRootBuilder::new(WidgetBuilder::new().on_column(0).on_row(0))
.with_items(vec![
{
graphics_section_item = TreeBuilder::new(WidgetBuilder::new())
.with_content(
TextBuilder::new(WidgetBuilder::new())
.with_text("Graphics")
.build(ctx),
)
.build(ctx);
graphics_section_item
},
{
debugging_section_item = TreeBuilder::new(WidgetBuilder::new())
.with_content(
TextBuilder::new(WidgetBuilder::new())
.with_text("Debugging")
.build(ctx),
)
.build(ctx);
debugging_section_item
},
{
move_mode_section_item = TreeBuilder::new(WidgetBuilder::new())
.with_content(
TextBuilder::new(WidgetBuilder::new())
.with_text("Move Interaction Mode")
.build(ctx),
)
.build(ctx);
move_mode_section_item
},
])
.build(ctx);
sections_root
})
.with_child(
BorderBuilder::new(WidgetBuilder::new().on_row(0).on_column(1).with_children(
[
graphics_section.section,
debugging_section.section,
move_mode_section.section,
],
))
.build(ctx),
),
)
.add_row(Row::stretch())
.add_column(Column::strict(200.0))
.add_column(Column::stretch())
.build(ctx);
let section_switches = vec![
SwitchEntry {
tree_item: graphics_section_item,
section: graphics_section.section,
kind: SettingsSectionKind::Graphics,
},
SwitchEntry {
tree_item: debugging_section_item,
section: debugging_section.section,
kind: SettingsSectionKind::Debugging,
},
SwitchEntry {
tree_item: move_mode_section_item,
section: move_mode_section.section,
kind: SettingsSectionKind::MoveModeSettings,
},
];
let window = WindowBuilder::new(WidgetBuilder::new().with_width(500.0).with_height(600.0))
.open(false)
.with_title(WindowTitle::Text("Settings".to_owned()))
.with_content(
GridBuilder::new(
WidgetBuilder::new()
.with_child(
TextBuilder::new(
WidgetBuilder::new()
.on_row(0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text(text)
.with_wrap(WrapMode::Word)
.build(ctx),
)
.with_child(section)
.with_child(
StackPanelBuilder::new(
WidgetBuilder::new()
.on_row(2)
.with_horizontal_alignment(HorizontalAlignment::Right)
.with_child({
default = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("Default")
.build(ctx);
default
})
.with_child({
ok = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("OK")
.build(ctx);
ok
}),
)
.with_orientation(Orientation::Horizontal)
.build(ctx),
),
)
.add_row(Row::auto())
.add_row(Row::stretch())
.add_row(Row::strict(25.0))
.add_column(Column::stretch())
.build(ctx),
)
.build(ctx);
Self {
sections_root,
section_switches,
window,
sender,
ok,
default,
graphics_section,
move_mode_section,
debugging_section,
}
}
pub fn open(&self, ui: &Ui, settings: &Settings, section: Option<SettingsSectionKind>) {
ui.send_message(WindowMessage::open(
self.window,
MessageDirection::ToWidget,
true,
));
if let Some(section) = section {
for entry in self.section_switches.iter() {
if entry.kind == section {
ui.send_message(TreeRootMessage::select(
self.sections_root,
MessageDirection::ToWidget,
vec![entry.tree_item],
));
}
}
}
self.sync_to_model(ui, settings);
}
fn sync_to_model(&self, ui: &Ui, settings: &Settings) {
self.graphics_section.sync_to_model(ui, &settings.graphics);
self.move_mode_section
.sync_to_model(ui, &settings.move_mode_settings);
self.debugging_section
.sync_to_model(ui, &settings.debugging);
}
pub fn handle_message(
&mut self,
message: &UiMessage,
editor_scene: &EditorScene,
engine: &mut GameEngine,
settings: &mut Settings,
) {
scope_profile!();
let old_settings = settings.clone();
self.graphics_section
.handle_message(message, editor_scene, engine, &mut settings.graphics);
self.debugging_section
.handle_message(message, &mut settings.debugging);
self.move_mode_section
.handle_message(message, &mut settings.move_mode_settings);
match message.data() {
UiMessageData::Button(ButtonMessage::Click) => {
if message.destination() == self.ok {
engine.user_interface.send_message(WindowMessage::close(
self.window,
MessageDirection::ToWidget,
));
} else if message.destination() == self.default {
*settings = Default::default();
self.sync_to_model(&engine.user_interface, settings);
}
}
UiMessageData::TreeRoot(TreeRootMessage::Selected(items)) => {
if let Some(selected) = items.first().cloned() {
for entry in self.section_switches.iter() {
engine
.user_interface
.send_message(WidgetMessage::visibility(
entry.section,
MessageDirection::ToWidget,
entry.tree_item == selected,
))
}
}
}
_ => {}
}
// Apply only if anything changed.
if settings != &old_settings {
if settings.graphics.quality != engine.renderer.get_quality_settings() {
if let Err(e) = engine
.renderer
.set_quality_settings(&settings.graphics.quality)
{
self.sender
.send(Message::Log(format!(
"An error occurred at attempt to set new graphics settings: {:?}",
e
)))
.unwrap();
} else {
self.sender
.send(Message::Log(
"New graphics quality settings were successfully set!".to_owned(),
))
.unwrap();
}
}
// Save config
match settings.save() {
Ok(_) => {
println!("Settings were successfully saved!");
}
Err(e) => {
println!("Unable to save settings! Reason: {:?}!", e);
}
};
}
}
}
|
/// Transform a traditional `for` loop into a parallel `for_each`
///
/// ```rust,ignore
/// for item in expr { /* body */ }
/// ```
///
/// becomes roughly:
///
/// ```rust,ignore
/// expr.into_par_iter().for_each(|item| { /* body */ });
/// ```
#[proc_macro_hack::proc_macro_hack]
pub use rayon_macro_hack::parallel;
#[doc(hidden)]
pub mod rayon_macro_impl {
pub use rayon::iter::{IntoParallelIterator, ParallelIterator};
}
|
use crate::api::models::bridgechain::Bridgechain;
use crate::api::Result;
use crate::http::client::Client;
use std::borrow::Borrow;
use std::collections::HashMap;
pub struct Bridgechains {
client: Client,
}
impl Bridgechains {
pub fn new(client: Client) -> Bridgechains {
Bridgechains { client }
}
pub async fn all(&mut self) -> Result<Vec<Bridgechain>> {
self.all_params(Vec::<(String, String)>::new()).await
}
pub async fn all_params<I, K, V>(&mut self, parameters: I) -> Result<Vec<Bridgechain>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
self.client
.get_with_params("bridgechains", parameters)
.await
}
pub async fn show(&mut self, genesis_hash: &str) -> Result<Bridgechain> {
let endpoint = format!("bridgechains/{}", genesis_hash);
self.client.get(&endpoint).await
}
pub async fn search<I, K, V>(
&mut self,
payload: HashMap<&str, &str>,
parameters: I,
) -> Result<Vec<Bridgechain>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
self.client
.post_with_params("bridgechains/search", payload, parameters)
.await
}
}
|
// q0102_binary_tree_level_order_traversal
struct Solution;
use crate::util::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
if let Some(rrc_root) = root {
let mut ret = vec![];
let mut level_node = vec![rrc_root];
loop {
let mut new_level_node = vec![];
let mut level_ret = vec![];
for node in level_node.iter() {
let val = node.borrow().val;
level_ret.push(val);
if let Some(ref ln) = node.borrow().left {
new_level_node.push(Rc::clone(ln));
}
if let Some(ref rn) = node.borrow().right {
new_level_node.push(Rc::clone(rn));
}
}
ret.push(level_ret);
if new_level_node.is_empty() {
break;
} else {
std::mem::replace(&mut level_node, new_level_node);
}
}
return ret;
} else {
return vec![];
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
use crate::util::TreeNode;
#[test]
fn it_works() {
assert_eq!(
Solution::level_order(TreeNode::build(vec![
Some(3),
Some(9),
Some(20),
None,
None,
Some(15),
Some(7)
])),
vec![vec![3], vec![9, 20], vec![15, 7]]
);
assert_eq!(
Solution::level_order(TreeNode::build(Vec::<Option<i32>>::new())),
Vec::<Vec<i32>>::new()
);
}
}
|
pub(crate) use std::fs::Metadata;
use std::{ffi::OsStr, io, path::Path};
pub(crate) use fs_err::*;
/// Removes a file from the filesystem **if exists**.
pub(crate) fn remove_file(path: impl AsRef<Path>) -> io::Result<()> {
match fs_err::remove_file(path.as_ref()) {
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
res => res,
}
}
/// Removes a directory at this path **if exists**.
pub(crate) fn remove_dir_all(path: impl AsRef<Path>) -> io::Result<()> {
match fs_err::remove_dir_all(path.as_ref()) {
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
res => res,
}
}
pub(crate) fn file_stem_recursive(path: &Path) -> Option<&OsStr> {
let mut file_name = path.file_name()?;
while let Some(stem) = Path::new(file_name).file_stem() {
if file_name == stem {
break;
}
file_name = stem;
}
Some(file_name)
}
|
use std::{
collections::{hash_map, HashMap},
fmt::Debug,
marker::PhantomData,
net::SocketAddr,
ops::Deref,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU32, AtomicUsize, Ordering},
Arc,
},
time::Duration,
};
use async_trait::async_trait;
use bonsaidb_core::{
admin::{Admin, User},
connection::{self, AccessPolicy, QueryKey, ServerConnection},
custodian_password::{
LoginFinalization, LoginRequest, RegistrationFinalization, RegistrationRequest,
},
custom_api::CustomApi,
kv::KeyOperation,
networking::{
self, CreateDatabaseHandler, DatabaseRequest, DatabaseRequestDispatcher, DatabaseResponse,
DeleteDatabaseHandler, Payload, Request, RequestDispatcher, Response, ServerRequest,
ServerRequestDispatcher, ServerResponse,
},
permissions::{
bonsai::{
bonsaidb_resource_name, collection_resource_name, database_resource_name,
document_resource_name, kv_key_resource_name, pubsub_topic_resource_name,
user_resource_name, view_resource_name, BonsaiAction, DatabaseAction, DocumentAction,
KvAction, PubSubAction, ServerAction, TransactionAction, ViewAction,
},
Action, Dispatcher, PermissionDenied, Permissions, ResourceName,
},
schema,
schema::{Collection, CollectionName, NamedReference, Schema, ViewName},
transaction::{Command, Transaction},
};
#[cfg(feature = "pubsub")]
use bonsaidb_core::{
circulate::{Message, Relay, Subscriber},
pubsub::database_topic,
};
use bonsaidb_jobs::{manager::Manager, Job};
use bonsaidb_local::{OpenDatabase, Storage};
use cfg_if::cfg_if;
use fabruic::{self, Certificate, CertificateChain, Endpoint, KeyPair, PrivateKey};
use flume::Sender;
#[cfg(feature = "websockets")]
use futures::SinkExt;
use futures::{Future, StreamExt, TryFutureExt};
use schema::SchemaName;
#[cfg(feature = "websockets")]
use tokio::net::TcpListener;
use tokio::{fs::File, sync::RwLock};
use crate::{
async_io_util::FileExt, backend::ConnectionHandling, error::Error, Backend, Configuration,
};
mod connected_client;
mod database;
use self::connected_client::OwnedClient;
#[cfg(feature = "pubsub")]
pub use self::database::ServerSubscriber;
pub use self::{
connected_client::{ConnectedClient, Transport},
database::ServerDatabase,
};
static CONNECTED_CLIENT_ID_COUNTER: AtomicU32 = AtomicU32::new(0);
/// A `BonsaiDb` server.
#[derive(Debug)]
pub struct CustomServer<B: Backend> {
data: Arc<Data<B>>,
}
/// A `BonsaiDb` server without a custom bakend.
pub type Server = CustomServer<()>;
impl<B: Backend> Clone for CustomServer<B> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
}
}
}
#[derive(Debug)]
struct Data<B: Backend = ()> {
directory: PathBuf,
storage: Storage,
clients: RwLock<HashMap<u32, ConnectedClient<B>>>,
request_processor: Manager,
default_permissions: Permissions,
endpoint: RwLock<Option<Endpoint>>,
client_simultaneous_request_limit: usize,
#[cfg(feature = "websockets")]
websocket_shutdown: RwLock<Option<Sender<()>>>,
#[cfg(feature = "pubsub")]
relay: Relay,
#[cfg(feature = "pubsub")]
subscribers: Arc<RwLock<HashMap<u64, Subscriber>>>,
_backend: PhantomData<B>,
}
impl<B: Backend> CustomServer<B> {
/// Opens a server using `directory` for storage.
pub async fn open(directory: &Path, configuration: Configuration) -> Result<Self, Error> {
let request_processor = Manager::default();
for _ in 0..configuration.request_workers {
request_processor.spawn_worker();
}
let storage = Storage::open_local(directory, configuration.storage).await?;
Ok(Self {
data: Arc::new(Data {
clients: RwLock::default(),
storage,
directory: directory.to_owned(),
endpoint: RwLock::default(),
request_processor,
default_permissions: configuration.default_permissions,
client_simultaneous_request_limit: configuration.client_simultaneous_request_limit,
#[cfg(feature = "websockets")]
websocket_shutdown: RwLock::default(),
#[cfg(feature = "pubsub")]
relay: Relay::default(),
#[cfg(feature = "pubsub")]
subscribers: Arc::default(),
_backend: PhantomData::default(),
}),
})
}
/// Returns the path to the directory that stores this server's data.
#[must_use]
pub fn directory(&self) -> &'_ PathBuf {
&self.data.directory
}
/// Retrieves a database. This function only verifies that the database exists.
pub async fn database<DB: Schema>(
&self,
name: &'_ str,
) -> Result<ServerDatabase<'_, B, DB>, Error> {
let db = self.data.storage.database(name).await?;
Ok(ServerDatabase { server: self, db })
}
/// Returns the administration database.
pub async fn admin(&self) -> ServerDatabase<'_, B, Admin> {
let db = self.data.storage.admin().await;
ServerDatabase { server: self, db }
}
pub(crate) async fn database_without_schema(
&self,
name: &'_ str,
) -> Result<Box<dyn OpenDatabase>, Error> {
let db = self.data.storage.database_without_schema(name).await?;
Ok(db)
}
/// Installs an X.509 certificate used for general purpose connections.
pub async fn install_self_signed_certificate(
&self,
server_name: &str,
overwrite: bool,
) -> Result<(), Error> {
let keypair = KeyPair::new_self_signed(server_name);
if self.certificate_path().exists() && !overwrite {
return Err(Error::Core(bonsaidb_core::Error::Configuration(String::from("Certificate already installed. Enable overwrite if you wish to replace the existing certificate."))));
}
self.install_certificate(keypair.end_entity_certificate(), keypair.private_key())
.await?;
Ok(())
}
/// Installs an X.509 certificate used for general purpose connections.
/// These currently must be in DER binary format, not ASCII PEM format.
pub async fn install_certificate(
&self,
certificate: &Certificate,
private_key: &PrivateKey,
) -> Result<(), Error> {
File::create(self.certificate_path())
.and_then(|file| file.write_all(certificate.as_ref()))
.await
.map_err(|err| {
Error::Core(bonsaidb_core::Error::Configuration(format!(
"Error writing certificate file: {}",
err
)))
})?;
File::create(self.private_key_path())
.and_then(|file| file.write_all(fabruic::dangerous::PrivateKey::as_ref(private_key)))
.await
.map_err(|err| {
Error::Core(bonsaidb_core::Error::Configuration(format!(
"Error writing private key file: {}",
err
)))
})?;
Ok(())
}
fn certificate_path(&self) -> PathBuf {
self.data.directory.join("public-certificate.der")
}
/// Returns the current certificate.
pub async fn certificate(&self) -> Result<Certificate, Error> {
Ok(File::open(self.certificate_path())
.and_then(FileExt::read_all)
.await
.map(Certificate::unchecked_from_der)
.map_err(|err| {
Error::Core(bonsaidb_core::Error::Configuration(format!(
"Error reading certificate file: {}",
err
)))
})?)
}
fn private_key_path(&self) -> PathBuf {
self.data.directory.join("private-key.der")
}
/// Listens for incoming client connections. Does not return until the
/// server shuts down.
pub async fn listen_on(&self, port: u16) -> Result<(), Error> {
let certificate = self.certificate().await?;
let private_key = File::open(self.private_key_path())
.and_then(FileExt::read_all)
.await
.map(PrivateKey::from_der)
.map_err(|err| {
Error::Core(bonsaidb_core::Error::Configuration(format!(
"Error reading private key file: {}",
err
)))
})??;
let certchain = CertificateChain::from_certificates(vec![certificate])?;
let keypair = KeyPair::from_parts(certchain, private_key)?;
let mut server = Endpoint::new_server(port, keypair)?;
{
let mut endpoint = self.data.endpoint.write().await;
*endpoint = Some(server.clone());
}
while let Some(result) = server.next().await {
let connection = result.accept::<()>().await?;
let task_self = self.clone();
tokio::spawn(async move {
let address = connection.remote_address();
if let Err(err) = task_self.handle_bonsai_connection(connection).await {
eprintln!("[server] closing connection {}: {:?}", address, err);
}
});
}
Ok(())
}
/// Listens for `WebSocket` traffic on `port`.
#[cfg(feature = "websockets")]
pub async fn listen_for_websockets_on<T: tokio::net::ToSocketAddrs + Send + Sync>(
&self,
addr: T,
) -> Result<(), Error> {
let listener = TcpListener::bind(&addr).await?;
let (shutdown_sender, shutdown_receiver) = flume::bounded(1);
{
let mut shutdown = self.data.websocket_shutdown.write().await;
*shutdown = Some(shutdown_sender);
}
loop {
tokio::select! {
_ = shutdown_receiver.recv_async() => {
break;
}
incoming = listener.accept() => {
if incoming.is_err() {
continue;
}
let (connection, remote_addr) = incoming.unwrap();
let task_self = self.clone();
tokio::spawn(async move {
if let Err(err) = task_self.handle_websocket_connection(connection).await {
eprintln!("[server] closing connection {}: {:?}", remote_addr, err);
}
});
}
}
}
Ok(())
}
/// Returns all of the currently connected clients.
pub async fn connected_clients(&self) -> Vec<ConnectedClient<B>> {
let clients = self.data.clients.read().await;
clients.values().cloned().collect()
}
/// Sends a custom API response to all connected clients.
pub async fn broadcast(&self, response: <B::CustomApi as CustomApi>::Response) {
let clients = self.data.clients.read().await;
for client in clients.values() {
drop(client.send(response.clone()));
}
}
async fn initialize_client(
&self,
transport: Transport,
address: SocketAddr,
sender: Sender<<B::CustomApi as CustomApi>::Response>,
) -> Option<OwnedClient<B>> {
let client = loop {
let next_id = CONNECTED_CLIENT_ID_COUNTER.fetch_add(1, Ordering::SeqCst);
let mut clients = self.data.clients.write().await;
if let hash_map::Entry::Vacant(e) = clients.entry(next_id) {
let client = OwnedClient::new(next_id, address, transport, sender, self.clone());
e.insert(client.clone());
break client;
}
};
if matches!(
B::client_connected(&client, self).await,
ConnectionHandling::Accept
) {
Some(client)
} else {
None
}
}
async fn disconnect_client(&self, id: u32) {
if let Some(client) = {
let mut clients = self.data.clients.write().await;
clients.remove(&id)
} {
B::client_disconnected(client, self).await;
}
}
async fn handle_bonsai_connection(
&self,
mut connection: fabruic::Connection<()>,
) -> Result<(), Error> {
if let Some(incoming) = connection.next().await {
let incoming = match incoming {
Ok(incoming) => incoming,
Err(err) => {
eprintln!("[server] Error establishing a stream: {:?}", err);
return Ok(());
}
};
match incoming
.accept::<networking::Payload<Response<<B::CustomApi as CustomApi>::Response>>, networking::Payload<Request<<B::CustomApi as CustomApi>::Request>>>()
.await
{
Ok((sender, receiver)) => {
let (api_response_sender, api_response_receiver) = flume::unbounded();
if let Some(disconnector) = self.initialize_client(Transport::Bonsai, connection.remote_address(), api_response_sender).await {
let task_sender = sender.clone();
tokio::spawn(async move {
while let Ok(response) = api_response_receiver.recv_async().await {
if task_sender.send(&Payload {
id: None,
wrapped: Response::Api(response)
}).is_err() {
break;
}
}
});
let task_self = self.clone();
tokio::spawn(async move { task_self.handle_stream(disconnector, sender, receiver).await });
} else {
eprintln!("[server] Backend rejected connection.");
return Ok(())
}
}
Err(err) => {
eprintln!("[server] Error accepting incoming stream: {:?}", err);
return Ok(());
}
}
}
Ok(())
}
#[cfg(feature = "websockets")]
async fn handle_websocket_connection(
&self,
connection: tokio::net::TcpStream,
) -> Result<(), Error> {
use tokio_tungstenite::tungstenite::Message;
let address = connection.peer_addr()?;
let stream = tokio_tungstenite::accept_async(connection).await?;
let (mut sender, mut receiver) = stream.split();
let (response_sender, response_receiver) = flume::unbounded();
let (message_sender, message_receiver) = flume::unbounded();
let (api_response_sender, api_response_receiver) = flume::unbounded();
let client = if let Some(client) = self
.initialize_client(Transport::WebSocket, address, api_response_sender)
.await
{
client
} else {
return Ok(());
};
let task_sender = response_sender.clone();
tokio::spawn(async move {
while let Ok(response) = api_response_receiver.recv_async().await {
if task_sender
.send(Payload {
id: None,
wrapped: Response::Api(response),
})
.is_err()
{
break;
}
}
});
tokio::spawn(async move {
while let Ok(response) = message_receiver.recv_async().await {
sender.send(response).await?;
}
Result::<(), anyhow::Error>::Ok(())
});
let task_sender = message_sender.clone();
tokio::spawn(async move {
while let Ok(response) = response_receiver.recv_async().await {
if task_sender
.send(Message::Binary(bincode::serialize(&response)?))
.is_err()
{
break;
}
}
Result::<(), anyhow::Error>::Ok(())
});
let (request_sender, request_receiver) =
flume::bounded::<Payload<Request<<B::CustomApi as CustomApi>::Request>>>(
self.data.client_simultaneous_request_limit,
);
let task_self = self.clone();
tokio::spawn(async move {
task_self
.handle_client_requests(client.clone(), request_receiver, response_sender)
.await;
});
while let Some(payload) = receiver.next().await {
match payload? {
Message::Binary(binary) => {
let payload = bincode::deserialize::<
Payload<Request<<B::CustomApi as CustomApi>::Request>>,
>(&binary)?;
drop(request_sender.send_async(payload).await);
}
Message::Close(_) => break,
Message::Ping(payload) => {
drop(message_sender.send(Message::Pong(payload)));
}
other => {
eprintln!("[server] unexpected message: {:?}", other);
}
}
}
Ok(())
}
async fn handle_client_requests(
&self,
client: ConnectedClient<B>,
request_receiver: flume::Receiver<Payload<Request<<B::CustomApi as CustomApi>::Request>>>,
response_sender: flume::Sender<Payload<Response<<B::CustomApi as CustomApi>::Response>>>,
) {
let (request_completion_sender, request_completion_receiver) = flume::unbounded::<()>();
let requests_in_queue = Arc::new(AtomicUsize::new(0));
loop {
let current_requests = requests_in_queue.load(Ordering::SeqCst);
if current_requests == self.data.client_simultaneous_request_limit {
// Wait for requests to finish.
let _ = request_completion_receiver.recv_async().await;
// Clear the queue
while request_completion_receiver.try_recv().is_ok() {}
} else if requests_in_queue
.compare_exchange(
current_requests,
current_requests + 1,
Ordering::SeqCst,
Ordering::SeqCst,
)
.is_ok()
{
let payload = match request_receiver.recv_async().await {
Ok(payload) => payload,
Err(_) => break,
};
let id = payload.id;
let task_sender = response_sender.clone();
let request_completion_sender = request_completion_sender.clone();
let requests_in_queue = requests_in_queue.clone();
self.handle_request_through_worker(
payload.wrapped,
move |response| async move {
drop(task_sender.send(Payload {
id,
wrapped: response,
}));
requests_in_queue.fetch_sub(1, Ordering::SeqCst);
let _ = request_completion_sender.send(());
Ok(())
},
client.clone(),
#[cfg(feature = "pubsub")]
self.data.subscribers.clone(),
#[cfg(feature = "pubsub")]
response_sender.clone(),
)
.await
.unwrap();
}
}
}
async fn handle_request_through_worker<
F: FnOnce(Response<<B::CustomApi as CustomApi>::Response>) -> R + Send + 'static,
R: Future<Output = Result<(), Error>> + Send,
>(
&self,
request: Request<<B::CustomApi as CustomApi>::Request>,
callback: F,
client: ConnectedClient<B>,
#[cfg(feature = "pubsub")] subscribers: Arc<RwLock<HashMap<u64, Subscriber>>>,
#[cfg(feature = "pubsub")] response_sender: flume::Sender<
Payload<Response<<B::CustomApi as CustomApi>::Response>>,
>,
) -> Result<(), Error> {
let job = self
.data
.request_processor
.enqueue(ClientRequest::<B>::new(
request,
self.clone(),
client,
#[cfg(feature = "pubsub")]
subscribers,
#[cfg(feature = "pubsub")]
response_sender,
))
.await;
tokio::spawn(async move {
let result = job
.receive()
.await
.map_err(|_| Error::Request(Arc::new(anyhow::anyhow!("background job aborted"))))?
.map_err(Error::Request)?;
callback(result).await?;
Result::<(), Error>::Ok(())
});
Ok(())
}
async fn handle_stream(
&self,
client: OwnedClient<B>,
sender: fabruic::Sender<Payload<Response<<B::CustomApi as CustomApi>::Response>>>,
mut receiver: fabruic::Receiver<Payload<Request<<B::CustomApi as CustomApi>::Request>>>,
) -> Result<(), Error> {
let (payload_sender, payload_receiver) = flume::unbounded();
tokio::spawn(async move {
while let Ok(payload) = payload_receiver.recv_async().await {
if sender.send(&payload).is_err() {
break;
}
}
});
let (request_sender, request_receiver) =
flume::bounded::<Payload<Request<<B::CustomApi as CustomApi>::Request>>>(
self.data.client_simultaneous_request_limit,
);
let task_self = self.clone();
tokio::spawn(async move {
task_self
.handle_client_requests(client.clone(), request_receiver, payload_sender)
.await;
});
while let Some(payload) = receiver.next().await {
drop(request_sender.send_async(payload?).await);
}
Ok(())
}
#[cfg(feature = "pubsub")]
async fn forward_notifications_for(
&self,
subscriber_id: u64,
receiver: flume::Receiver<Arc<Message>>,
sender: flume::Sender<Payload<Response<<B::CustomApi as CustomApi>::Response>>>,
) {
while let Ok(message) = receiver.recv_async().await {
if sender
.send(Payload {
id: None,
wrapped: Response::Database(DatabaseResponse::MessageReceived {
subscriber_id,
topic: message.topic.clone(),
payload: message.payload.clone(),
}),
})
.is_err()
{
break;
}
}
}
/// Shuts the server down. If a `timeout` is provided, the server will stop
/// accepting new connections and attempt to respond to any outstanding
/// requests already being processed. After the `timeout` has elapsed or if
/// no `timeout` was provided, the server is forcefully shut down.
pub async fn shutdown(&self, timeout: Option<Duration>) -> Result<(), Error> {
let endpoint = {
let endpoint = self.data.endpoint.read().await;
endpoint.clone()
};
if let Some(server) = endpoint {
if let Some(timeout) = timeout {
server.close_incoming().await?;
if tokio::time::timeout(timeout, server.wait_idle())
.await
.is_err()
{
server.close().await;
}
} else {
server.close().await;
}
}
Ok(())
}
#[cfg(feature = "pubsub")]
async fn publish_message(&self, database: &str, topic: &str, payload: Vec<u8>) {
self.data
.relay
.publish_message(Message {
topic: database_topic(database, topic),
payload,
})
.await;
}
#[cfg(feature = "pubsub")]
async fn publish_serialized_to_all(&self, database: &str, topics: &[String], payload: Vec<u8>) {
self.data
.relay
.publish_serialized_to_all(
topics
.iter()
.map(|topic| database_topic(database, topic))
.collect(),
payload,
)
.await;
}
#[cfg(feature = "pubsub")]
async fn create_subscriber(&self, database: String) -> ServerSubscriber<B> {
let subscriber = self.data.relay.create_subscriber().await;
let mut subscribers = self.data.subscribers.write().await;
let subscriber_id = subscriber.id();
let receiver = subscriber.receiver().clone();
subscribers.insert(subscriber_id, subscriber);
ServerSubscriber {
server: self.clone(),
database,
receiver,
id: subscriber_id,
}
}
#[cfg(feature = "pubsub")]
async fn subscribe_to<S: Into<String> + Send>(
&self,
subscriber_id: u64,
database: &str,
topic: S,
) -> Result<(), bonsaidb_core::Error> {
let subscribers = self.data.subscribers.read().await;
if let Some(subscriber) = subscribers.get(&subscriber_id) {
subscriber
.subscribe_to(database_topic(database, &topic.into()))
.await;
Ok(())
} else {
Err(bonsaidb_core::Error::Server(String::from(
"invalid subscriber id",
)))
}
}
#[cfg(feature = "pubsub")]
async fn unsubscribe_from(
&self,
subscriber_id: u64,
database: &str,
topic: &str,
) -> Result<(), bonsaidb_core::Error> {
let subscribers = self.data.subscribers.read().await;
if let Some(subscriber) = subscribers.get(&subscriber_id) {
subscriber
.unsubscribe_from(&database_topic(database, topic))
.await;
Ok(())
} else {
Err(bonsaidb_core::Error::Server(String::from(
"invalid subscriber id",
)))
}
}
}
impl<B: Backend> Deref for CustomServer<B> {
type Target = Storage;
fn deref(&self) -> &Self::Target {
&self.data.storage
}
}
#[derive(Debug)]
struct ClientRequest<B: Backend> {
request: Option<Request<<B::CustomApi as CustomApi>::Request>>,
client: ConnectedClient<B>,
server: CustomServer<B>,
#[cfg(feature = "pubsub")]
subscribers: Arc<RwLock<HashMap<u64, Subscriber>>>,
#[cfg(feature = "pubsub")]
sender: flume::Sender<Payload<Response<<B::CustomApi as CustomApi>::Response>>>,
}
impl<B: Backend> ClientRequest<B> {
pub fn new(
request: Request<<B::CustomApi as CustomApi>::Request>,
server: CustomServer<B>,
client: ConnectedClient<B>,
#[cfg(feature = "pubsub")] subscribers: Arc<RwLock<HashMap<u64, Subscriber>>>,
#[cfg(feature = "pubsub")] sender: flume::Sender<
Payload<Response<<B::CustomApi as CustomApi>::Response>>,
>,
) -> Self {
Self {
request: Some(request),
server,
client,
#[cfg(feature = "pubsub")]
subscribers,
#[cfg(feature = "pubsub")]
sender,
}
}
}
#[async_trait]
impl<B: Backend> Job for ClientRequest<B> {
type Output = Response<<B::CustomApi as CustomApi>::Response>;
async fn execute(&mut self) -> anyhow::Result<Self::Output> {
let request = self.request.take().unwrap();
Ok(ServerDispatcher {
server: &self.server,
client: &self.client,
#[cfg(feature = "pubsub")]
subscribers: &self.subscribers,
#[cfg(feature = "pubsub")]
response_sender: &self.sender,
}
.dispatch(&self.client.permissions().await, request)
.await
.unwrap_or_else(Response::Error))
}
}
#[async_trait]
impl<B: Backend> ServerConnection for CustomServer<B> {
async fn create_database_with_schema(
&self,
name: &str,
schema: SchemaName,
) -> Result<(), bonsaidb_core::Error> {
self.data
.storage
.create_database_with_schema(name, schema)
.await
}
async fn delete_database(&self, name: &str) -> Result<(), bonsaidb_core::Error> {
self.data.storage.delete_database(name).await
}
async fn list_databases(&self) -> Result<Vec<connection::Database>, bonsaidb_core::Error> {
self.data.storage.list_databases().await
}
async fn list_available_schemas(&self) -> Result<Vec<SchemaName>, bonsaidb_core::Error> {
self.data.storage.list_available_schemas().await
}
async fn create_user(&self, username: &str) -> Result<u64, bonsaidb_core::Error> {
self.data.storage.create_user(username).await
}
async fn set_user_password<'user, U: Into<NamedReference<'user>> + Send + Sync>(
&self,
user: U,
password_request: RegistrationRequest,
) -> Result<bonsaidb_core::custodian_password::RegistrationResponse, bonsaidb_core::Error> {
self.data
.storage
.set_user_password(user, password_request)
.await
}
async fn finish_set_user_password<'user, U: Into<NamedReference<'user>> + Send + Sync>(
&self,
user: U,
password_finalization: RegistrationFinalization,
) -> Result<(), bonsaidb_core::Error> {
self.data
.storage
.finish_set_user_password(user, password_finalization)
.await
}
async fn add_permission_group_to_user<
'user,
'group,
U: Into<NamedReference<'user>> + Send + Sync,
G: Into<NamedReference<'group>> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), bonsaidb_core::Error> {
self.data
.storage
.add_permission_group_to_user(user, permission_group)
.await
}
async fn remove_permission_group_from_user<
'user,
'group,
U: Into<NamedReference<'user>> + Send + Sync,
G: Into<NamedReference<'group>> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), bonsaidb_core::Error> {
self.data
.storage
.remove_permission_group_from_user(user, permission_group)
.await
}
async fn add_role_to_user<
'user,
'group,
U: Into<NamedReference<'user>> + Send + Sync,
G: Into<NamedReference<'group>> + Send + Sync,
>(
&self,
user: U,
role: G,
) -> Result<(), bonsaidb_core::Error> {
self.data.storage.add_role_to_user(user, role).await
}
async fn remove_role_from_user<
'user,
'group,
U: Into<NamedReference<'user>> + Send + Sync,
G: Into<NamedReference<'group>> + Send + Sync,
>(
&self,
user: U,
role: G,
) -> Result<(), bonsaidb_core::Error> {
self.data.storage.remove_role_from_user(user, role).await
}
}
#[derive(Dispatcher, Debug)]
#[dispatcher(input = Request<<B::CustomApi as CustomApi>::Request>, input = ServerRequest)]
struct ServerDispatcher<'s, B: Backend> {
server: &'s CustomServer<B>,
client: &'s ConnectedClient<B>,
#[cfg(feature = "pubsub")]
subscribers: &'s Arc<RwLock<HashMap<u64, Subscriber>>>,
#[cfg(feature = "pubsub")]
response_sender: &'s flume::Sender<Payload<Response<<B::CustomApi as CustomApi>::Response>>>,
}
#[async_trait]
impl<'s, B: Backend> RequestDispatcher for ServerDispatcher<'s, B> {
type Subaction = <B::CustomApi as CustomApi>::Request;
type Output = Response<<B::CustomApi as CustomApi>::Response>;
type Error = bonsaidb_core::Error;
async fn handle_subaction(
&self,
permissions: &Permissions,
subaction: Self::Subaction,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
let dispatcher = B::dispatcher_for(self.server, self.client);
dispatcher
.dispatch(permissions, subaction)
.await
.map(Response::Api)
.map_err(|err| {
bonsaidb_core::Error::Server(format!("error executing custom api: {:?}", err))
})
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ServerHandler for ServerDispatcher<'s, B> {
async fn handle(
&self,
permissions: &Permissions,
request: ServerRequest,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
ServerRequestDispatcher::dispatch_to_handlers(self, permissions, request).await
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::DatabaseHandler for ServerDispatcher<'s, B> {
async fn handle(
&self,
permissions: &Permissions,
database_name: String,
request: DatabaseRequest,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
let database = self.server.database_without_schema(&database_name).await?;
DatabaseDispatcher {
name: database_name,
database: database.as_ref(),
server_dispatcher: self,
}
.dispatch(permissions, request)
.await
}
}
impl<'s, B: Backend> ServerRequestDispatcher for ServerDispatcher<'s, B> {
type Output = Response<<B::CustomApi as CustomApi>::Response>;
type Error = bonsaidb_core::Error;
}
#[async_trait]
impl<'s, B: Backend> CreateDatabaseHandler for ServerDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
database: &'a bonsaidb_core::connection::Database,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(database_resource_name(&database.name))
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::CreateDatabase)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
database: bonsaidb_core::connection::Database,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
self.server
.create_database_with_schema(&database.name, database.schema)
.await?;
Ok(Response::Server(ServerResponse::DatabaseCreated {
name: database.name.clone(),
}))
}
}
#[async_trait]
impl<'s, B: Backend> DeleteDatabaseHandler for ServerDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
database: &'a String,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(database_resource_name(database))
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::DeleteDatabase)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
name: String,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
self.server.delete_database(&name).await?;
Ok(Response::Server(ServerResponse::DatabaseDeleted { name }))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ListDatabasesHandler for ServerDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(&'a self) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(bonsaidb_resource_name())
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::ListDatabases)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
Ok(Response::Server(ServerResponse::Databases(
self.server.list_databases().await?,
)))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ListAvailableSchemasHandler
for ServerDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(&'a self) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(bonsaidb_resource_name())
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::ListAvailableSchemas)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
Ok(Response::Server(ServerResponse::AvailableSchemas(
self.server.list_available_schemas().await?,
)))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::CreateUserHandler for ServerDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
_username: &'a String,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(bonsaidb_resource_name())
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::CreateUser)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
username: String,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
Ok(Response::Server(ServerResponse::UserCreated {
id: self.server.create_user(&username).await?,
}))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::LoginWithPasswordHandler
for ServerDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
username: &'a String,
_password_request: &'a LoginRequest,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
let id = NamedReference::from(username.as_str())
.id::<User, _>(&self.server.admin().await)
.await?
.ok_or(bonsaidb_core::Error::UserNotFound)?;
Ok(user_resource_name(id))
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::LoginWithPassword)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
username: String,
password_request: LoginRequest,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
let (user_id, login, response) = self
.server
.internal_login_with_password(&username, password_request)
.await?;
self.client.set_pending_password_login(user_id, login).await;
Ok(Response::Server(ServerResponse::PasswordLoginResponse {
response: Box::new(response),
}))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::FinishPasswordLoginHandler
for ServerDispatcher<'s, B>
{
async fn handle(
&self,
_permissions: &Permissions,
password_request: LoginFinalization,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
if let Some((user_id, login)) = self.client.take_pending_password_login().await {
login.finish(password_request)?;
let user_id = user_id.expect("logged in without a user_id");
let admin = self.server.data.storage.admin().await;
let user = User::get(user_id, &admin)
.await?
.ok_or(bonsaidb_core::Error::UserNotFound)?;
let permissions = user.contents.effective_permissions(&admin).await?;
self.client.logged_in_as(user_id, permissions.clone()).await;
Ok(Response::Server(ServerResponse::LoggedIn { permissions }))
} else {
Err(bonsaidb_core::Error::Server(String::from(
"no login state found",
)))
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::SetPasswordHandler for ServerDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
user: &'a NamedReference<'static>,
_password_request: &'a RegistrationRequest,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
let id = user
.id::<User, _>(&self.server.admin().await)
.await?
.ok_or(bonsaidb_core::Error::UserNotFound)?;
Ok(user_resource_name(id))
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::SetPassword)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
user: NamedReference<'static>,
password_request: RegistrationRequest,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
Ok(Response::Server(ServerResponse::FinishSetPassword {
password_reponse: Box::new(
self.server
.set_user_password(user, password_request)
.await?,
),
}))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::FinishSetPasswordHandler
for ServerDispatcher<'s, B>
{
async fn handle(
&self,
_permissions: &Permissions,
user: NamedReference<'static>,
password_request: RegistrationFinalization,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
self.server
.finish_set_user_password(user, password_request)
.await?;
Ok(Response::Ok)
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::AlterUserPermissionGroupMembershipHandler
for ServerDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
user: &'a NamedReference<'static>,
_group: &'a NamedReference<'static>,
_should_be_member: &'a bool,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
let id = user
.id::<User, _>(&self.server.admin().await)
.await?
.ok_or(bonsaidb_core::Error::UserNotFound)?;
Ok(user_resource_name(id))
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::ModifyUserPermissionGroups)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
user: NamedReference<'static>,
group: NamedReference<'static>,
should_be_member: bool,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
if should_be_member {
self.server
.add_permission_group_to_user(user, group)
.await?;
} else {
self.server
.remove_permission_group_from_user(user, group)
.await?;
}
Ok(Response::Ok)
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::AlterUserRoleMembershipHandler
for ServerDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
user: &'a NamedReference<'static>,
_role: &'a NamedReference<'static>,
_should_be_member: &'a bool,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
let id = user
.id::<User, _>(&self.server.admin().await)
.await?
.ok_or(bonsaidb_core::Error::UserNotFound)?;
Ok(user_resource_name(id))
}
fn action() -> Self::Action {
BonsaiAction::Server(ServerAction::ModifyUserRoles)
}
async fn handle_protected(
&self,
_permissions: &Permissions,
user: NamedReference<'static>,
role: NamedReference<'static>,
should_be_member: bool,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
if should_be_member {
self.server.add_role_to_user(user, role).await?;
} else {
self.server.remove_role_from_user(user, role).await?;
}
Ok(Response::Ok)
}
}
#[derive(Dispatcher, Debug)]
#[dispatcher(input = DatabaseRequest)]
struct DatabaseDispatcher<'s, B>
where
B: Backend,
{
name: String,
database: &'s dyn OpenDatabase,
server_dispatcher: &'s ServerDispatcher<'s, B>,
}
impl<'s, B: Backend> DatabaseRequestDispatcher for DatabaseDispatcher<'s, B> {
type Output = Response<<B::CustomApi as CustomApi>::Response>;
type Error = bonsaidb_core::Error;
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::GetHandler for DatabaseDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
collection: &'a CollectionName,
id: &'a u64,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(document_resource_name(&self.name, collection, *id))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::Document(DocumentAction::Get))
}
async fn handle_protected(
&self,
permissions: &Permissions,
collection: CollectionName,
id: u64,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
let document = self
.database
.get_from_collection_id(id, &collection, permissions)
.await?
.ok_or(Error::Core(bonsaidb_core::Error::DocumentNotFound(
collection, id,
)))?;
Ok(Response::Database(DatabaseResponse::Documents(vec![
document,
])))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::GetMultipleHandler for DatabaseDispatcher<'s, B> {
async fn verify_permissions(
&self,
permissions: &Permissions,
collection: &CollectionName,
ids: &Vec<u64>,
) -> Result<(), bonsaidb_core::Error> {
for &id in ids {
let document_name = document_resource_name(&self.name, collection, id);
let action = BonsaiAction::Database(DatabaseAction::Document(DocumentAction::Get));
if !permissions.allowed_to(&document_name, &action) {
return Err(bonsaidb_core::Error::from(PermissionDenied {
resource: document_name.to_owned(),
action: action.name(),
}));
}
}
Ok(())
}
async fn handle_protected(
&self,
permissions: &Permissions,
collection: CollectionName,
ids: Vec<u64>,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
let documents = self
.database
.get_multiple_from_collection_id(&ids, &collection, permissions)
.await?;
Ok(Response::Database(DatabaseResponse::Documents(documents)))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::QueryHandler for DatabaseDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
view: &'a ViewName,
_key: &'a Option<QueryKey<Vec<u8>>>,
_access_policy: &'a AccessPolicy,
_with_docs: &'a bool,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(view_resource_name(&self.name, view))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::View(ViewAction::Query))
}
async fn handle_protected(
&self,
permissions: &Permissions,
view: ViewName,
key: Option<QueryKey<Vec<u8>>>,
access_policy: AccessPolicy,
with_docs: bool,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
if with_docs {
let mappings = self
.database
.query_with_docs(&view, key, access_policy, permissions)
.await?;
Ok(Response::Database(DatabaseResponse::ViewMappingsWithDocs(
mappings,
)))
} else {
let mappings = self.database.query(&view, key, access_policy).await?;
Ok(Response::Database(DatabaseResponse::ViewMappings(mappings)))
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ReduceHandler for DatabaseDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
view: &'a ViewName,
_key: &'a Option<QueryKey<Vec<u8>>>,
_access_policy: &'a AccessPolicy,
_grouped: &'a bool,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(view_resource_name(&self.name, view))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::View(ViewAction::Reduce))
}
async fn handle_protected(
&self,
_permissions: &Permissions,
view: ViewName,
key: Option<QueryKey<Vec<u8>>>,
access_policy: AccessPolicy,
grouped: bool,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
if grouped {
let values = self
.database
.reduce_grouped(&view, key, access_policy)
.await?;
Ok(Response::Database(DatabaseResponse::ViewGroupedReduction(
values,
)))
} else {
let value = self.database.reduce(&view, key, access_policy).await?;
Ok(Response::Database(DatabaseResponse::ViewReduction(value)))
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ApplyTransactionHandler
for DatabaseDispatcher<'s, B>
{
async fn verify_permissions(
&self,
permissions: &Permissions,
transaction: &Transaction<'static>,
) -> Result<(), bonsaidb_core::Error> {
for op in &transaction.operations {
let (resource, action) = match &op.command {
Command::Insert { .. } => (
collection_resource_name(&self.name, &op.collection),
BonsaiAction::Database(DatabaseAction::Document(DocumentAction::Insert)),
),
Command::Update { header, .. } => (
document_resource_name(&self.name, &op.collection, header.id),
BonsaiAction::Database(DatabaseAction::Document(DocumentAction::Update)),
),
Command::Delete { header } => (
document_resource_name(&self.name, &op.collection, header.id),
BonsaiAction::Database(DatabaseAction::Document(DocumentAction::Delete)),
),
};
if !permissions.allowed_to(&resource, &action) {
return Err(bonsaidb_core::Error::from(PermissionDenied {
resource: resource.to_owned(),
action: action.name(),
}));
}
}
Ok(())
}
async fn handle_protected(
&self,
permissions: &Permissions,
transaction: Transaction<'static>,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
let results = self
.database
.apply_transaction(transaction, permissions)
.await?;
Ok(Response::Database(DatabaseResponse::TransactionResults(
results,
)))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ListExecutedTransactionsHandler
for DatabaseDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
_starting_id: &'a Option<u64>,
_result_limit: &'a Option<usize>,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(database_resource_name(&self.name))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::Transaction(TransactionAction::ListExecuted))
}
async fn handle_protected(
&self,
_permissions: &Permissions,
starting_id: Option<u64>,
result_limit: Option<usize>,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
Ok(Response::Database(DatabaseResponse::ExecutedTransactions(
self.database
.list_executed_transactions(starting_id, result_limit)
.await?,
)))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::LastTransactionIdHandler
for DatabaseDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(&'a self) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(database_resource_name(&self.name))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::Transaction(TransactionAction::GetLastId))
}
async fn handle_protected(
&self,
_permissions: &Permissions,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
Ok(Response::Database(DatabaseResponse::LastTransactionId(
self.database.last_transaction_id().await?,
)))
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::CreateSubscriberHandler
for DatabaseDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(&'a self) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(database_resource_name(&self.name))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::PubSub(PubSubAction::CreateSuscriber))
}
#[cfg_attr(not(feature = "pubsub"), allow(unused_variables))]
async fn handle_protected(
&self,
_permissions: &Permissions,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "pubsub")] {
let server = self.server_dispatcher.server;
let subscriber = server.create_subscriber(self.name.clone()).await;
let subscriber_id = subscriber.id;
let task_self = server.clone();
let response_sender = self.server_dispatcher.response_sender.clone();
tokio::spawn(async move {
task_self
.forward_notifications_for(subscriber.id, subscriber.receiver, response_sender.clone())
.await;
});
Ok(Response::Database(DatabaseResponse::SubscriberCreated {
subscriber_id,
}))
} else {
Err(bonsaidb_core::Error::Server(String::from("pubsub is not enabled on this server")))
}
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::PublishHandler for DatabaseDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
topic: &'a String,
_payload: &'a Vec<u8>,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(pubsub_topic_resource_name(&self.name, topic))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::PubSub(PubSubAction::Publish))
}
#[cfg_attr(not(feature = "pubsub"), allow(unused_variables))]
async fn handle_protected(
&self,
_permissions: &Permissions,
topic: String,
payload: Vec<u8>,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "pubsub")] {
self
.server_dispatcher
.server
.publish_message(&self.name, &topic, payload)
.await;
Ok(Response::Ok)
} else {
Err(bonsaidb_core::Error::Server(String::from("pubsub is not enabled on this server")))
}
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::PublishToAllHandler for DatabaseDispatcher<'s, B> {
async fn verify_permissions(
&self,
permissions: &Permissions,
topics: &Vec<String>,
_payload: &Vec<u8>,
) -> Result<(), bonsaidb_core::Error> {
for topic in topics {
let topic_name = pubsub_topic_resource_name(&self.name, topic);
let action = BonsaiAction::Database(DatabaseAction::PubSub(PubSubAction::Publish));
if !permissions.allowed_to(&topic_name, &action) {
return Err(bonsaidb_core::Error::from(PermissionDenied {
resource: topic_name.to_owned(),
action: action.name(),
}));
}
}
Ok(())
}
#[cfg_attr(not(feature = "pubsub"), allow(unused_variables))]
async fn handle_protected(
&self,
_permissions: &Permissions,
topics: Vec<String>,
payload: Vec<u8>,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "pubsub")] {
self
.server_dispatcher
.server
.publish_serialized_to_all(
&self.name,
&topics,
payload,
)
.await;
Ok(Response::Ok)
} else {
Err(bonsaidb_core::Error::Server(String::from("pubsub is not enabled on this server")))
}
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::SubscribeToHandler for DatabaseDispatcher<'s, B> {
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
_subscriber_id: &'a u64,
topic: &'a String,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(pubsub_topic_resource_name(&self.name, topic))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::PubSub(PubSubAction::SubscribeTo))
}
#[cfg_attr(not(feature = "pubsub"), allow(unused_variables))]
async fn handle_protected(
&self,
_permissions: &Permissions,
subscriber_id: u64,
topic: String,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "pubsub")] {
self.server_dispatcher.server.subscribe_to(subscriber_id, &self.name, topic).await.map(|_| Response::Ok)
} else {
Err(bonsaidb_core::Error::Server(String::from("pubsub is not enabled on this server")))
}
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::UnsubscribeFromHandler
for DatabaseDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
_subscriber_id: &'a u64,
topic: &'a String,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(pubsub_topic_resource_name(&self.name, topic))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::PubSub(PubSubAction::UnsubscribeFrom))
}
#[cfg_attr(not(feature = "pubsub"), allow(unused_variables))]
async fn handle_protected(
&self,
_permissions: &Permissions,
subscriber_id: u64,
topic: String,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "pubsub")] {
self.server_dispatcher.server.unsubscribe_from(subscriber_id, &self.name, &topic).await.map(|_| Response::Ok)
} else {
Err(bonsaidb_core::Error::Server(String::from("pubsub is not enabled on this server")))
}
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::UnregisterSubscriberHandler
for DatabaseDispatcher<'s, B>
{
#[cfg_attr(not(feature = "pubsub"), allow(unused_variables))]
async fn handle(
&self,
_permissions: &Permissions,
subscriber_id: u64,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "pubsub")] {
let mut subscribers = self.server_dispatcher.subscribers.write().await;
if subscribers.remove(&subscriber_id).is_none() {
Ok(Response::Error(bonsaidb_core::Error::Server(String::from(
"invalid subscriber id",
))))
} else {
Ok(Response::Ok)
}
} else {
Err(bonsaidb_core::Error::Server(String::from("pubsub is not enabled on this server")))
}
}
}
}
#[async_trait]
impl<'s, B: Backend> bonsaidb_core::networking::ExecuteKeyOperationHandler
for DatabaseDispatcher<'s, B>
{
type Action = BonsaiAction;
async fn resource_name<'a>(
&'a self,
op: &'a KeyOperation,
) -> Result<ResourceName<'a>, bonsaidb_core::Error> {
Ok(kv_key_resource_name(
&self.name,
op.namespace.as_deref(),
&op.key,
))
}
fn action() -> Self::Action {
BonsaiAction::Database(DatabaseAction::Kv(KvAction::ExecuteOperation))
}
#[cfg_attr(not(feature = "keyvalue"), allow(unused_variables))]
async fn handle_protected(
&self,
_permissions: &Permissions,
op: KeyOperation,
) -> Result<Response<<B::CustomApi as CustomApi>::Response>, bonsaidb_core::Error> {
cfg_if! {
if #[cfg(feature = "keyvalue")] {
let result = self.database.execute_key_operation(op).await?;
Ok(Response::Database(DatabaseResponse::KvOutput(result)))
} else {
Err(bonsaidb_core::Error::Server(String::from("keyvalue is not enabled on this server")))
}
}
}
}
|
#![allow(non_snake_case)]
extern crate sfml;
use crate::cpu::{Z80, Flags, UNPREFIXED_INSTRUCTION_TABLE, PREFIXED_INSTRUCTION_TABLE};
use sfml::{
graphics::{
Text, RenderTarget, RenderWindow, Color, Font, Transformable
},
};
const CHAR_SIZE: u32 = 14;
pub fn showRam(c: &Z80, startIndex: u16, nRows: u16, nCols: u16) -> String {
let mut nStr = String::new();
let mut n: u16 = 0;
for _i in 0..nRows {
let addr = startIndex + n;
nStr.push_str(&format!("{:#06X}:\t", addr));
for j in 0..nCols {
nStr.push_str(&format!("{:02x} ", c.readByte(addr + (j as u16))));
n += 1;
}
nStr.push('\n');
}
return nStr;
}
pub fn showRegisters(c: &Z80) -> String {
let mut nStr = String::new();
let mut nStr2 = String::new();
nStr.push_str(&format!("A: {:02X} ", c.a));
nStr2.push_str(&format!("F: {:02X} ", c.f));
nStr.push_str(&format!("B: {:02X} ", c.b));
nStr2.push_str(&format!("C: {:02X} ", c.c));
nStr.push_str(&format!("D: {:02X} ", c.d));
nStr2.push_str(&format!("E: {:02X} ", c.e));
nStr.push_str(&format!("H: {:02X} ", c.h));
nStr2.push_str(&format!("L: {:02X} ", c.l));
nStr.push_str(&format!("SP: {:02X} ", c.sp));
nStr2.push_str(&format!("PC: {:02X} ", c.pc));
nStr.push('\n');
nStr.push_str(&nStr2);
return nStr;
}
pub fn showCode(c: &Z80, startIndex: u16, nInstructions: u16) -> String{
let mut nStr = String::new();
let mut addr = startIndex;
let mut prefixed = false;
let mut opcodeLen = 0;
for _i in 0..nInstructions {
addr += opcodeLen;
nStr.push_str(&format!("{:#06X}\t", addr));
let (name, length, cycles) = if prefixed {PREFIXED_INSTRUCTION_TABLE[c.readByte(addr) as usize]} else {UNPREFIXED_INSTRUCTION_TABLE[c.readByte(addr) as usize]};
if name == "CB" && !prefixed {
prefixed = true;
} else {
prefixed = false;
}
match length {
3 => {nStr.push_str(&format!("{} #{:#06X} [{}]", name, c.readBytes(addr + 1), cycles))},
2 => {nStr.push_str(&format!("{} #{:#04X}[{}]", name, c.readByte(addr + 1), cycles))},
_ => {nStr.push_str(&format!("{} [{}]", name, cycles))},
}
opcodeLen = length as u16;
nStr.push('\n');
}
return nStr;
}
pub fn showTimers(c: &Z80) -> String {
let mut nStr = String::new();
nStr.push_str(&format!("DIV [{:b}]\n", c.bus.timerRegisters.divRegister));
nStr.push_str(&format!("TIMA [{:b}]\n", c.bus.timerRegisters.timaRegister));
nStr.push_str(&format!("TMA [{:b}]\n", c.bus.timerRegisters.tmaRegister));
nStr.push_str(&format!("TAC [{:b}]\n", c.bus.timerRegisters.tacRegister));
nStr
}
pub fn renderFullDissassembly(c: &Z80, ramPage1: u16, ramPage2: u16, f: &Font, w: &mut RenderWindow) {
let mut ramText = Text::default();
ramText.set_font(f);
ramText.set_string(&showRam(c, ramPage1, 9, 12));
ramText.set_character_size(CHAR_SIZE * 2);
ramText.set_fill_color(Color::WHITE);
let mut ramText2 = Text::default();
ramText2.set_font(f);
ramText2.set_string(&showRam(c, ramPage2, 9, 12));
ramText2.set_character_size(CHAR_SIZE * 2);
ramText2.set_fill_color(Color::WHITE);
ramText2.set_position((ramText.position().x, ramText.local_bounds().height + 20.0));
let mut tArr: [Text; 8] = [
Text::new("Z ", f, CHAR_SIZE * 2),
Text::new("N ", f, CHAR_SIZE * 2),
Text::new("HC ", f, CHAR_SIZE * 2),
Text::new("C ", f, CHAR_SIZE * 2),
Text::new("0 ", f, CHAR_SIZE * 2),
Text::new("0 ", f, CHAR_SIZE * 2),
Text::new("0 ", f, CHAR_SIZE * 2),
Text::new("0", f, CHAR_SIZE * 2),
];
if c.getFlag(Flags::Zero) {tArr[0].set_fill_color(Color::GREEN)} else {tArr[0].set_fill_color(Color::RED)};
if c.getFlag(Flags::Sub) {tArr[1].set_fill_color(Color::GREEN)} else {tArr[1].set_fill_color(Color::RED)};
if c.getFlag(Flags::HCarry) {tArr[2].set_fill_color(Color::GREEN)} else {tArr[2].set_fill_color(Color::RED)};
if c.getFlag(Flags::Carry) {tArr[3].set_fill_color(Color::GREEN)} else {tArr[3].set_fill_color(Color::RED)};
tArr[0].set_position((ramText.local_bounds().width + 20.0, ramText.position().y));
for i in 1..tArr.len() {
tArr[i].set_position((tArr[i - 1].local_bounds().width + tArr[i - 1].position().x, tArr[i - 1].position().y));
}
let mut registerText = Text::default();
registerText.set_font(f);
registerText.set_string(&showRegisters(c));
registerText.set_character_size(CHAR_SIZE + 6);
registerText.set_fill_color(Color::WHITE);
registerText.set_position((tArr[0].position().x, tArr[0].local_bounds().height + 20.0));
let mut timerText = Text::default();
timerText.set_font(f);
timerText.set_string(&showTimers(c));
timerText.set_fill_color(Color::WHITE);
timerText.set_character_size(CHAR_SIZE + 6);
timerText.set_position((registerText.position().x, registerText.local_bounds().height + registerText.position().y + 20.0));
let mut codeText = Text::default();
codeText.set_font(f);
codeText.set_string(&showCode(c, c.pc, 15));
codeText.set_character_size(CHAR_SIZE);
codeText.set_fill_color(Color::WHITE);
codeText.set_position((timerText.position().x, timerText.local_bounds().height + timerText.position().y + 20.0));
/*
let mut registerBinaryText = Text::default();
registerBinaryText.set_font(f);
registerBinaryText.set_string(&showRegistersBinary(c));
registerBinaryText.set_character_size(CHAR_SIZE);
registerBinaryText.set_fill_color(Color::WHITE);
registerBinaryText.set_position((codeText.position().x + codeText.local_bounds().width + 20.0, codeText.position().y));
*/
w.draw(&ramText);
w.draw(&ramText2);
for e in tArr.iter() {
w.draw(e);
}
w.draw(®isterText);
w.draw(&timerText);
w.draw(&codeText);
//w.draw(®isterBinaryText);
} |
// cargo-deps: chrono
extern crate chrono;
fn main() {
println!("--output--");
println!("Hello");
} |
use std::path::Path;
extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::Canvas;
use sdl2::render::TextureQuery;
use sdl2::ttf::{Font, Sdl2TtfContext};
use sdl2::video::Window;
use sdl2::Sdl;
const PADDING: u32 = 64;
pub struct Screen<'a> {
pub canvas: Canvas<Window>,
font: Font<'a, 'static>,
top_left: Rect,
top_right: Rect,
}
impl<'a> Screen<'a> {
const SCREEN_WIDTH: u32 = 800;
const SCREEN_HEIGHT: u32 = 800;
const BACKGROUND_COLOR: Color = Color {
r: 0,
g: 0,
b: 0,
a: 255,
};
const TEXT_COL: Color = Color {
r: 255,
g: 255,
b: 0,
a: 255,
};
pub fn new(sdl_context: &Sdl, ttf_context: &'a Sdl2TtfContext, font_path: &str) -> Self {
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem
.window("asteroids", Self::SCREEN_WIDTH, Self::SCREEN_HEIGHT)
.position_centered()
.build()
.unwrap();
let mut font = ttf_context.load_font(Path::new(font_path), 128).unwrap();
font.set_style(sdl2::ttf::STYLE_BOLD);
Screen {
font,
top_left: Rect::new(10, 10, 100, 20),
top_right: Rect::new(690, 10, 100, 20),
canvas: window.into_canvas().build().unwrap(),
}
}
pub fn draw_background(&mut self) {
self.canvas.set_draw_color(Self::BACKGROUND_COLOR);
self.canvas.clear();
}
pub fn draw_health(&mut self, health: u32) {
let rect = self.top_left;
self.text_in_rect(&format!("health: {:?}", health), rect);
}
pub fn draw_level(&mut self, level: u32) {
let rect = self.top_right;
self.text_in_rect(&format!("Level: {:?}", level), rect);
}
fn text_in_rect(&mut self, text: &str, rect: Rect) {
let texture_creator = self.canvas.texture_creator();
let surface = self.font.render(text).blended(Self::TEXT_COL).unwrap();
let texture = texture_creator
.create_texture_from_surface(&surface)
.unwrap();
self.canvas.copy(&texture, None, Some(rect)).unwrap();
}
pub fn draw_big_centered(&mut self, text: &str) {
let surface = self
.font
.render(text)
.blended(Color::RGB(255, 0, 0))
.unwrap();
let texture_creator = self.canvas.texture_creator();
let texture = texture_creator
.create_texture_from_surface(&surface)
.unwrap();
let TextureQuery { width, height, .. } = texture.query();
let target = get_centered_rect(width, height, self.canvas.viewport(), PADDING);
self.canvas.copy(&texture, None, Some(target)).unwrap();
}
}
fn get_centered_rect(rect_width: u32, rect_height: u32, frame: Rect, padding: u32) -> Rect {
let (screen_width, screen_height) = frame.size() as (u32, u32);
let cons_width = screen_width - padding;
let cons_height = screen_height - padding;
let wr = rect_width as f32 / cons_width as f32;
let hr = rect_height as f32 / cons_height as f32;
let (w, h) = if wr > 1f32 || hr > 1f32 {
if wr > hr {
let h = (rect_height as f32 / wr) as i32;
(cons_width as i32, h)
} else {
let w = (rect_width as f32 / hr) as i32;
(w, cons_height as i32)
}
} else {
(rect_width as i32, rect_height as i32)
};
let cx = (screen_width as i32 - w) / 2;
let cy = (screen_height as i32 - h) / 2;
Rect::new(cx as i32, cy as i32, w as u32, h as u32)
}
|
use crate::{
error::SendDuccError,
util::{
get_time_ms,
JsEngine,
},
Nonce,
};
use url::Url;
#[derive(Debug)]
pub enum QuizError {
Ducc(SendDuccError),
QuizAnswer(QuizAnswerError),
}
impl From<ducc::Error> for QuizError {
fn from(e: ducc::Error) -> Self {
Self::Ducc(SendDuccError::from_ducc_error_lossy(e))
}
}
impl From<QuizAnswerError> for QuizError {
fn from(e: QuizAnswerError) -> Self {
Self::QuizAnswer(e)
}
}
#[derive(Debug, Clone)]
pub struct Quiz {
id: u32,
answers: Vec<QuizAnswer>,
hash: String,
closed: bool,
referer: String,
va: String, // I don't know what this is but i need it
}
impl Quiz {
pub fn from_script_data(referer: String, id: u32, data: &str) -> Result<Self, QuizError> {
let vm = JsEngine::new()?;
vm.exec(data)?;
let hash = vm.get_global(format!("PDV_h{}", id))?;
let closed = vm.get_global(format!("pollClosed{}", id))?;
let va = vm.get_global(format!("PDV_va{}", id))?;
let answers = vm
.get_global::<_, Vec<Vec<String>>>(format!("PDV_A{}", id))?
.iter()
.map(|a| QuizAnswer::from_string_array(a))
.collect::<Result<Vec<_>, _>>()?;
Ok(Quiz {
id,
answers,
hash,
closed,
referer,
va,
})
}
pub fn get_code_url(&self) -> Result<Url, url::ParseError> {
let url_str = format!(
"https://polldaddy.com/n/{hash}/{id}?{time}",
hash = self.hash,
id = self.id,
time = get_time_ms()
);
Url::parse(&url_str)
}
pub fn get_vote_url(&self, answer: u32, nonce: &Nonce) -> Result<Url, url::ParseError> {
let url_str = format!(
"https://polls.polldaddy.com/vote-js.php?p={id}&b=1&a={answer},&o=&va={va}&cookie=0&n={nonce}&url={referer}",
id = self.id, answer = answer, va = self.va, nonce = nonce.as_str(), referer = self.referer
);
Url::parse(&url_str)
}
pub fn get_id(&self) -> u32 {
self.id
}
pub fn get_hash(&self) -> &str {
&self.hash
}
pub fn is_closed(&self) -> bool {
self.closed
}
pub fn get_referer(&self) -> &str {
&self.referer
}
pub fn get_answers(&self) -> &[QuizAnswer] {
&self.answers
}
pub fn get_va(&self) -> &str {
&self.va
}
}
#[derive(Debug, Clone)]
pub enum QuizAnswerError {
MissingString(usize),
BadIdParse(std::num::ParseIntError),
}
#[derive(Debug, Clone)]
pub struct QuizAnswer {
id: u32,
text: String,
}
impl QuizAnswer {
fn from_string_array(arr: &[String]) -> Result<Self, QuizAnswerError> {
let mut iter = arr.iter();
Ok(QuizAnswer {
id: iter
.next()
.ok_or(QuizAnswerError::MissingString(0))?
.parse()
.map_err(QuizAnswerError::BadIdParse)?,
text: String::from(iter.next().ok_or(QuizAnswerError::MissingString(1))?),
})
}
pub fn get_id(&self) -> u32 {
self.id
}
pub fn get_text(&self) -> &str {
&self.text
}
}
|
pub mod entry;
pub mod file;
pub mod item;
pub use entry::{Entry, Status};
pub use file::Dotfile;
pub use item::Item;
|
#[macro_use]
extern crate serde_derive;
use azure_storage::table::{Batch, CloudTable, TableClient};
use std::error::Error;
use std::mem;
#[derive(Debug, Serialize, Deserialize)]
struct MyEntity {
data: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!");
let client = TableClient::new(&account, &master_key);
let cloud_table = CloudTable::new(client, "test");
cloud_table.create_if_not_exists().await?;
let entity = cloud_table.get::<MyEntity>("pk", "rk", None).await?;
println!("entity: {:?}", entity);
let cnt = 20usize;
let mut batch = Batch::new("big2".to_owned());
for r in 0usize..cnt {
batch.add_insert(
format!("rk-{}", r),
&MyEntity {
data: "hello".to_owned(),
},
)?;
if batch.is_full() {
println!("batch insert {}", r);
let batch = mem::replace(&mut batch, Batch::new("big2".to_owned()));
cloud_table.execute_batch(batch).await?;
}
}
if !batch.is_empty() {
println!("batch insert last part");
cloud_table.execute_batch(batch).await?;
}
let entity = cloud_table
.get::<serde_json::Value>("big2", "0", None)
.await?;
println!("entity(value): {:?}", entity);
let mut response = cloud_table.begin_get_all::<MyEntity>().await?;
while let Some(continuation_token) = response.continuation_token {
response = cloud_table.continue_execution(continuation_token).await?;
println!("segment: {:?}", response.entities.first());
}
let mut response = cloud_table.begin_get_all::<serde_json::Value>().await?;
while let Some(continuation_token) = response.continuation_token {
response = cloud_table.continue_execution(continuation_token).await?;
println!("segment: {:?}", response.entities.first());
}
let mut batch = Batch::new("big2".to_owned());
for r in 0usize..cnt {
if r % 2 == 0 {
batch.add_delete(format!("rk-{}", r), None)?;
} else {
batch.add_update(
format!("rk-{}", r),
&MyEntity {
data: "updated".to_owned(),
},
None,
)?;
}
if batch.is_full() {
println!("batch delete/update {}", r);
let batch = mem::replace(&mut batch, Batch::new("big2".to_owned()));
cloud_table.execute_batch(batch).await?;
}
}
if !batch.is_empty() {
println!("batch delete/update last part");
cloud_table.execute_batch(batch).await?;
}
Ok(())
}
|
use std::io;
use aoc2020;
fn main() {
aoc2020::run(25);
loop {
println!("Enter input: ");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read input");
let input : Vec<&str> = input.split_ascii_whitespace().collect();
if input.len() == 1 {
if let Ok(day) = input[0].trim().parse() {
aoc2020::run(day)
} else {
break
}
} else if input.len() > 1 {
if input[0].contains("benchmark") {
if let Ok(day) = input[1].trim().parse() {
if input.len() == 3 {
if let Ok(iter) = input[2].trim().parse() {
aoc2020::benchmark(day, iter)
} else {
aoc2020::benchmark(day, 500)
}
} else {
aoc2020::benchmark(day, 500);
}
} else {
break
}
}
} else {
break
}
}
}
|
//! Common IO primitives.
//!
//! These primitives are closely mirroring the definitions in
//! [`tokio-io`](https://docs.rs/tokio-io). A big difference is that these definitions are not tied
//! to `std::io::Error`, but instead allow for custom error types, and also don't require
//! allocation.
use core::fmt;
use core::pin;
use core::task;
pub mod flush;
pub mod read;
pub mod read_exact;
pub mod shutdown;
pub mod write;
pub mod write_all;
/// Reads bytes from a source.
pub trait Read: fmt::Debug {
/// The type of error that can occur during a read operation.
type Error: ReadError;
/// Attempts to read into the provided buffer.
///
/// On success, returns the number of bytes read.
fn poll_read(
self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
buffer: &mut [u8],
) -> task::Poll<Result<usize, Self::Error>>;
}
/// An error that might arise from read operations.
pub trait ReadError: fmt::Debug {
/// Creates an error that indicates an EOF (end-of-file) condition.
///
/// This condition is to be used when there is not enough data available to satisfy a read
/// operation.
fn eof() -> Self;
}
/// Writes bytes to a source.
pub trait Write: fmt::Debug {
/// The type of error that can occur during a write operation.
type Error: WriteError;
/// Attempts to write the contents of the provided buffer.
///
/// On success, returns the number of bytes written.
fn poll_write(
self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
bytes: &[u8],
) -> task::Poll<Result<usize, Self::Error>>;
/// Attempts to flush the object, ensuring that any buffered data reach their destination.
fn poll_flush(
self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
) -> task::Poll<Result<(), Self::Error>>;
/// Initiates or attempts to shut down this writer, returning success when the I/O connection
/// has completely shut down.
fn poll_shutdown(
self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
) -> task::Poll<Result<(), Self::Error>>;
}
impl<A: ?Sized + Write + Unpin> Write for &mut A {
type Error = A::Error;
fn poll_write(
mut self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
bytes: &[u8],
) -> task::Poll<Result<usize, Self::Error>> {
pin::Pin::new(&mut **self).poll_write(cx, bytes)
}
fn poll_flush(
mut self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
) -> task::Poll<Result<(), Self::Error>> {
pin::Pin::new(&mut **self).poll_flush(cx)
}
fn poll_shutdown(
mut self: pin::Pin<&mut Self>,
cx: &mut task::Context<'_>,
) -> task::Poll<Result<(), Self::Error>> {
pin::Pin::new(&mut **self).poll_shutdown(cx)
}
}
/// An error that might arise from write operations.
pub trait WriteError: fmt::Debug {
/// Creates an error that indicates a zero-write condition.
///
/// This condition is to be used when a write operation requires more bytes to be written, but
/// an attempt to write returned zero bytes, indicating that there's no more room for bytes
/// to be written.
fn write_zero() -> Self;
}
/// Utility methods for types implementing [`Read`].
pub trait ReadExt: Read {
/// Reads data into the specified buffer, returning the number of bytes written.
fn read<'a>(&'a mut self, buffer: &'a mut [u8]) -> read::Read<'a, Self>
where
Self: Unpin,
{
read::read(self, buffer)
}
/// Reads data into the specified buffer, until the buffer is filled.
fn read_exact<'a>(&'a mut self, buffer: &'a mut [u8]) -> read_exact::ReadExact<'a, Self>
where
Self: Unpin,
{
read_exact::read_exact(self, buffer)
}
}
impl<A> ReadExt for A where A: Read {}
/// Utility methods for types implementing [`Write`].
pub trait WriteExt: Write {
/// Writes data from the specified buffer, returning the number of bytes written.
fn write<'a>(&'a mut self, bytes: &'a [u8]) -> write::Write<'a, Self>
where
Self: Unpin,
{
write::write(self, bytes)
}
/// Writes data from the specified buffer until all bytes are written.
fn write_all<'a>(&'a mut self, bytes: &'a [u8]) -> write_all::WriteAll<'a, Self>
where
Self: Unpin,
{
write_all::write_all(self, bytes)
}
/// Shuts down this writer.
fn shutdown(&mut self) -> shutdown::Shutdown<Self>
where
Self: Unpin,
{
shutdown::shutdown(self)
}
}
impl<A> WriteExt for A where A: Write {}
|
use super::responses::RemoveNeighborsResponse;
use crate::Result;
use reqwest::Client;
/// Removes a list of neighbors to your node.
/// This is only temporary, and if you have your neighbors
/// added via the command line, they will be retained after
/// you restart your node.
pub async fn remove_neighbors(
client: Client,
uri: String,
uris: Vec<String>,
) -> Result<RemoveNeighborsResponse> {
let body = json!({
"command": "removeNeighbors",
"uris": uris,
});
Ok(client
.post(&uri)
.header("ContentType", "application/json")
.header("X-IOTA-API-Version", "1")
.body(body.to_string())
.send()?
.json()?)
}
|
#[macro_use]
extern crate criterion;
use criterion::{BatchSize, Criterion};
use hacspec_aes::*;
use hacspec_dev::rand::random_byte_vec;
use hacspec_lib::prelude::*;
fn benchmark(c: &mut Criterion) {
c.bench_function("AES 128 encrypt", |b| {
b.iter_batched(
|| {
let key = Key128::from_public_slice(&random_byte_vec(16));
let nonce = AesNonce::from_public_slice(&random_byte_vec(12));
let data = ByteSeq::from_public_slice(&random_byte_vec(10_000));
(data, nonce, key)
},
|(data, nonce, key)| {
let _c = aes128_encrypt(key, nonce, U32(0), &data);
},
BatchSize::SmallInput,
)
});
c.bench_function("AES 128 decrypt", |b| {
b.iter_batched(
|| {
let key = Key128::from_public_slice(&random_byte_vec(16));
let nonce = AesNonce::from_public_slice(&random_byte_vec(12));
let data = ByteSeq::from_public_slice(&random_byte_vec(10_000));
let ctxt = aes128_encrypt(key, nonce, U32(0), &data);
(ctxt, nonce, key)
},
|(ctxt, nonce, key)| {
let _m = aes128_decrypt(key, nonce, U32(0), &ctxt);
},
BatchSize::SmallInput,
)
});
}
criterion_group!(benches, benchmark);
criterion_main!(benches);
|
use frame::Frame;
use texture::{Pixel, Texture};
pub use self::skyline_packer::SkylinePacker;
mod skyline_packer;
pub trait Packer {
type Pixel: Pixel;
fn pack(
&mut self,
key: String,
texture: &Texture<Pixel = Self::Pixel>,
) -> Option<Frame>;
fn can_pack(&self, texture: &Texture<Pixel = Self::Pixel>) -> bool;
}
|
use std::path::{Component, Path};
use quick_error::ResultExt;
pub use rodio::{queue::SourcesQueueOutput, Decoder, Device, Sample, Sink, Source, SpatialSink};
use serde::Deserialize;
use crate::{cache::download, error::Result, types::Chatsound, Chatsounds};
#[derive(Deserialize)]
pub struct GitHubApiFileEntry {
pub path: String,
pub r#type: String,
pub size: Option<usize>,
}
#[derive(Deserialize)]
pub struct GitHubApiTrees {
pub tree: Vec<GitHubApiFileEntry>,
}
pub type GitHubMsgpackEntries = Vec<Vec<String>>;
impl Chatsounds {
pub async fn fetch_github_api(&self, repo: &str, _repo_path: &str) -> Result<GitHubApiTrees> {
let api_url = format!(
"https://api.github.com/repos/{}/git/trees/HEAD?recursive=1",
repo
);
#[cfg(feature = "fs")]
let cache = &self.cache_path;
#[cfg(feature = "memory")]
let cache = self.fs_memory.clone();
let bytes = download(&api_url, cache, true).await?;
let trees: GitHubApiTrees = serde_json::from_slice(&bytes).context(&api_url)?;
Ok(trees)
}
pub fn load_github_api(
&mut self,
repo: &str,
repo_path: &str,
mut trees: GitHubApiTrees,
) -> Result<()> {
for entry in trees.tree.iter_mut() {
if entry.r#type != "blob" || !entry.path.starts_with(repo_path) {
continue;
}
// e26/stop.ogg or e26/nestetrismusic/1.ogg
let sound_path = entry.path.split_off(repo_path.len() + 1);
let path = Path::new(&sound_path);
if let Some(Component::Normal(s)) = path.components().nth(1) {
if let Some(sentence) = Path::new(&s).file_stem() {
let sentence = sentence.to_string_lossy().to_string();
let vec = self.map_store.entry(sentence).or_insert_with(Vec::new);
let chatsound = Chatsound {
repo: repo.to_string(),
repo_path: repo_path.to_string(),
sound_path,
};
let url = chatsound.get_url();
match vec.binary_search_by(|c| c.get_url().cmp(&url)) {
Ok(_pos) => {
// already exists, don't add again
}
Err(pos) => {
vec.insert(pos, chatsound);
}
}
}
}
}
Ok(())
}
pub async fn fetch_github_msgpack(
&self,
repo: &str,
repo_path: &str,
) -> Result<GitHubMsgpackEntries> {
let msgpack_url = format!(
"https://raw.githubusercontent.com/{}/HEAD/{}/list.msgpack",
repo, repo_path
);
#[cfg(feature = "fs")]
let cache = &self.cache_path;
#[cfg(feature = "memory")]
let cache = self.fs_memory.clone();
let bytes = download(&msgpack_url, cache, true).await?;
let entries: GitHubMsgpackEntries =
rmp_serde::decode::from_slice(&bytes).context(&msgpack_url)?;
Ok(entries)
}
pub fn load_github_msgpack(
&mut self,
repo: &str,
repo_path: &str,
mut entries: GitHubMsgpackEntries,
) -> Result<()> {
for entry in entries.drain(..) {
// e26/stop.ogg or e26/nestetrismusic/1.ogg
let sentence = entry[1].clone();
let sound_path = entry[2].clone();
let vec = self
.map_store
.entry(sentence.to_string())
.or_insert_with(Vec::new);
let chatsound = Chatsound {
repo: repo.to_string(),
repo_path: repo_path.to_string(),
sound_path,
};
let url = chatsound.get_url();
match vec.binary_search_by(|c| c.get_url().cmp(&url)) {
Ok(_pos) => {
// already exists, don't add again
}
Err(pos) => {
vec.insert(pos, chatsound);
}
}
}
Ok(())
}
}
|
fn main() {
let mut v = std::vec::Vec::<Body>::new();
v.push(Body {
pos: [-3,15,-11],
vel: [0,0,0],
});
v.push(Body {
pos: [3,13,-19],
vel: [0,0,0],
});
v.push(Body {
pos: [-13,18,-2],
vel: [0,0,0],
});
v.push(Body {
pos: [6,0,-1],
vel: [0,0,0],
});
for b in v.iter() {
println!("{:?}", b);
}
for n in 1..=1000 {
println!("Step {}", n);
simulate_step(&mut v);
}
let mut energy = 0;
for b in v.iter() {
let potential: i32 = b.pos.iter().map(|x| x.abs()).sum();
let kinetic: i32 = b.vel.iter().map(|x| x.abs()).sum();
energy += potential * kinetic;
}
println!("Total energy: {}", energy);
}
fn simulate_step(v: &mut std::vec::Vec::<Body>) {
for i in 0..v.len() {
for j in i+1..v.len() {
for n in 0..3 {
let (posl, posr) = (v[i].pos[n], v[j].pos[n]);
if posl > posr {
v[i].vel[n] -= 1;
v[j].vel[n] += 1;
} else if posl < posr {
v[i].vel[n] += 1;
v[j].vel[n] -= 1;
}
}
}
}
for b in v.iter_mut() {
for i in 0..3 {
b.pos[i] += b.vel[i];
}
println!("{:?}", b);
}
}
#[derive(Debug)]
struct Body {
pos: [i32; 3],
vel: [i32; 3],
}
|
use relalg::{Datum, ScalarExpr};
// Can copy-paste the examples from the tests in here to actually run them.
fn main() {
let __values_2 = vec![
vec![
ScalarExpr::Literal(Datum::Int(1i64)).eval(&Vec::new()),
ScalarExpr::Literal(Datum::Int(2i64)).eval(&Vec::new()),
ScalarExpr::Literal(Datum::Int(3i64)).eval(&Vec::new()),
],
vec![
ScalarExpr::Literal(Datum::Int(4i64)).eval(&Vec::new()),
ScalarExpr::Literal(Datum::Int(5i64)).eval(&Vec::new()),
ScalarExpr::Literal(Datum::Int(6i64)).eval(&Vec::new()),
],
]
.into_iter();
let __project_1 = __values_2.map(|row| {
vec![
ScalarExpr::Plus(
Box::new(ScalarExpr::ColRef(0usize)),
Box::new(ScalarExpr::Literal(Datum::Int(1i64))),
)
.eval(&row),
ScalarExpr::Plus(
Box::new(ScalarExpr::Literal(Datum::Int(5i64))),
Box::new(ScalarExpr::Plus(
Box::new(ScalarExpr::ColRef(1usize)),
Box::new(ScalarExpr::ColRef(2usize)),
)),
)
.eval(&row),
]
});
for row in __project_1 {
println!("{:?}", row);
}
}
|
fn main(){
newfunction(23);
}
fn newfunction(x: i32){
println!("Hello {}",x);
} |
use crate::frame_counter::FrameCounter;
use std::cell::RefCell;
pub struct GraphicsState {
pub window: winit::window::Window,
pub(super) surface: wgpu::Surface,
pub(super) device: wgpu::Device,
pub(super) queue: wgpu::Queue,
pub(super) swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub(super) swap_chain: wgpu::SwapChain,
pub(super) staging_belt: wgpu::util::StagingBelt,
pub(super) local_pool: futures::executor::LocalPool,
pub(super) local_spawner: futures::executor::LocalSpawner,
#[allow(dead_code)]
pub(super) shader_compiler: shaderc::Compiler,
#[allow(dead_code)]
pub(super) imgui_context: &'static RefCell<imgui::Context>,
pub(super) frame_counter: FrameCounter,
}
|
pub mod nuke;
pub mod package;
pub mod repo;
pub(crate) mod fbs {
fbs_build::include_fbs!("index");
}
pub trait Request {
type Error;
type Partial;
fn new_from_user_input(partial: Self::Partial) -> Result<Self, Self::Error>
where
Self: Sized;
}
pub fn make_lang_tag_map(value: String) -> pahkat_types::LangTagMap<String> {
let mut map = pahkat_types::LangTagMap::new();
map.insert("en".into(), value);
map
}
|
use brotli::CompressorWriter;
use bytes::BufMut;
use std::io::{Read, Write};
use bytes::Buf;
use std::ffi::{CStr, CString};
pub fn brotli_compress_rs(buf: &Vec<u8>) -> Vec<u8> {
// (false, buf.clone())
let compressed_buf = Vec::with_capacity(buf.len());
let mut w = compressed_buf.writer();
let mut c = CompressorWriter::new(&mut w, 4096, 11, 22);
let wa = c.write_all(buf.as_slice()).map_err(|_| ());
if wa.is_err() {
return buf.clone();
}
c.flush()
.map(|_| {
let c = c.into_inner();
if c.get_ref().len() < buf.len() {
c.get_ref().to_vec()
} else {
buf.clone()
}
})
.unwrap_or(buf.clone())
}
#[no_mangle]
pub extern "C" fn brotli_compress_base64(s: *const libc::c_char) -> *const libc::c_char {
let str = unsafe {
assert!(!s.is_null());
CStr::from_ptr(s)
};
let str = str.to_str().unwrap();
let buf = base64::decode(str).unwrap();
let ret = brotli_compress_rs(&buf);
let ret = base64::encode(&ret);
let s = CString::new(ret).unwrap();
s.into_raw()
}
pub fn brotli_copy<R: Read, W: Write>(source: R, mut dest: W) -> std::io::Result<u64> {
let mut decoder = brotli::Decompressor::new(source, 4096);
std::io::copy(&mut decoder, &mut dest)
}
#[no_mangle]
pub extern "C" fn brotli_decompress_base64(s: *const libc::c_char) -> *const libc::c_char {
let str = unsafe {
assert!(!s.is_null());
CStr::from_ptr(s)
};
let str = str.to_str().unwrap();
let buf = base64::decode(str).unwrap();
let ret = brotli_decompress_rs(&buf);
let ret = base64::encode(&ret);
let s = CString::new(ret).unwrap();
s.into_raw()
}
#[no_mangle]
pub extern "C" fn brotli_free_string(s: *mut libc::c_char) {
unsafe {
if s.is_null() {
return;
}
CString::from_raw(s);
}
}
pub fn brotli_decompress_rs(arr: &Vec<u8>) -> Vec<u8> {
let buf = Vec::with_capacity(arr.len());
let mut w = buf.writer();
let cpy = brotli_copy(arr.reader(), &mut w).map_err(|_| ());
if cpy.is_err() {
return vec![];
}
w.get_ref().to_vec()
}
|
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub enum Dir {
North,
East,
South,
West,
}
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub struct CoordinateSystem {
dx_east: i64,
dy_south: i64,
}
pub fn step(dir: Dir, coords: CoordinateSystem) -> (i64, i64) {
match dir {
Dir::North => (0, -coords.dy_south),
Dir::East => (coords.dx_east, 0),
Dir::South => (0, coords.dy_south),
Dir::West => (-coords.dx_east, 0),
}
}
pub trait Directional {
fn as_dir(&self) -> Dir;
fn from_dir(dir: Dir) -> Self;
fn step(&self) -> (i64, i64) {
step(self.as_dir(), Self::coord_system())
}
fn coord_system() -> CoordinateSystem;
}
pub fn step_to<D: Directional>(pos: (i64, i64), dir: D) -> (i64, i64) {
let (dx, dy) = dir.step();
(pos.0 + dx, pos.1 + dy)
}
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub enum Turn {
Left,
Right,
}
pub fn turn_to<D: Directional>(dir: D, turn: Turn) -> D {
match (dir.as_dir(), turn) {
(Dir::North, Turn::Left) => D::from_dir(Dir::West),
(Dir::North, Turn::Right) => D::from_dir(Dir::East),
(Dir::East, Turn::Left) => D::from_dir(Dir::North),
(Dir::East, Turn::Right) => D::from_dir(Dir::South),
(Dir::South, Turn::Left) => D::from_dir(Dir::East),
(Dir::South, Turn::Right) => D::from_dir(Dir::West),
(Dir::West, Turn::Left) => D::from_dir(Dir::South),
(Dir::West, Turn::Right) => D::from_dir(Dir::North),
}
}
pub const CART_COORDS: CoordinateSystem = CoordinateSystem { dx_east: 1, dy_south: -1};
pub const SCREEN_COORDS: CoordinateSystem = CoordinateSystem { dx_east: 1, dy_south: 1};
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub enum CartesianDir {
North,
East,
South,
West,
}
impl Directional for CartesianDir {
fn as_dir(&self) -> Dir {
match self {
CartesianDir::North => Dir::North,
CartesianDir::East => Dir::East,
CartesianDir::South => Dir::South,
CartesianDir::West => Dir::West,
}
}
fn from_dir(dir: Dir) -> Self {
match dir {
Dir::North => CartesianDir::North,
Dir::East => CartesianDir::East,
Dir::South => CartesianDir::South,
Dir::West => CartesianDir::West,
}
}
fn coord_system() -> CoordinateSystem {
CART_COORDS
}
}
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub enum ScreenDir {
North,
East,
South,
West,
}
impl Directional for ScreenDir {
fn as_dir(&self) -> Dir {
match self {
ScreenDir::North => Dir::North,
ScreenDir::East => Dir::East,
ScreenDir::South => Dir::South,
ScreenDir::West => Dir::West,
}
}
fn from_dir(dir: Dir) -> Self {
match dir {
Dir::North => ScreenDir::North,
Dir::East => ScreenDir::East,
Dir::South => ScreenDir::South,
Dir::West => ScreenDir::West,
}
}
fn coord_system() -> CoordinateSystem {
SCREEN_COORDS
}
}
|
fn main() {
tonic_build::compile_protos("proto/pahkat.proto").unwrap();
let gen_path = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("pahkat.rs");
let data = std::fs::read_to_string(&gen_path).unwrap();
let data = data.replace(
"::prost::Message)",
"::prost::Message, ::serde::Serialize, ::serde::Deserialize)",
);
let data = data.replace(
"::prost::Oneof)",
"::prost::Oneof, ::serde::Serialize, ::serde::Deserialize)",
);
let data = data.replace(
"pub enum Value {",
"#[serde(tag = \"type\")] pub enum Value {",
);
std::fs::write(gen_path, data).unwrap();
}
|
// Copyright 2019, 2020 Wingchain
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_attribute]
pub fn enum_codec(_attr: TokenStream, item: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(item).unwrap();
let variants = match ast.data {
syn::Data::Enum(ref v) => &v.variants,
_ => panic!("enum_codec only works on Enum"),
};
let type_name = &ast.ident;
let encode_vec = variants
.iter()
.map(|x| {
let ident = &x.ident;
quote! { #type_name :: #ident(v) => {
stringify!(#ident).encode_to(&mut r);
v.encode_to(&mut r);
}, }
})
.collect::<Vec<_>>();
let decode_vec = variants
.iter()
.map(|x| {
let ident = &x.ident;
quote! { stringify!(#ident) => {
Ok(Self::#ident(Decode::decode(value)?))
}, }
})
.collect::<Vec<_>>();
let gen = quote! {
#ast
impl Encode for #type_name {
fn encode(&self) -> Vec<u8> {
let mut r = vec![];
match self {
#(#encode_vec)*
}
r
}
}
impl Decode for #type_name {
fn decode<I: scale_codec::Input>(value: &mut I) -> Result<Self, scale_codec::Error> {
let name: String = Decode::decode(value)?;
match name.as_str() {
#(#decode_vec)*
_ => Err("Unknown variant name".into()),
}
}
}
};
gen.into()
}
|
#[derive(Debug)]
pub struct Rating {
pub value: i64,
}
|
use super::BlockId;
use crate::arena::resource::ResourceId;
use crate::libs::select_list::SelectList;
#[derive(Clone)]
pub struct Drawing {
drawing_texture_id: BlockId,
drawed_texture_id: BlockId,
}
impl Drawing {
pub fn new(drawing_texture_id: BlockId, drawed_texture_id: BlockId) -> Self {
Self {
drawing_texture_id,
drawed_texture_id,
}
}
pub fn drawing_texture_id(&self) -> &BlockId {
&self.drawed_texture_id
}
pub fn set_drawing_texture_id(&mut self, block_id: BlockId) {
self.drawing_texture_id = block_id;
}
pub fn drawed_texture_id(&self) -> &BlockId {
&self.drawed_texture_id
}
pub fn set_drawed_texture_id(&mut self, block_id: BlockId) {
self.drawed_texture_id = block_id;
}
}
#[derive(Clone)]
pub struct Image {
resource_id: Option<ResourceId>,
}
impl Image {
pub fn new() -> Self {
Self { resource_id: None }
}
pub fn resource_id(&self) -> Option<&ResourceId> {
self.resource_id.as_ref()
}
pub fn set_resource_id(&mut self, resource_id: Option<ResourceId>) {
self.resource_id = resource_id;
}
}
#[derive(Clone)]
pub struct Fill {
color: crate::libs::color::Pallet,
}
impl Fill {
pub fn new() -> Self {
Self {
color: crate::libs::color::Pallet::gray(0),
}
}
}
#[derive(Clone)]
pub enum Layer {
ShapeGroup(BlockId),
Drawing(Drawing),
Image(Image),
Fill(Fill),
LayerGroup(BlockId),
}
impl Layer {
pub fn new_shape_group(shape_group: BlockId) -> Self {
Self::ShapeGroup(shape_group)
}
pub fn new_drawing(drawing_texture_id: BlockId, drawed_texture_id: BlockId) -> Self {
Self::Drawing(Drawing::new(drawing_texture_id, drawed_texture_id))
}
pub fn new_image() -> Self {
Self::Image(Image::new())
}
pub fn new_layer_group(layer_group: BlockId) -> Self {
Self::LayerGroup(layer_group)
}
pub fn as_drawing(&self) -> Option<&Drawing> {
match self {
Self::Drawing(x) => Some(x),
_ => None,
}
}
}
#[derive(Clone)]
pub struct LayerGroup {
layers: SelectList<Layer>,
}
impl LayerGroup {
pub fn new() -> Self {
Self {
layers: SelectList::new(vec![], 0),
}
}
pub fn layers(&self) -> std::slice::Iter<Layer> {
self.layers.iter()
}
pub fn add_layer(&mut self, layer: Layer) {
self.layers.push(layer);
}
pub fn remove_layer(&mut self, idx: usize) -> Option<Layer> {
self.layers.remove(idx)
}
pub fn selected_layer(&self) -> Option<&Layer> {
self.layers.selected()
}
}
|
struct Solution {}
impl Solution {
pub fn mirror_reflection(mut p: i32, mut q: i32) -> i32 {
while p%2 == 0 && q%2 == 0 {
p/=2;
q/=2;
}
1 - p%2 + q%2
}
}
fn main() {
println!("Hello, world!");
}
|
use std::borrow::Borrow;
use std::collections::HashMap;
use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::{FluentResource, FluentValue};
pub use unic_langid::{langid, langids, LanguageIdentifier};
pub fn lookup_single_language<T: AsRef<str>, R: Borrow<FluentResource>>(
bundles: &HashMap<LanguageIdentifier, FluentBundle<R>>,
lang: &LanguageIdentifier,
text_id: &str,
args: Option<&HashMap<T, FluentValue>>,
) -> Option<String> {
let bundle = bundles.get(lang)?;
let mut errors = Vec::new();
let pattern = if text_id.contains('.') {
// TODO: #![feature(str_split_once)]
let ids: Vec<_> = text_id.splitn(2, '.').collect();
bundle
.get_message(ids[0])?
.attributes
.iter()
.find(|attribute| attribute.id == ids[1])?
.value
} else {
bundle.get_message(text_id)?.value?
};
let args = super::map_to_fluent_args(args);
let value = bundle.format_pattern(&pattern, args.as_ref(), &mut errors);
if errors.is_empty() {
Some(value.into())
} else {
panic!(
"Failed to format a message for locale {} and id {}.\nErrors\n{:?}",
lang, text_id, errors
)
}
}
pub fn lookup_no_default_fallback<S: AsRef<str>, R: Borrow<FluentResource>>(
bundles: &HashMap<LanguageIdentifier, FluentBundle<R>>,
fallbacks: &HashMap<LanguageIdentifier, Vec<LanguageIdentifier>>,
lang: &LanguageIdentifier,
text_id: &str,
args: Option<&HashMap<S, FluentValue>>,
) -> Option<String> {
let fallbacks = fallbacks.get(lang)?;
for l in fallbacks {
if let Some(val) = lookup_single_language(bundles, l, text_id, args) {
return Some(val);
}
}
None
}
|
use super::{new_block_assembler_config, type_lock_script_code_hash};
use crate::utils::wait_until;
use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW};
use ckb_app_config::CKBAppConfig;
use ckb_crypto::secp::{Generator, Privkey};
use ckb_hash::{blake2b_256, new_blake2b};
use ckb_types::{
bytes::Bytes,
core::{
capacity_bytes, BlockView, Capacity, DepType, ScriptHashType, TransactionBuilder,
TransactionView,
},
packed::{CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs},
prelude::*,
H256,
};
use log::info;
pub struct SendLargeCyclesTxInBlock {
privkey: Privkey,
lock_arg: Bytes,
}
impl SendLargeCyclesTxInBlock {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let mut generator = Generator::new();
let privkey = generator.gen_privkey();
let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize();
let lock_arg = Bytes::from(&blake2b_256(&pubkey_data)[0..20]);
SendLargeCyclesTxInBlock { privkey, lock_arg }
}
}
impl Spec for SendLargeCyclesTxInBlock {
crate::name!("send_large_cycles_tx_in_block");
crate::setup!(num_nodes: 2, connect_all: false);
fn run(&self, net: &mut Net) {
// high cycle limit node
let mut node0 = net.nodes.remove(0);
// low cycle limit node
let node1 = &net.nodes[0];
node0.stop();
node0.edit_config_file(
Box::new(|_| ()),
Box::new(move |config| {
config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into();
}),
);
node0.start();
node1.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
info!("Generate large cycles tx");
let tx = build_tx(&node1, &self.privkey, self.lock_arg.clone());
// send tx
let ret = node1.rpc_client().send_transaction_result(tx.data().into());
assert!(ret.is_err());
info!("Node0 mine large cycles tx");
node0.connect(&node1);
let result = wait_until(60, || {
node1.get_tip_block_number() == node0.get_tip_block_number()
});
assert!(result, "node0 can't sync with node1");
node0.disconnect(&node1);
let ret = node0.rpc_client().send_transaction_result(tx.data().into());
ret.expect("package large cycles tx");
node0.generate_blocks(3);
let block: BlockView = node0.get_tip_block();
assert_eq!(block.transactions()[1], tx);
node0.connect(&node1);
info!("Wait block relay to node1");
let result = wait_until(60, || {
let block2: BlockView = node1.get_tip_block();
block2.hash() == block.hash()
});
assert!(result, "block can't relay to node1");
}
fn modify_ckb_config(&self) -> Box<dyn Fn(&mut CKBAppConfig) -> ()> {
let lock_arg = self.lock_arg.clone();
Box::new(move |config| {
config.network.connect_outbound_interval_secs = 0;
config.tx_pool.max_tx_verify_cycles = 5000u64;
let block_assembler =
new_block_assembler_config(lock_arg.clone(), ScriptHashType::Type);
config.block_assembler = Some(block_assembler);
})
}
}
pub struct SendLargeCyclesTxToRelay {
privkey: Privkey,
lock_arg: Bytes,
}
impl SendLargeCyclesTxToRelay {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let mut generator = Generator::new();
let privkey = generator.gen_privkey();
let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize();
let lock_arg = Bytes::from(&blake2b_256(&pubkey_data)[0..20]);
SendLargeCyclesTxToRelay { privkey, lock_arg }
}
}
impl Spec for SendLargeCyclesTxToRelay {
crate::name!("send_large_cycles_tx_to_relay");
crate::setup!(num_nodes: 2, connect_all: false);
fn run(&self, net: &mut Net) {
// high cycle limit node
let mut node0 = net.nodes.remove(0);
// low cycle limit node
let node1 = &net.nodes[0];
node0.stop();
node0.edit_config_file(
Box::new(|_| ()),
Box::new(move |config| {
config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into();
}),
);
node0.start();
node1.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
info!("Generate large cycles tx");
let tx = build_tx(&node1, &self.privkey, self.lock_arg.clone());
// send tx
let ret = node1.rpc_client().send_transaction_result(tx.data().into());
assert!(ret.is_err());
info!("Node0 mine large cycles tx");
node0.connect(&node1);
let result = wait_until(60, || {
node1.get_tip_block_number() == node0.get_tip_block_number()
});
assert!(result, "node0 can't sync with node1");
let ret = node0.rpc_client().send_transaction_result(tx.data().into());
ret.expect("package large cycles tx");
info!("Node1 do not accept tx");
let result = wait_until(5, || {
node1.rpc_client().get_transaction(tx.hash()).is_some()
});
assert!(!result, "Node1 should ignore tx");
}
fn modify_ckb_config(&self) -> Box<dyn Fn(&mut CKBAppConfig) -> ()> {
let lock_arg = self.lock_arg.clone();
Box::new(move |config| {
config.network.connect_outbound_interval_secs = 0;
config.tx_pool.max_tx_verify_cycles = 5000u64;
let block_assembler =
new_block_assembler_config(lock_arg.clone(), ScriptHashType::Type);
config.block_assembler = Some(block_assembler);
})
}
}
fn build_tx(node: &Node, privkey: &Privkey, lock_arg: Bytes) -> TransactionView {
let secp_out_point = OutPoint::new(node.dep_group_tx_hash(), 0);
let lock = Script::new_builder()
.args(lock_arg.pack())
.code_hash(type_lock_script_code_hash().pack())
.hash_type(ScriptHashType::Type.into())
.build();
let cell_dep = CellDep::new_builder()
.out_point(secp_out_point)
.dep_type(DepType::DepGroup.into())
.build();
let input1 = {
let block = node.get_tip_block();
let cellbase_hash = block.transactions()[0].hash();
CellInput::new(OutPoint::new(cellbase_hash, 0), 0)
};
let output1 = CellOutput::new_builder()
.capacity(capacity_bytes!(100).pack())
.lock(lock)
.build();
let tx = TransactionBuilder::default()
.cell_dep(cell_dep)
.input(input1)
.output(output1)
.output_data(Default::default())
.build();
let tx_hash: H256 = tx.hash().unpack();
let witness = WitnessArgs::new_builder()
.lock(Some(Bytes::from(vec![0u8; 65])).pack())
.build();
let witness_len = witness.as_slice().len() as u64;
let message = {
let mut hasher = new_blake2b();
hasher.update(&tx_hash.as_bytes());
hasher.update(&witness_len.to_le_bytes());
hasher.update(&witness.as_slice());
let mut buf = [0u8; 32];
hasher.finalize(&mut buf);
H256::from(buf)
};
let sig = privkey.sign_recoverable(&message).expect("sign");
let witness = witness
.as_builder()
.lock(Some(Bytes::from(sig.serialize())).pack())
.build();
tx.as_advanced_builder()
.witness(witness.as_bytes().pack())
.build()
}
|
use crate::{
arch::{self, KERNEL_STACK_SIZE, USER_STACK_TOP},
ctypes::*,
fs::{
devfs::SERIAL_TTY,
mount::RootFs,
opened_file::{Fd, OpenFlags, OpenOptions, OpenedFile, OpenedFileTable, PathComponent},
path::Path,
},
mm::vm::{Vm, VmAreaType},
prelude::*,
process::{
cmdline::Cmdline,
current_process,
elf::{Elf, ProgramHeader},
init_stack::{estimate_user_init_stack_size, init_user_stack, Auxv},
process_group::{PgId, ProcessGroup},
signal::{SigAction, Signal, SignalDelivery, SIGCHLD, SIGKILL},
switch, UserVAddr, JOIN_WAIT_QUEUE, SCHEDULER,
},
random::read_secure_random,
INITIAL_ROOT_FS,
};
use alloc::collections::BTreeMap;
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;
use atomic_refcell::{AtomicRef, AtomicRefCell};
use core::cmp::max;
use core::mem::size_of;
use core::sync::atomic::{AtomicI32, Ordering};
use crossbeam::atomic::AtomicCell;
use goblin::elf64::program_header::PT_LOAD;
use kerla_runtime::{
arch::{SyscallFrame, PAGE_SIZE},
page_allocator::{alloc_pages, AllocPageFlags},
spinlock::{SpinLock, SpinLockGuard},
};
use kerla_utils::alignment::align_up;
type ProcessTable = BTreeMap<PId, Arc<Process>>;
/// The process table. All processes are registered in with its process Id.
pub(super) static PROCESSES: SpinLock<ProcessTable> = SpinLock::new(BTreeMap::new());
/// Returns an unused PID. Note that this function does not reserve the PID:
/// keep the process table locked until you insert the process into the table!
pub(super) fn alloc_pid(table: &mut ProcessTable) -> Result<PId> {
static NEXT_PID: AtomicI32 = AtomicI32::new(2);
let last_pid = NEXT_PID.load(Ordering::SeqCst);
loop {
// Note: `fetch_add` may wrap around.
let pid = NEXT_PID.fetch_add(1, Ordering::SeqCst);
if pid <= 1 {
continue;
}
if !table.contains_key(&PId::new(pid)) {
return Ok(PId::new(pid));
}
if pid == last_pid {
return Err(Errno::EAGAIN.into());
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PId(i32);
impl PId {
pub const fn new(pid: i32) -> PId {
PId(pid)
}
pub const fn as_i32(self) -> i32 {
self.0
}
}
/// Process states.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ProcessState {
/// The process is runnable.
Runnable,
/// The process is sleeping. It can be resumed by signals.
BlockedSignalable,
/// The process has exited.
ExitedWith(c_int),
}
/// The process control block.
pub struct Process {
arch: arch::Process,
process_group: AtomicRefCell<Weak<SpinLock<ProcessGroup>>>,
pid: PId,
state: AtomicCell<ProcessState>,
parent: Weak<Process>,
cmdline: AtomicRefCell<Cmdline>,
children: SpinLock<Vec<Arc<Process>>>,
vm: AtomicRefCell<Option<Arc<SpinLock<Vm>>>>,
opened_files: SpinLock<OpenedFileTable>,
root_fs: Arc<SpinLock<RootFs>>,
signals: SpinLock<SignalDelivery>,
signaled_frame: AtomicCell<Option<SyscallFrame>>,
}
impl Process {
/// Creates a per-CPU idle thread.
///
/// An idle thread is a special type of kernel threads which is executed
/// only if there're no other runnable processes.
pub fn new_idle_thread() -> Result<Arc<Process>> {
let process_group = ProcessGroup::new(PgId::new(0));
let proc = Arc::new(Process {
process_group: AtomicRefCell::new(Arc::downgrade(&process_group)),
arch: arch::Process::new_idle_thread(),
state: AtomicCell::new(ProcessState::Runnable),
parent: Weak::new(),
cmdline: AtomicRefCell::new(Cmdline::new()),
children: SpinLock::new(Vec::new()),
vm: AtomicRefCell::new(None),
pid: PId::new(0),
root_fs: INITIAL_ROOT_FS.clone(),
opened_files: SpinLock::new(OpenedFileTable::new()),
signals: SpinLock::new(SignalDelivery::new()),
signaled_frame: AtomicCell::new(None),
});
process_group.lock().add(Arc::downgrade(&proc));
Ok(proc)
}
/// Creates the initial process (PID=1).
pub fn new_init_process(
root_fs: Arc<SpinLock<RootFs>>,
executable_path: Arc<PathComponent>,
console: Arc<PathComponent>,
argv: &[&[u8]],
) -> Result<()> {
assert!(console.inode.is_file());
let mut opened_files = OpenedFileTable::new();
// Open stdin.
opened_files.open_with_fixed_fd(
Fd::new(0),
Arc::new(OpenedFile::new(
console.clone(),
OpenFlags::O_RDONLY.into(),
0,
)),
OpenOptions::empty(),
)?;
// Open stdout.
opened_files.open_with_fixed_fd(
Fd::new(1),
Arc::new(OpenedFile::new(
console.clone(),
OpenFlags::O_WRONLY.into(),
0,
)),
OpenOptions::empty(),
)?;
// Open stderr.
opened_files.open_with_fixed_fd(
Fd::new(2),
Arc::new(OpenedFile::new(console, OpenFlags::O_WRONLY.into(), 0)),
OpenOptions::empty(),
)?;
let entry = setup_userspace(executable_path, argv, &[], &root_fs)?;
let pid = PId::new(1);
let stack_bottom = alloc_pages(KERNEL_STACK_SIZE / PAGE_SIZE, AllocPageFlags::KERNEL)?;
let kernel_sp = stack_bottom.as_vaddr().add(KERNEL_STACK_SIZE);
let process_group = ProcessGroup::new(PgId::new(1));
let process = Arc::new(Process {
process_group: AtomicRefCell::new(Arc::downgrade(&process_group)),
pid,
parent: Weak::new(),
children: SpinLock::new(Vec::new()),
state: AtomicCell::new(ProcessState::Runnable),
cmdline: AtomicRefCell::new(Cmdline::from_argv(argv)),
arch: arch::Process::new_user_thread(entry.ip, entry.user_sp, kernel_sp),
vm: AtomicRefCell::new(Some(Arc::new(SpinLock::new(entry.vm)))),
opened_files: SpinLock::new(opened_files),
root_fs,
signals: SpinLock::new(SignalDelivery::new()),
signaled_frame: AtomicCell::new(None),
});
process_group.lock().add(Arc::downgrade(&process));
PROCESSES.lock().insert(pid, process);
SCHEDULER.lock().enqueue(pid);
SERIAL_TTY.set_foreground_process_group(Arc::downgrade(&process_group));
Ok(())
}
/// Returns the process with the given process ID.
pub fn find_by_pid(pid: PId) -> Option<Arc<Process>> {
PROCESSES.lock().get(&pid).cloned()
}
/// The process ID.
pub fn pid(&self) -> PId {
self.pid
}
/// The thread ID.
pub fn tid(&self) -> PId {
// In a single-threaded process, the thread ID is equal to the process ID (PID).
// https://man7.org/linux/man-pages/man2/gettid.2.html
self.pid
}
/// The arch-specific information.
pub fn arch(&self) -> &arch::Process {
&self.arch
}
/// The process parent.
fn parent(&self) -> Option<Arc<Process>> {
self.parent.upgrade().as_ref().cloned()
}
/// The ID of process being parent of this process.
pub fn ppid(&self) -> PId {
if let Some(parent) = self.parent() {
parent.pid()
} else {
PId::new(0)
}
}
pub fn cmdline(&self) -> AtomicRef<'_, Cmdline> {
self.cmdline.borrow()
}
/// Its child processes.
pub fn children(&self) -> SpinLockGuard<'_, Vec<Arc<Process>>> {
self.children.lock()
}
/// The process's path resolution info.
pub fn root_fs(&self) -> &Arc<SpinLock<RootFs>> {
&self.root_fs
}
/// The ppened files table.
pub fn opened_files(&self) -> &SpinLock<OpenedFileTable> {
&self.opened_files
}
/// The virtual memory space. It's `None` if the process is a kernel thread.
pub fn vm(&self) -> AtomicRef<'_, Option<Arc<SpinLock<Vm>>>> {
self.vm.borrow()
}
/// Signals.
pub fn signals(&self) -> &SpinLock<SignalDelivery> {
&self.signals
}
/// Changes the process group.
pub fn set_process_group(&self, pg: Weak<SpinLock<ProcessGroup>>) {
*self.process_group.borrow_mut() = pg;
}
/// The current process group.
pub fn process_group(&self) -> Arc<SpinLock<ProcessGroup>> {
self.process_group.borrow().upgrade().unwrap()
}
/// Returns true if the process belongs to the process group `pg`.
pub fn belongs_to_process_group(&self, pg: &Weak<SpinLock<ProcessGroup>>) -> bool {
Weak::ptr_eq(&self.process_group.borrow(), pg)
}
/// The current process state.
pub fn state(&self) -> ProcessState {
self.state.load()
}
/// Updates the process state.
pub fn set_state(&self, new_state: ProcessState) {
let scheduler = SCHEDULER.lock();
self.state.store(new_state);
match new_state {
ProcessState::Runnable => {}
ProcessState::BlockedSignalable | ProcessState::ExitedWith(_) => {
scheduler.remove(self.pid);
}
}
}
/// Resumes a process.
pub fn resume(&self) {
let old_state = self.state.swap(ProcessState::Runnable);
debug_assert!(!matches!(old_state, ProcessState::ExitedWith(_)));
if old_state == ProcessState::Runnable {
return;
}
SCHEDULER.lock().enqueue(self.pid);
}
/// Searches the opned file table by the file descriptor.
pub fn get_opened_file_by_fd(&self, fd: Fd) -> Result<Arc<OpenedFile>> {
Ok(self.opened_files.lock().get(fd)?.clone())
}
/// Terminates the **current** process.
pub fn exit(status: c_int) -> ! {
let current = current_process();
if current.pid == PId::new(1) {
panic!("init (pid=0) tried to exit")
}
current.set_state(ProcessState::ExitedWith(status));
if let Some(parent) = current.parent.upgrade() {
parent.send_signal(SIGCHLD);
}
// Close opened files here instead of in Drop::drop because `proc` is
// not dropped until it's joined by the parent process. Drop them to
// make pipes closed.
current.opened_files.lock().close_all();
PROCESSES.lock().remove(¤t.pid);
JOIN_WAIT_QUEUE.wake_all();
switch();
unreachable!();
}
/// Terminates the **current** process by a signal.
pub fn exit_by_signal(_signal: Signal) -> ! {
Process::exit(1 /* FIXME: how should we compute the exit status? */);
}
/// Sends a signal.
pub fn send_signal(&self, signal: Signal) {
self.signals.lock().signal(signal);
self.resume();
}
/// Returns `true` if there's a pending signal.
pub fn has_pending_signals(&self) -> bool {
self.signals.lock().is_pending()
}
/// Tries to delivering a pending signal to the current process.
///
/// If there's a pending signal, it may modify `frame` (e.g. user return
/// address and stack pointer) to call the registered user's signal handler.
pub fn try_delivering_signal(frame: &mut SyscallFrame) -> Result<()> {
// TODO: sigmask
let current = current_process();
if let Some((signal, sigaction)) = current.signals.lock().pop_pending() {
match sigaction {
SigAction::Ignore => {}
SigAction::Terminate => {
trace!("terminating {:?} by {:?}", current.pid, signal,);
Process::exit(1 /* FIXME: */);
}
SigAction::Handler { handler } => {
trace!("delivering {:?} to {:?}", signal, current.pid,);
current.signaled_frame.store(Some(*frame));
unsafe {
current.arch.setup_signal_stack(frame, signal, handler)?;
}
}
}
}
Ok(())
}
/// So-called `sigreturn`: restores the user context when the signal is
/// delivered to a signal handler.
pub fn restore_signaled_user_stack(current: &Arc<Process>, current_frame: &mut SyscallFrame) {
if let Some(signaled_frame) = current.signaled_frame.swap(None) {
current
.arch
.setup_sigreturn_stack(current_frame, &signaled_frame);
} else {
// The user intentionally called sigreturn(2) while it is not signaled.
// TODO: Should we ignore instead of the killing the process?
Process::exit_by_signal(SIGKILL);
}
}
/// Creates a new virtual memory space, loads the executable, and overwrites
/// the **current** process.
///
/// It modifies `frame` to start from the new executable's entry point with
/// new stack (ie. argv and envp) when the system call handler returns into
/// the userspace.
pub fn execve(
frame: &mut SyscallFrame,
executable_path: Arc<PathComponent>,
argv: &[&[u8]],
envp: &[&[u8]],
) -> Result<()> {
let current = current_process();
current.opened_files.lock().close_cloexec_files();
current.cmdline.borrow_mut().set_by_argv(argv);
let entry = setup_userspace(executable_path, argv, envp, ¤t.root_fs)?;
// FIXME: Should we prevent try_delivering_signal()?
current.signaled_frame.store(None);
entry.vm.page_table().switch();
*current.vm.borrow_mut() = Some(Arc::new(SpinLock::new(entry.vm)));
current
.arch
.setup_execve_stack(frame, entry.ip, entry.user_sp)?;
Ok(())
}
/// Creates a new process. The calling process (`self`) will be the parent
/// process of the created process. Returns the created child process.
pub fn fork(parent: &Arc<Process>, parent_frame: &SyscallFrame) -> Result<Arc<Process>> {
let parent_weak = Arc::downgrade(parent);
let mut process_table = PROCESSES.lock();
let pid = alloc_pid(&mut process_table)?;
let arch = parent.arch.fork(parent_frame)?;
let vm = parent.vm().as_ref().unwrap().lock().fork()?;
let opened_files = parent.opened_files().lock().fork();
let process_group = parent.process_group();
let child = Arc::new(Process {
process_group: AtomicRefCell::new(Arc::downgrade(&process_group)),
pid,
state: AtomicCell::new(ProcessState::Runnable),
parent: parent_weak,
cmdline: AtomicRefCell::new(parent.cmdline().clone()),
children: SpinLock::new(Vec::new()),
vm: AtomicRefCell::new(Some(Arc::new(SpinLock::new(vm)))),
opened_files: SpinLock::new(opened_files),
root_fs: parent.root_fs().clone(),
arch,
signals: SpinLock::new(SignalDelivery::new()),
signaled_frame: AtomicCell::new(None),
});
process_group.lock().add(Arc::downgrade(&child));
parent.children().push(child.clone());
process_table.insert(pid, child.clone());
SCHEDULER.lock().enqueue(pid);
Ok(child)
}
}
impl Drop for Process {
fn drop(&mut self) {
trace!(
"dropping {:?} (cmdline={})",
self.pid(),
self.cmdline().as_str()
);
// Since the process's reference count has already reached to zero (that's
// why the process is being dropped), ProcessGroup::remove_dropped_processes
// should remove this process from its list.
self.process_group().lock().remove_dropped_processes();
}
}
struct UserspaceEntry {
vm: Vm,
ip: UserVAddr,
user_sp: UserVAddr,
}
fn setup_userspace(
executable_path: Arc<PathComponent>,
argv: &[&[u8]],
envp: &[&[u8]],
root_fs: &Arc<SpinLock<RootFs>>,
) -> Result<UserspaceEntry> {
do_setup_userspace(executable_path, argv, envp, root_fs, true)
}
/// Creates a new virtual memory space, parses and maps an executable file,
/// and set up the user stack.
fn do_setup_userspace(
executable_path: Arc<PathComponent>,
argv: &[&[u8]],
envp: &[&[u8]],
root_fs: &Arc<SpinLock<RootFs>>,
handle_shebang: bool,
) -> Result<UserspaceEntry> {
// Read the ELF header in the executable file.
let file_header_len = PAGE_SIZE;
let file_header_top = USER_STACK_TOP;
let file_header_pages = alloc_pages(file_header_len / PAGE_SIZE, AllocPageFlags::KERNEL)?;
let buf =
unsafe { core::slice::from_raw_parts_mut(file_header_pages.as_mut_ptr(), file_header_len) };
let executable = executable_path.inode.as_file()?;
executable.read(0, buf.into(), &OpenOptions::readwrite())?;
if handle_shebang && buf.starts_with(b"#!") && buf.contains(&b'\n') {
let mut argv: Vec<&[u8]> = buf[2..buf.iter().position(|&ch| ch == b'\n').unwrap()]
.split(|&ch| ch == b' ')
.collect();
if argv.is_empty() {
return Err(Errno::EINVAL.into());
}
let executable_pathbuf = executable_path.resolve_absolute_path();
argv.push(executable_pathbuf.as_str().as_bytes());
let shebang_path = root_fs.lock().lookup_path(
Path::new(core::str::from_utf8(argv[0]).map_err(|_| Error::new(Errno::EINVAL))?),
true,
)?;
return do_setup_userspace(shebang_path, &argv, envp, root_fs, false);
}
let elf = Elf::parse(buf)?;
let ip = elf.entry()?;
let mut end_of_image = 0;
for phdr in elf.program_headers() {
if phdr.p_type == PT_LOAD {
end_of_image = max(end_of_image, (phdr.p_vaddr + phdr.p_memsz) as usize);
}
}
let mut random_bytes = [0u8; 16];
read_secure_random(((&mut random_bytes) as &mut [u8]).into())?;
// Set up the user stack.
let auxv = &[
Auxv::Phdr(
file_header_top
.sub(file_header_len)
.add(elf.header().e_phoff as usize),
),
Auxv::Phnum(elf.program_headers().len()),
Auxv::Phent(size_of::<ProgramHeader>()),
Auxv::Pagesz(PAGE_SIZE),
Auxv::Random(random_bytes),
];
const USER_STACK_LEN: usize = 128 * 1024; // TODO: Implement rlimit
let init_stack_top = file_header_top.sub(file_header_len);
let user_stack_bottom = init_stack_top.sub(USER_STACK_LEN).value();
let user_heap_bottom = align_up(end_of_image, PAGE_SIZE);
let init_stack_len = align_up(estimate_user_init_stack_size(argv, envp, auxv), PAGE_SIZE);
if user_heap_bottom >= user_stack_bottom || init_stack_len >= USER_STACK_LEN {
return Err(Errno::E2BIG.into());
}
let init_stack_pages = alloc_pages(init_stack_len / PAGE_SIZE, AllocPageFlags::KERNEL)?;
let user_sp = init_user_stack(
init_stack_top,
init_stack_pages.as_vaddr().add(init_stack_len),
init_stack_pages.as_vaddr(),
argv,
envp,
auxv,
)?;
let mut vm = Vm::new(
UserVAddr::new(user_stack_bottom).unwrap(),
UserVAddr::new(user_heap_bottom).unwrap(),
)?;
for i in 0..(file_header_len / PAGE_SIZE) {
vm.page_table_mut().map_user_page(
file_header_top.sub(((file_header_len / PAGE_SIZE) - i) * PAGE_SIZE),
file_header_pages.add(i * PAGE_SIZE),
);
}
for i in 0..(init_stack_len / PAGE_SIZE) {
vm.page_table_mut().map_user_page(
init_stack_top.sub(((init_stack_len / PAGE_SIZE) - i) * PAGE_SIZE),
init_stack_pages.add(i * PAGE_SIZE),
);
}
// Register program headers in the virtual memory space.
for phdr in elf.program_headers() {
if phdr.p_type != PT_LOAD {
continue;
}
let area_type = if phdr.p_filesz > 0 {
VmAreaType::File {
file: executable.clone(),
offset: phdr.p_offset as usize,
file_size: phdr.p_filesz as usize,
}
} else {
VmAreaType::Anonymous
};
vm.add_vm_area(
UserVAddr::new_nonnull(phdr.p_vaddr as usize)?,
phdr.p_memsz as usize,
area_type,
)?;
}
Ok(UserspaceEntry { vm, ip, user_sp })
}
|
#[doc = "Register `CR2` reader"]
pub type R = crate::R<CR2_SPEC>;
#[doc = "Register `CR2` writer"]
pub type W = crate::W<CR2_SPEC>;
#[doc = "Field `ADON` reader - A/D Converter ON / OFF"]
pub type ADON_R = crate::BitReader<ADON_A>;
#[doc = "A/D Converter ON / OFF\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ADON_A {
#[doc = "0: Disable ADC conversion and go to power down mode"]
Disabled = 0,
#[doc = "1: Enable ADC"]
Enabled = 1,
}
impl From<ADON_A> for bool {
#[inline(always)]
fn from(variant: ADON_A) -> Self {
variant as u8 != 0
}
}
impl ADON_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADON_A {
match self.bits {
false => ADON_A::Disabled,
true => ADON_A::Enabled,
}
}
#[doc = "Disable ADC conversion and go to power down mode"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ADON_A::Disabled
}
#[doc = "Enable ADC"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ADON_A::Enabled
}
}
#[doc = "Field `ADON` writer - A/D Converter ON / OFF"]
pub type ADON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ADON_A>;
impl<'a, REG, const O: u8> ADON_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Disable ADC conversion and go to power down mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ADON_A::Disabled)
}
#[doc = "Enable ADC"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ADON_A::Enabled)
}
}
#[doc = "Field `CONT` reader - Continuous conversion"]
pub type CONT_R = crate::BitReader<CONT_A>;
#[doc = "Continuous conversion\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CONT_A {
#[doc = "0: Single conversion mode"]
Single = 0,
#[doc = "1: Continuous conversion mode"]
Continuous = 1,
}
impl From<CONT_A> for bool {
#[inline(always)]
fn from(variant: CONT_A) -> Self {
variant as u8 != 0
}
}
impl CONT_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CONT_A {
match self.bits {
false => CONT_A::Single,
true => CONT_A::Continuous,
}
}
#[doc = "Single conversion mode"]
#[inline(always)]
pub fn is_single(&self) -> bool {
*self == CONT_A::Single
}
#[doc = "Continuous conversion mode"]
#[inline(always)]
pub fn is_continuous(&self) -> bool {
*self == CONT_A::Continuous
}
}
#[doc = "Field `CONT` writer - Continuous conversion"]
pub type CONT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CONT_A>;
impl<'a, REG, const O: u8> CONT_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Single conversion mode"]
#[inline(always)]
pub fn single(self) -> &'a mut crate::W<REG> {
self.variant(CONT_A::Single)
}
#[doc = "Continuous conversion mode"]
#[inline(always)]
pub fn continuous(self) -> &'a mut crate::W<REG> {
self.variant(CONT_A::Continuous)
}
}
#[doc = "Field `DMA` reader - Direct memory access mode (for single ADC mode)"]
pub type DMA_R = crate::BitReader<DMA_A>;
#[doc = "Direct memory access mode (for single ADC mode)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DMA_A {
#[doc = "0: DMA mode disabled"]
Disabled = 0,
#[doc = "1: DMA mode enabled"]
Enabled = 1,
}
impl From<DMA_A> for bool {
#[inline(always)]
fn from(variant: DMA_A) -> Self {
variant as u8 != 0
}
}
impl DMA_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DMA_A {
match self.bits {
false => DMA_A::Disabled,
true => DMA_A::Enabled,
}
}
#[doc = "DMA mode disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DMA_A::Disabled
}
#[doc = "DMA mode enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DMA_A::Enabled
}
}
#[doc = "Field `DMA` writer - Direct memory access mode (for single ADC mode)"]
pub type DMA_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DMA_A>;
impl<'a, REG, const O: u8> DMA_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "DMA mode disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DMA_A::Disabled)
}
#[doc = "DMA mode enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DMA_A::Enabled)
}
}
#[doc = "Field `DDS` reader - DMA disable selection (for single ADC mode)"]
pub type DDS_R = crate::BitReader<DDS_A>;
#[doc = "DMA disable selection (for single ADC mode)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DDS_A {
#[doc = "0: No new DMA request is issued after the last transfer"]
Single = 0,
#[doc = "1: DMA requests are issued as long as data are converted and DMA=1"]
Continuous = 1,
}
impl From<DDS_A> for bool {
#[inline(always)]
fn from(variant: DDS_A) -> Self {
variant as u8 != 0
}
}
impl DDS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DDS_A {
match self.bits {
false => DDS_A::Single,
true => DDS_A::Continuous,
}
}
#[doc = "No new DMA request is issued after the last transfer"]
#[inline(always)]
pub fn is_single(&self) -> bool {
*self == DDS_A::Single
}
#[doc = "DMA requests are issued as long as data are converted and DMA=1"]
#[inline(always)]
pub fn is_continuous(&self) -> bool {
*self == DDS_A::Continuous
}
}
#[doc = "Field `DDS` writer - DMA disable selection (for single ADC mode)"]
pub type DDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DDS_A>;
impl<'a, REG, const O: u8> DDS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No new DMA request is issued after the last transfer"]
#[inline(always)]
pub fn single(self) -> &'a mut crate::W<REG> {
self.variant(DDS_A::Single)
}
#[doc = "DMA requests are issued as long as data are converted and DMA=1"]
#[inline(always)]
pub fn continuous(self) -> &'a mut crate::W<REG> {
self.variant(DDS_A::Continuous)
}
}
#[doc = "Field `EOCS` reader - End of conversion selection"]
pub type EOCS_R = crate::BitReader<EOCS_A>;
#[doc = "End of conversion selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EOCS_A {
#[doc = "0: The EOC bit is set at the end of each sequence of regular conversions"]
EachSequence = 0,
#[doc = "1: The EOC bit is set at the end of each regular conversion"]
EachConversion = 1,
}
impl From<EOCS_A> for bool {
#[inline(always)]
fn from(variant: EOCS_A) -> Self {
variant as u8 != 0
}
}
impl EOCS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EOCS_A {
match self.bits {
false => EOCS_A::EachSequence,
true => EOCS_A::EachConversion,
}
}
#[doc = "The EOC bit is set at the end of each sequence of regular conversions"]
#[inline(always)]
pub fn is_each_sequence(&self) -> bool {
*self == EOCS_A::EachSequence
}
#[doc = "The EOC bit is set at the end of each regular conversion"]
#[inline(always)]
pub fn is_each_conversion(&self) -> bool {
*self == EOCS_A::EachConversion
}
}
#[doc = "Field `EOCS` writer - End of conversion selection"]
pub type EOCS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EOCS_A>;
impl<'a, REG, const O: u8> EOCS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "The EOC bit is set at the end of each sequence of regular conversions"]
#[inline(always)]
pub fn each_sequence(self) -> &'a mut crate::W<REG> {
self.variant(EOCS_A::EachSequence)
}
#[doc = "The EOC bit is set at the end of each regular conversion"]
#[inline(always)]
pub fn each_conversion(self) -> &'a mut crate::W<REG> {
self.variant(EOCS_A::EachConversion)
}
}
#[doc = "Field `ALIGN` reader - Data alignment"]
pub type ALIGN_R = crate::BitReader<ALIGN_A>;
#[doc = "Data alignment\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ALIGN_A {
#[doc = "0: Right alignment"]
Right = 0,
#[doc = "1: Left alignment"]
Left = 1,
}
impl From<ALIGN_A> for bool {
#[inline(always)]
fn from(variant: ALIGN_A) -> Self {
variant as u8 != 0
}
}
impl ALIGN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ALIGN_A {
match self.bits {
false => ALIGN_A::Right,
true => ALIGN_A::Left,
}
}
#[doc = "Right alignment"]
#[inline(always)]
pub fn is_right(&self) -> bool {
*self == ALIGN_A::Right
}
#[doc = "Left alignment"]
#[inline(always)]
pub fn is_left(&self) -> bool {
*self == ALIGN_A::Left
}
}
#[doc = "Field `ALIGN` writer - Data alignment"]
pub type ALIGN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ALIGN_A>;
impl<'a, REG, const O: u8> ALIGN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Right alignment"]
#[inline(always)]
pub fn right(self) -> &'a mut crate::W<REG> {
self.variant(ALIGN_A::Right)
}
#[doc = "Left alignment"]
#[inline(always)]
pub fn left(self) -> &'a mut crate::W<REG> {
self.variant(ALIGN_A::Left)
}
}
#[doc = "Field `JEXTSEL` reader - External event select for injected group"]
pub type JEXTSEL_R = crate::FieldReader<JEXTSEL_A>;
#[doc = "External event select for injected group\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum JEXTSEL_A {
#[doc = "0: Timer 1 CC4 event"]
Tim1cc4 = 0,
#[doc = "1: Timer 1 TRGO event"]
Tim1trgo = 1,
#[doc = "2: Timer 2 CC1 event"]
Tim2cc1 = 2,
#[doc = "3: Timer 2 TRGO event"]
Tim2trgo = 3,
#[doc = "4: Timer 3 CC2 event"]
Tim3cc2 = 4,
#[doc = "5: Timer 3 CC4 event"]
Tim3cc4 = 5,
#[doc = "6: Timer 4 CC1 event"]
Tim4cc1 = 6,
#[doc = "7: Timer 4 CC2 event"]
Tim4cc2 = 7,
#[doc = "8: Timer 4 CC3 event"]
Tim4cc3 = 8,
#[doc = "9: Timer 4 TRGO event"]
Tim4trgo = 9,
#[doc = "10: Timer 5 CC4 event"]
Tim5cc4 = 10,
#[doc = "11: Timer 5 TRGO event"]
Tim5trgo = 11,
#[doc = "12: Timer 8 CC2 event"]
Tim8cc2 = 12,
#[doc = "13: Timer 8 CC3 event"]
Tim8cc3 = 13,
#[doc = "14: Timer 8 CC4 event"]
Tim8cc4 = 14,
#[doc = "15: EXTI line 15"]
Exti15 = 15,
}
impl From<JEXTSEL_A> for u8 {
#[inline(always)]
fn from(variant: JEXTSEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for JEXTSEL_A {
type Ux = u8;
}
impl JEXTSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> JEXTSEL_A {
match self.bits {
0 => JEXTSEL_A::Tim1cc4,
1 => JEXTSEL_A::Tim1trgo,
2 => JEXTSEL_A::Tim2cc1,
3 => JEXTSEL_A::Tim2trgo,
4 => JEXTSEL_A::Tim3cc2,
5 => JEXTSEL_A::Tim3cc4,
6 => JEXTSEL_A::Tim4cc1,
7 => JEXTSEL_A::Tim4cc2,
8 => JEXTSEL_A::Tim4cc3,
9 => JEXTSEL_A::Tim4trgo,
10 => JEXTSEL_A::Tim5cc4,
11 => JEXTSEL_A::Tim5trgo,
12 => JEXTSEL_A::Tim8cc2,
13 => JEXTSEL_A::Tim8cc3,
14 => JEXTSEL_A::Tim8cc4,
15 => JEXTSEL_A::Exti15,
_ => unreachable!(),
}
}
#[doc = "Timer 1 CC4 event"]
#[inline(always)]
pub fn is_tim1cc4(&self) -> bool {
*self == JEXTSEL_A::Tim1cc4
}
#[doc = "Timer 1 TRGO event"]
#[inline(always)]
pub fn is_tim1trgo(&self) -> bool {
*self == JEXTSEL_A::Tim1trgo
}
#[doc = "Timer 2 CC1 event"]
#[inline(always)]
pub fn is_tim2cc1(&self) -> bool {
*self == JEXTSEL_A::Tim2cc1
}
#[doc = "Timer 2 TRGO event"]
#[inline(always)]
pub fn is_tim2trgo(&self) -> bool {
*self == JEXTSEL_A::Tim2trgo
}
#[doc = "Timer 3 CC2 event"]
#[inline(always)]
pub fn is_tim3cc2(&self) -> bool {
*self == JEXTSEL_A::Tim3cc2
}
#[doc = "Timer 3 CC4 event"]
#[inline(always)]
pub fn is_tim3cc4(&self) -> bool {
*self == JEXTSEL_A::Tim3cc4
}
#[doc = "Timer 4 CC1 event"]
#[inline(always)]
pub fn is_tim4cc1(&self) -> bool {
*self == JEXTSEL_A::Tim4cc1
}
#[doc = "Timer 4 CC2 event"]
#[inline(always)]
pub fn is_tim4cc2(&self) -> bool {
*self == JEXTSEL_A::Tim4cc2
}
#[doc = "Timer 4 CC3 event"]
#[inline(always)]
pub fn is_tim4cc3(&self) -> bool {
*self == JEXTSEL_A::Tim4cc3
}
#[doc = "Timer 4 TRGO event"]
#[inline(always)]
pub fn is_tim4trgo(&self) -> bool {
*self == JEXTSEL_A::Tim4trgo
}
#[doc = "Timer 5 CC4 event"]
#[inline(always)]
pub fn is_tim5cc4(&self) -> bool {
*self == JEXTSEL_A::Tim5cc4
}
#[doc = "Timer 5 TRGO event"]
#[inline(always)]
pub fn is_tim5trgo(&self) -> bool {
*self == JEXTSEL_A::Tim5trgo
}
#[doc = "Timer 8 CC2 event"]
#[inline(always)]
pub fn is_tim8cc2(&self) -> bool {
*self == JEXTSEL_A::Tim8cc2
}
#[doc = "Timer 8 CC3 event"]
#[inline(always)]
pub fn is_tim8cc3(&self) -> bool {
*self == JEXTSEL_A::Tim8cc3
}
#[doc = "Timer 8 CC4 event"]
#[inline(always)]
pub fn is_tim8cc4(&self) -> bool {
*self == JEXTSEL_A::Tim8cc4
}
#[doc = "EXTI line 15"]
#[inline(always)]
pub fn is_exti15(&self) -> bool {
*self == JEXTSEL_A::Exti15
}
}
#[doc = "Field `JEXTSEL` writer - External event select for injected group"]
pub type JEXTSEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, JEXTSEL_A>;
impl<'a, REG, const O: u8> JEXTSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Timer 1 CC4 event"]
#[inline(always)]
pub fn tim1cc4(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim1cc4)
}
#[doc = "Timer 1 TRGO event"]
#[inline(always)]
pub fn tim1trgo(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim1trgo)
}
#[doc = "Timer 2 CC1 event"]
#[inline(always)]
pub fn tim2cc1(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim2cc1)
}
#[doc = "Timer 2 TRGO event"]
#[inline(always)]
pub fn tim2trgo(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim2trgo)
}
#[doc = "Timer 3 CC2 event"]
#[inline(always)]
pub fn tim3cc2(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim3cc2)
}
#[doc = "Timer 3 CC4 event"]
#[inline(always)]
pub fn tim3cc4(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim3cc4)
}
#[doc = "Timer 4 CC1 event"]
#[inline(always)]
pub fn tim4cc1(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim4cc1)
}
#[doc = "Timer 4 CC2 event"]
#[inline(always)]
pub fn tim4cc2(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim4cc2)
}
#[doc = "Timer 4 CC3 event"]
#[inline(always)]
pub fn tim4cc3(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim4cc3)
}
#[doc = "Timer 4 TRGO event"]
#[inline(always)]
pub fn tim4trgo(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim4trgo)
}
#[doc = "Timer 5 CC4 event"]
#[inline(always)]
pub fn tim5cc4(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim5cc4)
}
#[doc = "Timer 5 TRGO event"]
#[inline(always)]
pub fn tim5trgo(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim5trgo)
}
#[doc = "Timer 8 CC2 event"]
#[inline(always)]
pub fn tim8cc2(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim8cc2)
}
#[doc = "Timer 8 CC3 event"]
#[inline(always)]
pub fn tim8cc3(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim8cc3)
}
#[doc = "Timer 8 CC4 event"]
#[inline(always)]
pub fn tim8cc4(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Tim8cc4)
}
#[doc = "EXTI line 15"]
#[inline(always)]
pub fn exti15(self) -> &'a mut crate::W<REG> {
self.variant(JEXTSEL_A::Exti15)
}
}
#[doc = "Field `JEXTEN` reader - External trigger enable for injected channels"]
pub type JEXTEN_R = crate::FieldReader<JEXTEN_A>;
#[doc = "External trigger enable for injected channels\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum JEXTEN_A {
#[doc = "0: Trigger detection disabled"]
Disabled = 0,
#[doc = "1: Trigger detection on the rising edge"]
RisingEdge = 1,
#[doc = "2: Trigger detection on the falling edge"]
FallingEdge = 2,
#[doc = "3: Trigger detection on both the rising and falling edges"]
BothEdges = 3,
}
impl From<JEXTEN_A> for u8 {
#[inline(always)]
fn from(variant: JEXTEN_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for JEXTEN_A {
type Ux = u8;
}
impl JEXTEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> JEXTEN_A {
match self.bits {
0 => JEXTEN_A::Disabled,
1 => JEXTEN_A::RisingEdge,
2 => JEXTEN_A::FallingEdge,
3 => JEXTEN_A::BothEdges,
_ => unreachable!(),
}
}
#[doc = "Trigger detection disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == JEXTEN_A::Disabled
}
#[doc = "Trigger detection on the rising edge"]
#[inline(always)]
pub fn is_rising_edge(&self) -> bool {
*self == JEXTEN_A::RisingEdge
}
#[doc = "Trigger detection on the falling edge"]
#[inline(always)]
pub fn is_falling_edge(&self) -> bool {
*self == JEXTEN_A::FallingEdge
}
#[doc = "Trigger detection on both the rising and falling edges"]
#[inline(always)]
pub fn is_both_edges(&self) -> bool {
*self == JEXTEN_A::BothEdges
}
}
#[doc = "Field `JEXTEN` writer - External trigger enable for injected channels"]
pub type JEXTEN_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, JEXTEN_A>;
impl<'a, REG, const O: u8> JEXTEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Trigger detection disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(JEXTEN_A::Disabled)
}
#[doc = "Trigger detection on the rising edge"]
#[inline(always)]
pub fn rising_edge(self) -> &'a mut crate::W<REG> {
self.variant(JEXTEN_A::RisingEdge)
}
#[doc = "Trigger detection on the falling edge"]
#[inline(always)]
pub fn falling_edge(self) -> &'a mut crate::W<REG> {
self.variant(JEXTEN_A::FallingEdge)
}
#[doc = "Trigger detection on both the rising and falling edges"]
#[inline(always)]
pub fn both_edges(self) -> &'a mut crate::W<REG> {
self.variant(JEXTEN_A::BothEdges)
}
}
#[doc = "Field `JSWSTART` reader - Start conversion of injected channels"]
pub type JSWSTART_R = crate::BitReader<JSWSTARTW_A>;
#[doc = "Start conversion of injected channels\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JSWSTARTW_A {
#[doc = "1: Starts conversion of injected channels"]
Start = 1,
}
impl From<JSWSTARTW_A> for bool {
#[inline(always)]
fn from(variant: JSWSTARTW_A) -> Self {
variant as u8 != 0
}
}
impl JSWSTART_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<JSWSTARTW_A> {
match self.bits {
true => Some(JSWSTARTW_A::Start),
_ => None,
}
}
#[doc = "Starts conversion of injected channels"]
#[inline(always)]
pub fn is_start(&self) -> bool {
*self == JSWSTARTW_A::Start
}
}
#[doc = "Field `JSWSTART` writer - Start conversion of injected channels"]
pub type JSWSTART_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, JSWSTARTW_A>;
impl<'a, REG, const O: u8> JSWSTART_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Starts conversion of injected channels"]
#[inline(always)]
pub fn start(self) -> &'a mut crate::W<REG> {
self.variant(JSWSTARTW_A::Start)
}
}
#[doc = "Field `EXTSEL` reader - External event select for regular group"]
pub type EXTSEL_R = crate::FieldReader<EXTSEL_A>;
#[doc = "External event select for regular group\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum EXTSEL_A {
#[doc = "0: Timer 1 CC1 event"]
Tim1cc1 = 0,
#[doc = "1: Timer 1 CC2 event"]
Tim1cc2 = 1,
#[doc = "2: Timer 1 CC3 event"]
Tim1cc3 = 2,
#[doc = "3: Timer 2 CC2 event"]
Tim2cc2 = 3,
#[doc = "4: Timer 2 CC3 event"]
Tim2cc3 = 4,
#[doc = "5: Timer 2 CC4 event"]
Tim2cc4 = 5,
#[doc = "6: Timer 2 TRGO event"]
Tim2trgo = 6,
#[doc = "7: Timer 3 CC1 event"]
Tim3cc1 = 7,
#[doc = "8: Timer 3 TRGO event"]
Tim3trgo = 8,
#[doc = "9: Timer 4 CC4 event"]
Tim4cc4 = 9,
#[doc = "10: Timer 5 CC1 event"]
Tim5cc1 = 10,
#[doc = "11: Timer 5 CC2 event"]
Tim5cc2 = 11,
#[doc = "12: Timer 5 CC3 event"]
Tim5cc3 = 12,
#[doc = "13: Timer 8 CC1 event"]
Tim8cc1 = 13,
#[doc = "14: Timer 8 TRGO event"]
Tim8trgo = 14,
#[doc = "15: EXTI line 11"]
Exti11 = 15,
}
impl From<EXTSEL_A> for u8 {
#[inline(always)]
fn from(variant: EXTSEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for EXTSEL_A {
type Ux = u8;
}
impl EXTSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EXTSEL_A {
match self.bits {
0 => EXTSEL_A::Tim1cc1,
1 => EXTSEL_A::Tim1cc2,
2 => EXTSEL_A::Tim1cc3,
3 => EXTSEL_A::Tim2cc2,
4 => EXTSEL_A::Tim2cc3,
5 => EXTSEL_A::Tim2cc4,
6 => EXTSEL_A::Tim2trgo,
7 => EXTSEL_A::Tim3cc1,
8 => EXTSEL_A::Tim3trgo,
9 => EXTSEL_A::Tim4cc4,
10 => EXTSEL_A::Tim5cc1,
11 => EXTSEL_A::Tim5cc2,
12 => EXTSEL_A::Tim5cc3,
13 => EXTSEL_A::Tim8cc1,
14 => EXTSEL_A::Tim8trgo,
15 => EXTSEL_A::Exti11,
_ => unreachable!(),
}
}
#[doc = "Timer 1 CC1 event"]
#[inline(always)]
pub fn is_tim1cc1(&self) -> bool {
*self == EXTSEL_A::Tim1cc1
}
#[doc = "Timer 1 CC2 event"]
#[inline(always)]
pub fn is_tim1cc2(&self) -> bool {
*self == EXTSEL_A::Tim1cc2
}
#[doc = "Timer 1 CC3 event"]
#[inline(always)]
pub fn is_tim1cc3(&self) -> bool {
*self == EXTSEL_A::Tim1cc3
}
#[doc = "Timer 2 CC2 event"]
#[inline(always)]
pub fn is_tim2cc2(&self) -> bool {
*self == EXTSEL_A::Tim2cc2
}
#[doc = "Timer 2 CC3 event"]
#[inline(always)]
pub fn is_tim2cc3(&self) -> bool {
*self == EXTSEL_A::Tim2cc3
}
#[doc = "Timer 2 CC4 event"]
#[inline(always)]
pub fn is_tim2cc4(&self) -> bool {
*self == EXTSEL_A::Tim2cc4
}
#[doc = "Timer 2 TRGO event"]
#[inline(always)]
pub fn is_tim2trgo(&self) -> bool {
*self == EXTSEL_A::Tim2trgo
}
#[doc = "Timer 3 CC1 event"]
#[inline(always)]
pub fn is_tim3cc1(&self) -> bool {
*self == EXTSEL_A::Tim3cc1
}
#[doc = "Timer 3 TRGO event"]
#[inline(always)]
pub fn is_tim3trgo(&self) -> bool {
*self == EXTSEL_A::Tim3trgo
}
#[doc = "Timer 4 CC4 event"]
#[inline(always)]
pub fn is_tim4cc4(&self) -> bool {
*self == EXTSEL_A::Tim4cc4
}
#[doc = "Timer 5 CC1 event"]
#[inline(always)]
pub fn is_tim5cc1(&self) -> bool {
*self == EXTSEL_A::Tim5cc1
}
#[doc = "Timer 5 CC2 event"]
#[inline(always)]
pub fn is_tim5cc2(&self) -> bool {
*self == EXTSEL_A::Tim5cc2
}
#[doc = "Timer 5 CC3 event"]
#[inline(always)]
pub fn is_tim5cc3(&self) -> bool {
*self == EXTSEL_A::Tim5cc3
}
#[doc = "Timer 8 CC1 event"]
#[inline(always)]
pub fn is_tim8cc1(&self) -> bool {
*self == EXTSEL_A::Tim8cc1
}
#[doc = "Timer 8 TRGO event"]
#[inline(always)]
pub fn is_tim8trgo(&self) -> bool {
*self == EXTSEL_A::Tim8trgo
}
#[doc = "EXTI line 11"]
#[inline(always)]
pub fn is_exti11(&self) -> bool {
*self == EXTSEL_A::Exti11
}
}
#[doc = "Field `EXTSEL` writer - External event select for regular group"]
pub type EXTSEL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, EXTSEL_A>;
impl<'a, REG, const O: u8> EXTSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Timer 1 CC1 event"]
#[inline(always)]
pub fn tim1cc1(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim1cc1)
}
#[doc = "Timer 1 CC2 event"]
#[inline(always)]
pub fn tim1cc2(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim1cc2)
}
#[doc = "Timer 1 CC3 event"]
#[inline(always)]
pub fn tim1cc3(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim1cc3)
}
#[doc = "Timer 2 CC2 event"]
#[inline(always)]
pub fn tim2cc2(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim2cc2)
}
#[doc = "Timer 2 CC3 event"]
#[inline(always)]
pub fn tim2cc3(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim2cc3)
}
#[doc = "Timer 2 CC4 event"]
#[inline(always)]
pub fn tim2cc4(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim2cc4)
}
#[doc = "Timer 2 TRGO event"]
#[inline(always)]
pub fn tim2trgo(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim2trgo)
}
#[doc = "Timer 3 CC1 event"]
#[inline(always)]
pub fn tim3cc1(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim3cc1)
}
#[doc = "Timer 3 TRGO event"]
#[inline(always)]
pub fn tim3trgo(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim3trgo)
}
#[doc = "Timer 4 CC4 event"]
#[inline(always)]
pub fn tim4cc4(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim4cc4)
}
#[doc = "Timer 5 CC1 event"]
#[inline(always)]
pub fn tim5cc1(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim5cc1)
}
#[doc = "Timer 5 CC2 event"]
#[inline(always)]
pub fn tim5cc2(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim5cc2)
}
#[doc = "Timer 5 CC3 event"]
#[inline(always)]
pub fn tim5cc3(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim5cc3)
}
#[doc = "Timer 8 CC1 event"]
#[inline(always)]
pub fn tim8cc1(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim8cc1)
}
#[doc = "Timer 8 TRGO event"]
#[inline(always)]
pub fn tim8trgo(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Tim8trgo)
}
#[doc = "EXTI line 11"]
#[inline(always)]
pub fn exti11(self) -> &'a mut crate::W<REG> {
self.variant(EXTSEL_A::Exti11)
}
}
#[doc = "Field `EXTEN` reader - External trigger enable for regular channels"]
pub type EXTEN_R = crate::FieldReader<EXTEN_A>;
#[doc = "External trigger enable for regular channels\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum EXTEN_A {
#[doc = "0: Trigger detection disabled"]
Disabled = 0,
#[doc = "1: Trigger detection on the rising edge"]
RisingEdge = 1,
#[doc = "2: Trigger detection on the falling edge"]
FallingEdge = 2,
#[doc = "3: Trigger detection on both the rising and falling edges"]
BothEdges = 3,
}
impl From<EXTEN_A> for u8 {
#[inline(always)]
fn from(variant: EXTEN_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for EXTEN_A {
type Ux = u8;
}
impl EXTEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EXTEN_A {
match self.bits {
0 => EXTEN_A::Disabled,
1 => EXTEN_A::RisingEdge,
2 => EXTEN_A::FallingEdge,
3 => EXTEN_A::BothEdges,
_ => unreachable!(),
}
}
#[doc = "Trigger detection disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EXTEN_A::Disabled
}
#[doc = "Trigger detection on the rising edge"]
#[inline(always)]
pub fn is_rising_edge(&self) -> bool {
*self == EXTEN_A::RisingEdge
}
#[doc = "Trigger detection on the falling edge"]
#[inline(always)]
pub fn is_falling_edge(&self) -> bool {
*self == EXTEN_A::FallingEdge
}
#[doc = "Trigger detection on both the rising and falling edges"]
#[inline(always)]
pub fn is_both_edges(&self) -> bool {
*self == EXTEN_A::BothEdges
}
}
#[doc = "Field `EXTEN` writer - External trigger enable for regular channels"]
pub type EXTEN_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, EXTEN_A>;
impl<'a, REG, const O: u8> EXTEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Trigger detection disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(EXTEN_A::Disabled)
}
#[doc = "Trigger detection on the rising edge"]
#[inline(always)]
pub fn rising_edge(self) -> &'a mut crate::W<REG> {
self.variant(EXTEN_A::RisingEdge)
}
#[doc = "Trigger detection on the falling edge"]
#[inline(always)]
pub fn falling_edge(self) -> &'a mut crate::W<REG> {
self.variant(EXTEN_A::FallingEdge)
}
#[doc = "Trigger detection on both the rising and falling edges"]
#[inline(always)]
pub fn both_edges(self) -> &'a mut crate::W<REG> {
self.variant(EXTEN_A::BothEdges)
}
}
#[doc = "Field `SWSTART` reader - Start conversion of regular channels"]
pub type SWSTART_R = crate::BitReader<SWSTARTW_A>;
#[doc = "Start conversion of regular channels\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SWSTARTW_A {
#[doc = "1: Starts conversion of regular channels"]
Start = 1,
}
impl From<SWSTARTW_A> for bool {
#[inline(always)]
fn from(variant: SWSTARTW_A) -> Self {
variant as u8 != 0
}
}
impl SWSTART_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SWSTARTW_A> {
match self.bits {
true => Some(SWSTARTW_A::Start),
_ => None,
}
}
#[doc = "Starts conversion of regular channels"]
#[inline(always)]
pub fn is_start(&self) -> bool {
*self == SWSTARTW_A::Start
}
}
#[doc = "Field `SWSTART` writer - Start conversion of regular channels"]
pub type SWSTART_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SWSTARTW_A>;
impl<'a, REG, const O: u8> SWSTART_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Starts conversion of regular channels"]
#[inline(always)]
pub fn start(self) -> &'a mut crate::W<REG> {
self.variant(SWSTARTW_A::Start)
}
}
impl R {
#[doc = "Bit 0 - A/D Converter ON / OFF"]
#[inline(always)]
pub fn adon(&self) -> ADON_R {
ADON_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Continuous conversion"]
#[inline(always)]
pub fn cont(&self) -> CONT_R {
CONT_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 8 - Direct memory access mode (for single ADC mode)"]
#[inline(always)]
pub fn dma(&self) -> DMA_R {
DMA_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - DMA disable selection (for single ADC mode)"]
#[inline(always)]
pub fn dds(&self) -> DDS_R {
DDS_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - End of conversion selection"]
#[inline(always)]
pub fn eocs(&self) -> EOCS_R {
EOCS_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Data alignment"]
#[inline(always)]
pub fn align(&self) -> ALIGN_R {
ALIGN_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bits 16:19 - External event select for injected group"]
#[inline(always)]
pub fn jextsel(&self) -> JEXTSEL_R {
JEXTSEL_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:21 - External trigger enable for injected channels"]
#[inline(always)]
pub fn jexten(&self) -> JEXTEN_R {
JEXTEN_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bit 22 - Start conversion of injected channels"]
#[inline(always)]
pub fn jswstart(&self) -> JSWSTART_R {
JSWSTART_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bits 24:27 - External event select for regular group"]
#[inline(always)]
pub fn extsel(&self) -> EXTSEL_R {
EXTSEL_R::new(((self.bits >> 24) & 0x0f) as u8)
}
#[doc = "Bits 28:29 - External trigger enable for regular channels"]
#[inline(always)]
pub fn exten(&self) -> EXTEN_R {
EXTEN_R::new(((self.bits >> 28) & 3) as u8)
}
#[doc = "Bit 30 - Start conversion of regular channels"]
#[inline(always)]
pub fn swstart(&self) -> SWSTART_R {
SWSTART_R::new(((self.bits >> 30) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - A/D Converter ON / OFF"]
#[inline(always)]
#[must_use]
pub fn adon(&mut self) -> ADON_W<CR2_SPEC, 0> {
ADON_W::new(self)
}
#[doc = "Bit 1 - Continuous conversion"]
#[inline(always)]
#[must_use]
pub fn cont(&mut self) -> CONT_W<CR2_SPEC, 1> {
CONT_W::new(self)
}
#[doc = "Bit 8 - Direct memory access mode (for single ADC mode)"]
#[inline(always)]
#[must_use]
pub fn dma(&mut self) -> DMA_W<CR2_SPEC, 8> {
DMA_W::new(self)
}
#[doc = "Bit 9 - DMA disable selection (for single ADC mode)"]
#[inline(always)]
#[must_use]
pub fn dds(&mut self) -> DDS_W<CR2_SPEC, 9> {
DDS_W::new(self)
}
#[doc = "Bit 10 - End of conversion selection"]
#[inline(always)]
#[must_use]
pub fn eocs(&mut self) -> EOCS_W<CR2_SPEC, 10> {
EOCS_W::new(self)
}
#[doc = "Bit 11 - Data alignment"]
#[inline(always)]
#[must_use]
pub fn align(&mut self) -> ALIGN_W<CR2_SPEC, 11> {
ALIGN_W::new(self)
}
#[doc = "Bits 16:19 - External event select for injected group"]
#[inline(always)]
#[must_use]
pub fn jextsel(&mut self) -> JEXTSEL_W<CR2_SPEC, 16> {
JEXTSEL_W::new(self)
}
#[doc = "Bits 20:21 - External trigger enable for injected channels"]
#[inline(always)]
#[must_use]
pub fn jexten(&mut self) -> JEXTEN_W<CR2_SPEC, 20> {
JEXTEN_W::new(self)
}
#[doc = "Bit 22 - Start conversion of injected channels"]
#[inline(always)]
#[must_use]
pub fn jswstart(&mut self) -> JSWSTART_W<CR2_SPEC, 22> {
JSWSTART_W::new(self)
}
#[doc = "Bits 24:27 - External event select for regular group"]
#[inline(always)]
#[must_use]
pub fn extsel(&mut self) -> EXTSEL_W<CR2_SPEC, 24> {
EXTSEL_W::new(self)
}
#[doc = "Bits 28:29 - External trigger enable for regular channels"]
#[inline(always)]
#[must_use]
pub fn exten(&mut self) -> EXTEN_W<CR2_SPEC, 28> {
EXTEN_W::new(self)
}
#[doc = "Bit 30 - Start conversion of regular channels"]
#[inline(always)]
#[must_use]
pub fn swstart(&mut self) -> SWSTART_W<CR2_SPEC, 30> {
SWSTART_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CR2_SPEC;
impl crate::RegisterSpec for CR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cr2::R`](R) reader structure"]
impl crate::Readable for CR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cr2::W`](W) writer structure"]
impl crate::Writable for CR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CR2 to value 0"]
impl crate::Resettable for CR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::extensions::NodeExt as _;
use gdnative::prelude::*;
#[derive(NativeClass)]
#[inherit(CanvasLayer)]
#[user_data(user_data::ArcData<HUD>)]
#[register_with(Self::register_hud)]
/// Game state struct.
pub struct HUD;
#[methods]
impl HUD {
/// Create a new HUD.
pub fn new(_owner: &CanvasLayer) -> Self {
HUD
}
/// Register HUD.
pub fn register_hud(builder: &ClassBuilder<Self>) {
// This signal tells that the start button has been pressed
builder.add_signal(Signal { name: "start_game", args: &[] });
}
#[export]
/// Prepare the HUD.
pub fn _ready(&self, owner: &CanvasLayer) {
// Hide score label
unsafe { owner.get_typed_node::<Label, _>("ScoreLabel") }.hide();
}
#[export]
/// Show a message.
pub fn show_message(&self, owner: &CanvasLayer, text: String) {
// Get message label
let label = unsafe { owner.get_typed_node::<Label, _>("MessageLabel") };
label.set_text(text);
label.show();
// Start message timer
unsafe { owner.get_typed_node::<Timer, _>("MessageTimer") }.start(0.0);
}
#[export]
/// Show the game over message.
pub fn show_game_over(&self, owner: &CanvasLayer) {
// Show message
self.show_message(owner, "Game Over".into());
// Stop message timer
unsafe { owner.get_typed_node::<Timer, _>("MessageTimer") }.stop();
// Show start button
unsafe { owner.get_typed_node::<Button, _>("StartButton") }.show();
// Show game title
let label = unsafe { owner.get_typed_node::<Label, _>("MessageLabel") };
label.set_text("Dodge the Creeps!");
label.show();
}
#[export]
pub fn update_score(&self, owner: &CanvasLayer, score: u16) {
// Update score label
unsafe { owner.get_typed_node::<Label, _>("ScoreLabel") }
.set_text(score.to_string());
}
#[export]
/// Start the game.
pub fn on_start_button_pressed(&self, owner: &CanvasLayer) {
// Hide start button
unsafe { owner.get_typed_node::<Button, _>("StartButton") }.hide();
// Show score label
unsafe { owner.get_typed_node::<Label, _>("ScoreLabel") }.show();
// Emit start game signal
owner.emit_signal("start_game", &[]);
}
#[export]
/// Start the game.
pub fn on_message_timer_timeout(&self, owner: &CanvasLayer) {
// Hide start button
unsafe { owner.get_typed_node::<Label, _>("MessageLabel") }.hide();
}
}
|
use radix::node::Node;
use std::cmp::Ordering;
use std::mem;
pub type Tree<T> = Option<Box<Node<T>>>;
pub fn insert<T>(tree: &mut Tree<T>, mut key: &[u8], value: T) -> Option<T> {
let node = tree.as_mut().expect("Expected non-empty tree.");
let split_index = node.key
.iter()
.zip(key.iter())
.position(|pair| pair.0 != pair.1);
match split_index {
Some(split_index) => {
let mut split_key = node.key.split_off(split_index);
mem::swap(&mut split_key, &mut node.key);
let mut split = mem::replace(&mut **node, Node::new(split_key, None));
let mut child = Node::new(key.split_at(split_index).1.to_vec(), Some(value));
node.next = split.next.take();
node.insert_child(split);
node.insert_child(child);
None
},
None => {
match node.key.len().cmp(&key.len()) {
Ordering::Less => {
key = key.split_at(node.key.len()).1;
let byte = key[0];
if node.contains(byte) {
insert(node.get_mut(byte), key, value)
} else {
node.insert_child(Node::new(key.to_vec(), Some(value)));
None
}
},
Ordering::Greater => {
let mut split_key = node.key.split_off(key.len());
mem::swap(&mut split_key, &mut node.key);
let mut split = mem::replace(&mut **node, Node::new(split_key, None));
node.next = split.next.take();
node.value = Some(value);
node.insert_child(split);
None
},
Ordering::Equal => mem::replace(&mut node.value, Some(value)).map(|value| value),
}
},
}
}
pub fn remove<T>(tree: &mut Tree<T>, key: &[u8], mut index: usize) -> Option<(Vec<u8>, T)> {
let mut next_tree = None;
let ret;
{
let node = match tree {
Some(ref mut node) => node,
None => return None,
};
let split_index = node.key
.iter()
.zip(key[index..].iter())
.position(|pair| pair.0 != pair.1);
match split_index {
Some(_) => return None,
None => {
match node.key.len().cmp(&(key.len() - index)) {
Ordering::Less => {
index += node.key.len();
let byte = key[index];
ret = remove(node.get_mut(byte), key, index);
node.merge();
if node.value.is_none() && node.child.is_none() {
next_tree = Some(node.next.take());
}
},
Ordering::Greater => return None,
Ordering::Equal => {
ret = node.value.take().map(|value| (key.to_vec(), value));
node.merge();
if node.value.is_none() && node.child.is_none() {
next_tree = Some(node.next.take());
}
},
}
},
}
}
if let Some(next_tree) = next_tree {
*tree = next_tree;
}
ret
}
pub fn get<'a, T>(tree: &'a Tree<T>, key: &[u8], mut index: usize) -> Option<&'a T> {
let node = match tree {
Some(ref node) => node,
None => return None,
};
let split_index = node.key
.iter()
.zip(key[index..].iter())
.position(|pair| pair.0 != pair.1);
match split_index {
Some(_) => None,
None => {
match node.key.len().cmp(&(key.len() - index)) {
Ordering::Less => {
index += node.key.len();
get(node.get(key[index]), key, index)
},
Ordering::Greater => None,
Ordering::Equal => node.value.as_ref(),
}
},
}
}
pub fn get_mut<'a, T>(tree: &'a mut Tree<T>, key: &[u8], mut index: usize) -> Option<&'a mut T> {
let node = match tree {
Some(ref mut node) => node,
None => return None,
};
let split_index = node.key
.iter()
.zip(key[index..].iter())
.position(|pair| pair.0 != pair.1);
match split_index {
Some(_) => None,
None => {
match node.key.len().cmp(&(key.len() - index)) {
Ordering::Less => {
index += node.key.len();
get_mut(node.get_mut(key[index]), key, index)
},
Ordering::Greater => None,
Ordering::Equal => node.value.as_mut(),
}
},
}
}
fn push_all_children<T>(tree: &Tree<T>, mut curr_key: Vec<u8>, keys: &mut Vec<Vec<u8>>) {
if let Some(ref node) = tree {
let len = curr_key.len();
curr_key.extend(node.key.iter());
if node.value.is_some() {
keys.push(curr_key.clone());
}
push_all_children(&node.child, curr_key.clone(), keys);
curr_key.split_off(len);
push_all_children(&node.next, curr_key, keys);
}
}
pub fn get_longest_prefix<T>(
tree: &Tree<T>,
key: &[u8],
mut index: usize,
mut curr_key: Vec<u8>,
keys: &mut Vec<Vec<u8>>,
) {
let node = match tree {
Some(ref node) => node,
None => return,
};
curr_key.extend(node.key.iter());
let split_index = node.key
.iter()
.zip(key[index..].iter())
.position(|pair| pair.0 != pair.1);
match split_index {
Some(_) => {
if node.value.is_some() {
keys.push(curr_key.clone());
}
push_all_children(&node.child, curr_key, keys);
},
None => {
match node.key.len().cmp(&(key.len() - index)) {
Ordering::Less => {
index += node.key.len();
let next_child = node.get(key[index]);
match next_child {
Some(_) => get_longest_prefix(next_child, key, index, curr_key, keys),
None => {
if node.value.is_some() {
keys.push(curr_key.clone())
}
},
}
},
_ => {
if node.value.is_some() {
keys.push(curr_key.clone());
}
push_all_children(&node.child, curr_key, keys);
},
}
},
}
}
pub fn min<T>(tree: &Tree<T>, mut curr_key: Vec<u8>) -> Option<Vec<u8>> {
let node = match tree {
Some(ref node) => node,
None => return None,
};
curr_key.extend_from_slice(node.key.as_slice());
if node.value.is_some() {
Some(curr_key)
} else {
min(node.min(), curr_key)
}
}
pub fn max<T>(tree: &Tree<T>, mut curr_key: Vec<u8>) -> Option<Vec<u8>> {
let node = match tree {
Some(ref node) => node,
None => return None,
};
curr_key.extend_from_slice(node.key.as_slice());
if node.value.is_some() && node.child.is_none() {
Some(curr_key)
} else {
max(node.max(), curr_key)
}
}
|
/*!
## Auxiliar functions to manipulate arrays
*/
use ndarray::prelude::*;
use ndarray_linalg::generate::random;
use log::info;
use std::time::Instant;
use std::cmp::Ordering;
use approx::relative_eq;
/// Generate a random highly diagonal symmetric matrix
pub fn generate_diagonal_dominant(dim: usize, sparsity: f64) -> Array2<f64> {
let diag: Array1<f64> = 10.0 * random([dim]);
let off_diag: Array2<f64> = random((dim, dim));
let arr = &off_diag + &off_diag.t();
let mut arr = &arr * sparsity;
arr.diag_mut().assign(&diag);
arr
}
/// Random symmetric matrix
pub fn generate_random_symmetric(dim: usize, magnitude: f64) -> Array2<f64> {
let arr: Array2<f64> = random((dim, dim)) * magnitude;
arr.dot(&arr.t())
}
pub fn sort_vector<T: PartialOrd>(vs: &mut Vec<T>, ascending: bool) {
if ascending {
vs.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
} else {
vs.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
}
}
pub fn test_eigenpairs(
ref_eigenpair: (Array1<f64>, Array2<f64>),
eigenpair: (Array1<f64>, Array2<f64>),
number: usize,
) {
let (dav_eigenvalues, dav_eigenvectors) = eigenpair;
let (ref_eigenvalues, ref_eigenvectors) = ref_eigenpair;
for i in 0..number {
// Test Eigenvalues
assert!(relative_eq!(
ref_eigenvalues[i],
dav_eigenvalues[i],
epsilon = 1e-6
));
// Test Eigenvectors
let x = ref_eigenvectors.column(i);
let y = dav_eigenvectors.column(i);
// The autovectors may different in their sign
// They should be either parallel or antiparallel
let dot = x.dot(&y).abs();
assert!(relative_eq!(dot, 1.0, epsilon = 1e-6));
}
}
pub fn argsort(v: ArrayView1<f64>) -> Vec<usize> {
let mut idx = (0..v.len()).collect::<Vec<_>>();
idx.sort_unstable_by(|&i, &j| v[i].partial_cmp(&v[j]).unwrap_or(Ordering::Equal));
idx
}
pub fn print_davidson_init(max_iter: usize, nroots: usize, tolerance: f64) {
info!("{:^80}", "");
info!("{: ^80}", "Iterative Davidson Routine");
info!("{:-^80}", "");
info!("{: <25} {:4.2e}", "Energy is converged when residual is below:", tolerance);
info!("{: <25} {}", "Maximum number of iterations:", max_iter);
info!("{: >4} {: <25}", nroots, " Roots will be computed.");
info!("{:-^75} ", "");
info!(
"{: <5}{: >15}{: >15}{: >15}{: >15}",
"Iter.", "Roots conv.", "Roots left", "Total dev.", "Max dev."
);
info!("{:-^75} ", "");
}
pub fn print_davidson_iteration(iter: usize, roots_cvd: usize, roots_lft: usize, t_dev: f64, max_dev:f64) {
info!(
"{: >5}{:>15}{:>15}{:>15.8}{:>15.8}",
iter + 1,
roots_cvd,
roots_lft,
t_dev,
max_dev
);
}
pub fn print_davidson_end(result_is_ok: bool, time: Instant) {
info!("{:-^75} ", "");
if result_is_ok {
info!("Davidson routine converged")
} else {
info!("Davidson routine did not converge!")
}
info!("{:>68} {:>8.2} s",
"elapsed time:",
time.elapsed().as_secs_f32()
);
info!("{:-^80}", "");
info!("{:^80}", "");
}
#[cfg(test)]
mod test {
use ndarray::prelude::*;
#[test]
fn test_random_symmetric() {
let matrix = super::generate_random_symmetric(10, 2.5);
test_symmetric(matrix);
}
#[test]
fn test_diagonal_dominant() {
let matrix = super::generate_diagonal_dominant(10, 0.005);
test_symmetric(matrix);
}
fn test_symmetric(matrix: Array2<f64>) {
let rs = &matrix - &matrix.t();
assert!(rs.sum() < f64::EPSILON);
}
}
|
use std::collections::HashSet;
use aoc_runner_derive::{aoc, aoc_generator};
#[aoc_generator(day1)]
pub fn input_generator(input: &str) -> Vec<i32> {
input.lines().map(|l| l.parse().unwrap()).collect()
}
#[aoc(day1, part1)]
pub fn solve_part1(input: &[i32]) -> i32 {
input.iter().sum()
}
#[aoc(day1, part2)]
pub fn solve_part2(input: &[i32]) -> i32 {
let mut seen = HashSet::new();
let mut acc = 0;
for i in input.iter().cycle() {
acc += i;
if !seen.insert(acc) {
return acc;
}
}
unreachable!();
}
|
use lopdf::Dictionary;
pub fn get_object_rect(field: &Dictionary) -> Result<(f64, f64, f64, f64), lopdf::Error> {
let rect = field
.get(b"Rect")?
.as_array()?
.iter()
.map(|object| {
object
.as_f64()
.unwrap_or(object.as_i64().unwrap_or(0) as f64)
})
.collect::<Vec<_>>();
if rect.len() == 4 {
Ok((rect[0], rect[1], rect[2], rect[3]))
} else {
Err(lopdf::Error::ObjectNotFound)
}
}
|
//! **uvm_install_graph** is a helper library to visualize and traverse a unity installation manifest.
use petgraph::visit::NodeIndexable;
pub use daggy::petgraph;
use daggy::petgraph::graph::DefaultIx;
use daggy::petgraph::visit::Topo;
use daggy::Dag;
use daggy::NodeIndex;
pub use daggy::Walker;
use itertools::Itertools;
use std::collections::HashSet;
use std::fmt;
use uvm_core::unity::{Manifest, Component, Version};
/// `InstallStatus` is a marker enum to mark nodes in the `InstallGraph` based on the known
/// installation status. The default is **Unknown**.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstallStatus {
Unknown,
Missing,
Installed,
}
impl Default for InstallStatus {
fn default() -> InstallStatus {
InstallStatus::Unknown
}
}
impl fmt::Display for InstallStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstallStatus::Missing => write!(f, "missing"),
InstallStatus::Installed => write!(f, "installed"),
_ => write!(f, "unknown"),
}
}
}
type DagNode = (Component, InstallStatus);
type DagEdge = ();
type ModulesDag = Dag<DagNode, DagEdge>;
/// A simple [directed acyclic graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph)
/// representation of a unity version and it's modules. This graph allows the traversal of to
/// be installed modules in a topological order.
/// It is also possible to query submodule and or dependencies for a given module.
#[derive(Debug)]
pub struct InstallGraph<'a> {
manifest: &'a Manifest<'a>,
dag: ModulesDag,
}
impl<'a> From<&'a Manifest<'a>> for InstallGraph<'a> {
fn from(manifest: &'a Manifest<'a>) -> Self {
Self::from(manifest)
}
}
// use std::ops::Deref;
//
// impl<'a> Deref for InstallGraph<'a> {
// type Target = ModulesDag;
//
// fn deref(&self) -> &Self::Target {
// &self.dag
// }
// }
impl<'a> InstallGraph<'a> {
/// The total number of nodes in the Dag.
pub fn node_count(&self) -> usize {
self.dag.node_count()
}
pub fn keep(&mut self, modules: &HashSet<Component>) {
self.dag = self.dag.filter_map(
|_n, (module, install_status)| {
if modules.contains(&module) {
Some((*module, *install_status))
} else {
None
}
},
|_, _| Some(()),
);
}
/// Builds a Dag representation of the given **Manifest**.
pub fn from(manifest: &'a Manifest<'a>) -> Self {
let dag = Self::build_dag(&manifest);
InstallGraph {
manifest,
dag
}
}
/// Creates a `Topo` traversal struct from the current graph to walk the graph in topological order.
pub fn topo(&self) -> Topo<NodeIndex, fixedbitset::FixedBitSet> {
Topo::new(&self.dag)
}
pub fn version(&self) -> &Version {
self.manifest.version()
}
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
/// Mark all nodes with the given `InstallStatus`.
pub fn mark_all(&mut self, install_status: InstallStatus) {
self.dag = self
.dag
.map(|_, (module, _)| (*module, install_status), |_, e| (*e));
}
/// Mark all nodes as `InstallStatus::Missing`.
pub fn mark_all_missing(&mut self) {
self.mark_all(InstallStatus::Missing)
}
/// Mark all nodes contained in `modules` as `InstallStatus::Installed`.
/// If the node is not found in `modules` the node gets marked as `InstallStatus::Missing`.
pub fn mark_installed(&mut self, modules: &HashSet<Component>) {
self.dag = self.dag.filter_map(
|_n, (module, _)| {
if modules.contains(&module) {
Some((*module, InstallStatus::Installed))
} else {
Some((*module, InstallStatus::Missing))
}
},
|_, _| Some(()),
);
}
/// Returns the component for the given node index.
pub fn component(&self, node: NodeIndex) -> Option<&Component> {
self.dag.node_weight(node).map(|(component, _)| component)
}
pub fn install_status(&self, node: NodeIndex) -> Option<&InstallStatus> {
self.dag.node_weight(node).map(|(_, status)| status)
}
pub fn get_node_id(&self, component: Component) -> Option<NodeIndex> {
self.dag.raw_nodes().iter().enumerate().find(|(_,node)| {
let (c, _) = node.weight;
c == component
}).map(|(index,_)| self.dag.from_index(index))
}
pub fn depth(&self, node: NodeIndex) -> usize {
self.dag
.recursive_walk(node, |g, n| g.parents(n).walk_next(g))
.iter(&self.dag)
.count()
}
/// Returns a **Vec** with all depended modules for the given node.
pub fn get_dependend_modules(&self, node: NodeIndex) -> Vec<(DagNode, NodeIndex)> {
self.dag
.recursive_walk(node, |g, n| g.parents(n).walk_next(g))
.iter(&self.dag)
.map(|(_, n)| (*self.dag.node_weight(n).unwrap(), n))
.collect()
}
/// Returns a **Vec** with all submodules for the given node.
pub fn get_sub_modules(&self, node: NodeIndex) -> Vec<(DagNode, NodeIndex)> {
let mut modules = Vec::new();
for (_, n) in self.dag.children(node).iter(&self.dag) {
modules.push((*self.dag.node_weight(n).unwrap(), n));
modules.append(&mut self.get_sub_modules(n));
}
modules
}
pub fn context(&self) -> &ModulesDag {
&self.dag
}
fn build_dag(manifest: &Manifest) -> ModulesDag {
let mut dag = Dag::new();
let editor = dag.add_node((Component::Editor, InstallStatus::default()));
for (c, m1) in manifest
.iter()
.sorted_by(|(a, _), (b, _)| b.to_string().cmp(&a.to_string()))
{
if *c != Component::Editor && m1.sync.is_none() {
let (_, n) = dag.add_child(editor, (), (*c, InstallStatus::default()));
Self::find_sync(&mut dag, &manifest, *c, n, 1);
}
}
dag
}
fn find_sync(
dag: &mut ModulesDag,
manifest: &Manifest,
parent: Component,
n: NodeIndex<DefaultIx>,
depth: u64,
) {
for (c, m) in manifest.iter() {
match m.sync {
Some(id) if id == parent => {
let (_, n) = dag.add_child(n, (), (*c, InstallStatus::default()));
Self::find_sync(dag, manifest, *c, n, depth + 1);
}
_ => (),
};
}
}
}
|
pub mod listener;
mod stream;
pub use stream::Stream;
pub enum SocketAddr {
Tcp(std::net::SocketAddr),
Unix(tokio::net::unix::SocketAddr),
}
|
#[doc = "Register `APB2RSTR` reader"]
pub type R = crate::R<APB2RSTR_SPEC>;
#[doc = "Register `APB2RSTR` writer"]
pub type W = crate::W<APB2RSTR_SPEC>;
#[doc = "Field `SYSCFGRST` reader - System configuration (SYSCFG) reset"]
pub type SYSCFGRST_R = crate::BitReader<SYSCFGRST_A>;
#[doc = "System configuration (SYSCFG) reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SYSCFGRST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset SYSCFG + COMP + VREFBUF"]
Reset = 1,
}
impl From<SYSCFGRST_A> for bool {
#[inline(always)]
fn from(variant: SYSCFGRST_A) -> Self {
variant as u8 != 0
}
}
impl SYSCFGRST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SYSCFGRST_A {
match self.bits {
false => SYSCFGRST_A::NoEffect,
true => SYSCFGRST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == SYSCFGRST_A::NoEffect
}
#[doc = "Reset SYSCFG + COMP + VREFBUF"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == SYSCFGRST_A::Reset
}
}
#[doc = "Field `SYSCFGRST` writer - System configuration (SYSCFG) reset"]
pub type SYSCFGRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SYSCFGRST_A>;
impl<'a, REG, const O: u8> SYSCFGRST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(SYSCFGRST_A::NoEffect)
}
#[doc = "Reset SYSCFG + COMP + VREFBUF"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(SYSCFGRST_A::Reset)
}
}
#[doc = "Field `TIM1RST` reader - TIM1 timer reset"]
pub type TIM1RST_R = crate::BitReader<TIM1RST_A>;
#[doc = "TIM1 timer reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TIM1RST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset TIMx"]
Reset = 1,
}
impl From<TIM1RST_A> for bool {
#[inline(always)]
fn from(variant: TIM1RST_A) -> Self {
variant as u8 != 0
}
}
impl TIM1RST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIM1RST_A {
match self.bits {
false => TIM1RST_A::NoEffect,
true => TIM1RST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TIM1RST_A::NoEffect
}
#[doc = "Reset TIMx"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == TIM1RST_A::Reset
}
}
#[doc = "Field `TIM1RST` writer - TIM1 timer reset"]
pub type TIM1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIM1RST_A>;
impl<'a, REG, const O: u8> TIM1RST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(TIM1RST_A::NoEffect)
}
#[doc = "Reset TIMx"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(TIM1RST_A::Reset)
}
}
#[doc = "Field `SPI1RST` reader - SPI1 reset"]
pub type SPI1RST_R = crate::BitReader<SPI1RST_A>;
#[doc = "SPI1 reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SPI1RST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset SPI1"]
Reset = 1,
}
impl From<SPI1RST_A> for bool {
#[inline(always)]
fn from(variant: SPI1RST_A) -> Self {
variant as u8 != 0
}
}
impl SPI1RST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SPI1RST_A {
match self.bits {
false => SPI1RST_A::NoEffect,
true => SPI1RST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == SPI1RST_A::NoEffect
}
#[doc = "Reset SPI1"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == SPI1RST_A::Reset
}
}
#[doc = "Field `SPI1RST` writer - SPI1 reset"]
pub type SPI1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SPI1RST_A>;
impl<'a, REG, const O: u8> SPI1RST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(SPI1RST_A::NoEffect)
}
#[doc = "Reset SPI1"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(SPI1RST_A::Reset)
}
}
#[doc = "Field `TIM8RST` reader - TIM8 timer reset"]
pub use TIM1RST_R as TIM8RST_R;
#[doc = "Field `TIM8RST` writer - TIM8 timer reset"]
pub use TIM1RST_W as TIM8RST_W;
#[doc = "Field `USART1RST` reader - USART1 reset"]
pub type USART1RST_R = crate::BitReader<USART1RST_A>;
#[doc = "USART1 reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum USART1RST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset UARTx"]
Reset = 1,
}
impl From<USART1RST_A> for bool {
#[inline(always)]
fn from(variant: USART1RST_A) -> Self {
variant as u8 != 0
}
}
impl USART1RST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> USART1RST_A {
match self.bits {
false => USART1RST_A::NoEffect,
true => USART1RST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == USART1RST_A::NoEffect
}
#[doc = "Reset UARTx"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == USART1RST_A::Reset
}
}
#[doc = "Field `USART1RST` writer - USART1 reset"]
pub type USART1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, USART1RST_A>;
impl<'a, REG, const O: u8> USART1RST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(USART1RST_A::NoEffect)
}
#[doc = "Reset UARTx"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(USART1RST_A::Reset)
}
}
#[doc = "Field `TIM15RST` reader - TIM15 timer reset"]
pub use TIM1RST_R as TIM15RST_R;
#[doc = "Field `TIM16RST` reader - TIM16 timer reset"]
pub use TIM1RST_R as TIM16RST_R;
#[doc = "Field `TIM17RST` reader - TIM17 timer reset"]
pub use TIM1RST_R as TIM17RST_R;
#[doc = "Field `TIM15RST` writer - TIM15 timer reset"]
pub use TIM1RST_W as TIM15RST_W;
#[doc = "Field `TIM16RST` writer - TIM16 timer reset"]
pub use TIM1RST_W as TIM16RST_W;
#[doc = "Field `TIM17RST` writer - TIM17 timer reset"]
pub use TIM1RST_W as TIM17RST_W;
#[doc = "Field `SAI1RST` reader - Serial audio interface 1 (SAI1) reset"]
pub type SAI1RST_R = crate::BitReader<SAI1RST_A>;
#[doc = "Serial audio interface 1 (SAI1) reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SAI1RST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset SAIx"]
Reset = 1,
}
impl From<SAI1RST_A> for bool {
#[inline(always)]
fn from(variant: SAI1RST_A) -> Self {
variant as u8 != 0
}
}
impl SAI1RST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SAI1RST_A {
match self.bits {
false => SAI1RST_A::NoEffect,
true => SAI1RST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == SAI1RST_A::NoEffect
}
#[doc = "Reset SAIx"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == SAI1RST_A::Reset
}
}
#[doc = "Field `SAI1RST` writer - Serial audio interface 1 (SAI1) reset"]
pub type SAI1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SAI1RST_A>;
impl<'a, REG, const O: u8> SAI1RST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(SAI1RST_A::NoEffect)
}
#[doc = "Reset SAIx"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(SAI1RST_A::Reset)
}
}
#[doc = "Field `SAI2RST` reader - Serial audio interface 2 (SAI2) reset"]
pub use SAI1RST_R as SAI2RST_R;
#[doc = "Field `SAI2RST` writer - Serial audio interface 2 (SAI2) reset"]
pub use SAI1RST_W as SAI2RST_W;
#[doc = "Field `DFSDM1RST` reader - Digital filters for sigma-delata modulators (DFSDM) reset"]
pub type DFSDM1RST_R = crate::BitReader<DFSDM1RST_A>;
#[doc = "Digital filters for sigma-delata modulators (DFSDM) reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DFSDM1RST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset DFSDM1"]
Reset = 1,
}
impl From<DFSDM1RST_A> for bool {
#[inline(always)]
fn from(variant: DFSDM1RST_A) -> Self {
variant as u8 != 0
}
}
impl DFSDM1RST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DFSDM1RST_A {
match self.bits {
false => DFSDM1RST_A::NoEffect,
true => DFSDM1RST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == DFSDM1RST_A::NoEffect
}
#[doc = "Reset DFSDM1"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == DFSDM1RST_A::Reset
}
}
#[doc = "Field `DFSDM1RST` writer - Digital filters for sigma-delata modulators (DFSDM) reset"]
pub type DFSDM1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DFSDM1RST_A>;
impl<'a, REG, const O: u8> DFSDM1RST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(DFSDM1RST_A::NoEffect)
}
#[doc = "Reset DFSDM1"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(DFSDM1RST_A::Reset)
}
}
#[doc = "Field `LTDCRST` reader - LCD-TFT reset"]
pub type LTDCRST_R = crate::BitReader<LTDCRST_A>;
#[doc = "LCD-TFT reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LTDCRST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset LCD-TFT"]
Reset = 1,
}
impl From<LTDCRST_A> for bool {
#[inline(always)]
fn from(variant: LTDCRST_A) -> Self {
variant as u8 != 0
}
}
impl LTDCRST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LTDCRST_A {
match self.bits {
false => LTDCRST_A::NoEffect,
true => LTDCRST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == LTDCRST_A::NoEffect
}
#[doc = "Reset LCD-TFT"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == LTDCRST_A::Reset
}
}
#[doc = "Field `LTDCRST` writer - LCD-TFT reset"]
pub type LTDCRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LTDCRST_A>;
impl<'a, REG, const O: u8> LTDCRST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(LTDCRST_A::NoEffect)
}
#[doc = "Reset LCD-TFT"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(LTDCRST_A::Reset)
}
}
#[doc = "Field `DSIRST` reader - DSI reset"]
pub type DSIRST_R = crate::BitReader<DSIRST_A>;
#[doc = "DSI reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DSIRST_A {
#[doc = "0: No effect"]
NoEffect = 0,
#[doc = "1: Reset DSI"]
Reset = 1,
}
impl From<DSIRST_A> for bool {
#[inline(always)]
fn from(variant: DSIRST_A) -> Self {
variant as u8 != 0
}
}
impl DSIRST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DSIRST_A {
match self.bits {
false => DSIRST_A::NoEffect,
true => DSIRST_A::Reset,
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == DSIRST_A::NoEffect
}
#[doc = "Reset DSI"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == DSIRST_A::Reset
}
}
#[doc = "Field `DSIRST` writer - DSI reset"]
pub type DSIRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DSIRST_A>;
impl<'a, REG, const O: u8> DSIRST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(DSIRST_A::NoEffect)
}
#[doc = "Reset DSI"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(DSIRST_A::Reset)
}
}
impl R {
#[doc = "Bit 0 - System configuration (SYSCFG) reset"]
#[inline(always)]
pub fn syscfgrst(&self) -> SYSCFGRST_R {
SYSCFGRST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 11 - TIM1 timer reset"]
#[inline(always)]
pub fn tim1rst(&self) -> TIM1RST_R {
TIM1RST_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - SPI1 reset"]
#[inline(always)]
pub fn spi1rst(&self) -> SPI1RST_R {
SPI1RST_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - TIM8 timer reset"]
#[inline(always)]
pub fn tim8rst(&self) -> TIM8RST_R {
TIM8RST_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - USART1 reset"]
#[inline(always)]
pub fn usart1rst(&self) -> USART1RST_R {
USART1RST_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 16 - TIM15 timer reset"]
#[inline(always)]
pub fn tim15rst(&self) -> TIM15RST_R {
TIM15RST_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - TIM16 timer reset"]
#[inline(always)]
pub fn tim16rst(&self) -> TIM16RST_R {
TIM16RST_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - TIM17 timer reset"]
#[inline(always)]
pub fn tim17rst(&self) -> TIM17RST_R {
TIM17RST_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 21 - Serial audio interface 1 (SAI1) reset"]
#[inline(always)]
pub fn sai1rst(&self) -> SAI1RST_R {
SAI1RST_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - Serial audio interface 2 (SAI2) reset"]
#[inline(always)]
pub fn sai2rst(&self) -> SAI2RST_R {
SAI2RST_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 24 - Digital filters for sigma-delata modulators (DFSDM) reset"]
#[inline(always)]
pub fn dfsdm1rst(&self) -> DFSDM1RST_R {
DFSDM1RST_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 26 - LCD-TFT reset"]
#[inline(always)]
pub fn ltdcrst(&self) -> LTDCRST_R {
LTDCRST_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - DSI reset"]
#[inline(always)]
pub fn dsirst(&self) -> DSIRST_R {
DSIRST_R::new(((self.bits >> 27) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - System configuration (SYSCFG) reset"]
#[inline(always)]
#[must_use]
pub fn syscfgrst(&mut self) -> SYSCFGRST_W<APB2RSTR_SPEC, 0> {
SYSCFGRST_W::new(self)
}
#[doc = "Bit 11 - TIM1 timer reset"]
#[inline(always)]
#[must_use]
pub fn tim1rst(&mut self) -> TIM1RST_W<APB2RSTR_SPEC, 11> {
TIM1RST_W::new(self)
}
#[doc = "Bit 12 - SPI1 reset"]
#[inline(always)]
#[must_use]
pub fn spi1rst(&mut self) -> SPI1RST_W<APB2RSTR_SPEC, 12> {
SPI1RST_W::new(self)
}
#[doc = "Bit 13 - TIM8 timer reset"]
#[inline(always)]
#[must_use]
pub fn tim8rst(&mut self) -> TIM8RST_W<APB2RSTR_SPEC, 13> {
TIM8RST_W::new(self)
}
#[doc = "Bit 14 - USART1 reset"]
#[inline(always)]
#[must_use]
pub fn usart1rst(&mut self) -> USART1RST_W<APB2RSTR_SPEC, 14> {
USART1RST_W::new(self)
}
#[doc = "Bit 16 - TIM15 timer reset"]
#[inline(always)]
#[must_use]
pub fn tim15rst(&mut self) -> TIM15RST_W<APB2RSTR_SPEC, 16> {
TIM15RST_W::new(self)
}
#[doc = "Bit 17 - TIM16 timer reset"]
#[inline(always)]
#[must_use]
pub fn tim16rst(&mut self) -> TIM16RST_W<APB2RSTR_SPEC, 17> {
TIM16RST_W::new(self)
}
#[doc = "Bit 18 - TIM17 timer reset"]
#[inline(always)]
#[must_use]
pub fn tim17rst(&mut self) -> TIM17RST_W<APB2RSTR_SPEC, 18> {
TIM17RST_W::new(self)
}
#[doc = "Bit 21 - Serial audio interface 1 (SAI1) reset"]
#[inline(always)]
#[must_use]
pub fn sai1rst(&mut self) -> SAI1RST_W<APB2RSTR_SPEC, 21> {
SAI1RST_W::new(self)
}
#[doc = "Bit 22 - Serial audio interface 2 (SAI2) reset"]
#[inline(always)]
#[must_use]
pub fn sai2rst(&mut self) -> SAI2RST_W<APB2RSTR_SPEC, 22> {
SAI2RST_W::new(self)
}
#[doc = "Bit 24 - Digital filters for sigma-delata modulators (DFSDM) reset"]
#[inline(always)]
#[must_use]
pub fn dfsdm1rst(&mut self) -> DFSDM1RST_W<APB2RSTR_SPEC, 24> {
DFSDM1RST_W::new(self)
}
#[doc = "Bit 26 - LCD-TFT reset"]
#[inline(always)]
#[must_use]
pub fn ltdcrst(&mut self) -> LTDCRST_W<APB2RSTR_SPEC, 26> {
LTDCRST_W::new(self)
}
#[doc = "Bit 27 - DSI reset"]
#[inline(always)]
#[must_use]
pub fn dsirst(&mut self) -> DSIRST_W<APB2RSTR_SPEC, 27> {
DSIRST_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "APB2 peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2rstr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb2rstr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB2RSTR_SPEC;
impl crate::RegisterSpec for APB2RSTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb2rstr::R`](R) reader structure"]
impl crate::Readable for APB2RSTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb2rstr::W`](W) writer structure"]
impl crate::Writable for APB2RSTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB2RSTR to value 0"]
impl crate::Resettable for APB2RSTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use ducc::Ducc;
use std::time::{
SystemTime,
UNIX_EPOCH,
};
const BROWSER_ENV_SHIM: &str = include_str!("./browser_env_shim.js");
pub struct JsEngine {
vm: Ducc,
}
impl JsEngine {
pub fn new() -> Result<Self, ducc::Error> {
let vm = Ducc::new();
vm.exec(BROWSER_ENV_SHIM, None, Default::default())?;
Ok(JsEngine { vm })
}
pub fn exec(&self, data: &str) -> Result<(), ducc::Error> {
self.vm.exec(data, Some("main"), Default::default())?;
Ok(())
}
pub fn get_global<'a, K: ducc::ToValue<'a>, V: ducc::FromValue<'a>>(
&'a self,
name: K,
) -> Result<V, ducc::Error> {
let globals = self.vm.globals();
let prop = globals.get(name)?;
V::from_value(prop, &self.vm)
}
pub fn get_ducc(&self) -> &Ducc {
&self.vm
}
pub fn into_ducc(self) -> Ducc {
self.vm
}
}
pub fn get_time_ms() -> u128 {
let start = SystemTime::now();
start.duration_since(UNIX_EPOCH).unwrap().as_millis()
}
|
use super::{
Expr,
Type,
ExprValue,
IfExpr,
BinOp,
UnaryOp
};
use crate::parser::token::Token;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct TypedExpr<'a> {
token: Token<'a>,
/// Not actually a kind, but avoids having to call it r#type
kind: Type,
value: ExprValue<TypedExpr<'a>>
}
impl<'a> Expr for TypedExpr<'a> {}
impl<'a> TypedExpr<'a> {
pub fn kind(&self) -> &Type {
return &self.kind;
}
pub fn const_unit(token: Token<'a>) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: Type::Unit,
value: ExprValue::ConstUnit
})
}
pub fn const_int(token: Token<'a>, value: i64) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: Type::Int,
value: ExprValue::ConstInt(value)
})
}
pub fn const_bool(token: Token<'a>, value: bool) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: Type::Bool,
value: ExprValue::ConstBool(value)
})
}
pub fn bin_op(token: Token<'a>, kind: Type, op: BinOp, lhs: Box<TypedExpr<'a>>, rhs: Box<TypedExpr<'a>>) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: kind,
value: ExprValue::BinOp(op, lhs, rhs)
})
}
pub fn unary_op(token: Token<'a>, kind: Type, op: UnaryOp, expr: Box<TypedExpr<'a>>) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: kind,
value: ExprValue::UnaryOp(op, expr)
})
}
pub fn block(token: Token<'a>, exprs: Vec<Box<TypedExpr<'a>>>) -> Box<TypedExpr<'a>> {
let block_type = if exprs.len() == 0 { Type::Unit } else { exprs[exprs.len() - 1].kind().clone() };
Box::new(TypedExpr {
token: token,
kind: block_type,
value: ExprValue::Block(exprs)
})
}
pub fn conditional(token: Token<'a>, cond_expr: Box<TypedExpr<'a>>, then_expr: Box<TypedExpr<'a>>, else_expr: Box<TypedExpr<'a>>) -> Box<TypedExpr<'a>> {
assert_eq!(*cond_expr.kind(), Type::Bool);
assert_eq!(then_expr.kind(), else_expr.kind());
Box::new(TypedExpr {
token: token,
kind: then_expr.kind().clone(),
value: ExprValue::If(IfExpr {
cond: cond_expr,
then_expr: then_expr,
else_expr: else_expr
})
})
}
pub fn var(token: Token<'a>, iden: &String, kind: Type) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: kind,
value: ExprValue::Var(iden.clone())
})
}
pub fn function_app(token: Token<'a>, kind: Type, iden: String, args: Vec<Box<TypedExpr<'a>>>) -> Box<TypedExpr<'a>> {
Box::new(TypedExpr {
token: token,
kind: kind,
value: ExprValue::FunctionApp(iden, args)
})
}
}
impl<'a> Borrow<ExprValue<TypedExpr<'a>>> for TypedExpr<'a> {
fn borrow(&self) -> &ExprValue<TypedExpr<'a>> {
return &self.value;
}
} |
extern crate dmbc;
extern crate exonum;
extern crate exonum_testkit;
extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate mount;
extern crate serde_json;
pub mod dmbc_testkit;
use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi};
use exonum::crypto;
use exonum::messages::Message;
use hyper::status::StatusCode;
use dmbc::currency::api::error::ApiError;
use dmbc::currency::api::transaction::TransactionResponse;
use dmbc::currency::assets::AssetBundle;
use dmbc::currency::configuration::{Configuration, TransactionFees, TransactionPermissions};
use dmbc::currency::error::Error;
use dmbc::currency::transactions::builders::transaction;
use dmbc::currency::transactions::components::FeeStrategy;
use dmbc::currency::wallet::Wallet;
#[test]
fn exchange_assets_fee_from_recipient() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, info1) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&sender_pk, Wallet::new(others_balance, vec![]))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset1.clone(), info1))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::Recipient)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let tx_hash = tx_exchange_assets.hash();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::Created);
assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash })));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Ok(Ok(())));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let asset_fee = senders_units * fixed
+ sender_unit_exchange * fixed
+ senders_units * fixed
+ receiver_units * fixed
+ recipient_unit_exchange * fixed
+ recipient_unit_exchange * fixed;
let expected_senders_balance = others_balance;
let expected_recipient_balance = others_balance - transaction_fee - asset_fee;
let expected_genesis_balance = genesis_balance + transaction_fee;
let expected_creator_balance = creators_balance + asset_fee;
assert_eq!(sender_wallet.balance, expected_senders_balance);
assert_eq!(recipient_wallet.balance, expected_recipient_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
let recipient_assets = api
.get_wallet_assets(&recipient_pk)
.iter()
.map(|a| a.into())
.collect::<Vec<AssetBundle>>();
let sender_assets = api
.get_wallet_assets(&sender_pk)
.iter()
.map(|a| a.into())
.collect::<Vec<AssetBundle>>();
assert_eq!(
sender_assets,
vec![
AssetBundle::new(asset2.id(), senders_units - sender_unit_exchange),
AssetBundle::new(asset4.id(), receiver_units),
AssetBundle::new(asset5.id(), recipient_unit_exchange),
AssetBundle::new(asset6.id(), recipient_unit_exchange),
]
);
assert_eq!(
recipient_assets,
vec![
AssetBundle::new(asset5.id(), receiver_units - recipient_unit_exchange),
AssetBundle::new(asset6.id(), receiver_units - recipient_unit_exchange),
AssetBundle::new(asset1.id(), senders_units),
AssetBundle::new(asset2.id(), sender_unit_exchange),
AssetBundle::new(asset3.id(), senders_units),
]
);
}
#[test]
fn exchange_assets_fee_from_sender() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, info1) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&sender_pk, Wallet::new(others_balance, vec![]))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset1.clone(), info1))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::Sender)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let tx_hash = tx_exchange_assets.hash();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::Created);
assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash })));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Ok(Ok(())));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let asset_fee = senders_units * fixed
+ sender_unit_exchange * fixed
+ senders_units * fixed
+ receiver_units * fixed
+ recipient_unit_exchange * fixed
+ recipient_unit_exchange * fixed;
let expected_senders_balance = others_balance - transaction_fee - asset_fee;
let expected_recipient_balance = others_balance;
let expected_genesis_balance = genesis_balance + transaction_fee;
let expected_creator_balance = creators_balance + asset_fee;
assert_eq!(sender_wallet.balance, expected_senders_balance);
assert_eq!(recipient_wallet.balance, expected_recipient_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
let recipient_assets = api
.get_wallet_assets(&recipient_pk)
.iter()
.map(|a| a.into())
.collect::<Vec<AssetBundle>>();
let sender_assets = api
.get_wallet_assets(&sender_pk)
.iter()
.map(|a| a.into())
.collect::<Vec<AssetBundle>>();
assert_eq!(
sender_assets,
vec![
AssetBundle::new(asset2.id(), senders_units - sender_unit_exchange),
AssetBundle::new(asset4.id(), receiver_units),
AssetBundle::new(asset5.id(), recipient_unit_exchange),
AssetBundle::new(asset6.id(), recipient_unit_exchange),
]
);
assert_eq!(
recipient_assets,
vec![
AssetBundle::new(asset5.id(), receiver_units - recipient_unit_exchange),
AssetBundle::new(asset6.id(), receiver_units - recipient_unit_exchange),
AssetBundle::new(asset1.id(), senders_units),
AssetBundle::new(asset2.id(), sender_unit_exchange),
AssetBundle::new(asset3.id(), senders_units),
]
);
}
#[test]
fn exchange_assets_fee_from_recipient_and_sender() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, info1) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&sender_pk, Wallet::new(others_balance, vec![]))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset1.clone(), info1))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::RecipientAndSender)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let tx_hash = tx_exchange_assets.hash();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::Created);
assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash })));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Ok(Ok(())));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let asset_fee = senders_units * fixed
+ sender_unit_exchange * fixed
+ senders_units * fixed
+ receiver_units * fixed
+ recipient_unit_exchange * fixed
+ recipient_unit_exchange * fixed;
let expected_balance = others_balance - transaction_fee / 2 - asset_fee / 2;
let expected_genesis_balance = genesis_balance + transaction_fee;
let expected_creator_balance = creators_balance + asset_fee;
assert_eq!(sender_wallet.balance, expected_balance);
assert_eq!(recipient_wallet.balance, expected_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
let recipient_assets = api
.get_wallet_assets(&recipient_pk)
.iter()
.map(|a| a.into())
.collect::<Vec<AssetBundle>>();
let sender_assets = api
.get_wallet_assets(&sender_pk)
.iter()
.map(|a| a.into())
.collect::<Vec<AssetBundle>>();
assert_eq!(
sender_assets,
vec![
AssetBundle::new(asset2.id(), senders_units - sender_unit_exchange),
AssetBundle::new(asset4.id(), receiver_units),
AssetBundle::new(asset5.id(), recipient_unit_exchange),
AssetBundle::new(asset6.id(), recipient_unit_exchange),
]
);
assert_eq!(
recipient_assets,
vec![
AssetBundle::new(asset5.id(), receiver_units - recipient_unit_exchange),
AssetBundle::new(asset6.id(), receiver_units - recipient_unit_exchange),
AssetBundle::new(asset1.id(), senders_units),
AssetBundle::new(asset2.id(), sender_unit_exchange),
AssetBundle::new(asset3.id(), senders_units),
]
);
}
#[test]
fn exchange_assets_invalid_tx() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, info1) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&sender_pk, Wallet::new(others_balance, vec![]))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset1.clone(), info1))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::Intermediary)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::BadRequest);
assert_eq!(response, Ok(Err(Error::UnableToVerifyTransaction)));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Err(ApiError::TransactionNotFound));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let expected_balance = others_balance;
let expected_genesis_balance = genesis_balance;
let expected_creator_balance = creators_balance;
assert_eq!(sender_wallet.balance, expected_balance);
assert_eq!(recipient_wallet.balance, expected_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
}
#[test]
fn exchange_assets_insufficient_funds() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, info1) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset1.clone(), info1))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::Sender)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let tx_hash = tx_exchange_assets.hash();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::Created);
assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash })));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Ok(Err(Error::InsufficientFunds)));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let expected_balance = others_balance;
let expected_genesis_balance = genesis_balance;
let expected_creator_balance = creators_balance;
assert_eq!(sender_wallet.balance, 0);
assert_eq!(recipient_wallet.balance, expected_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
}
#[test]
fn exchange_assets_assets_not_found() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, _) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&sender_pk, Wallet::new(others_balance, vec![]))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::Sender)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let tx_hash = tx_exchange_assets.hash();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::Created);
assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash })));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Ok(Err(Error::AssetNotFound)));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let expected_senders_balance = others_balance - transaction_fee;
let expected_balance = others_balance;
let expected_genesis_balance = genesis_balance + transaction_fee;
let expected_creator_balance = creators_balance;
assert_eq!(sender_wallet.balance, expected_senders_balance);
assert_eq!(recipient_wallet.balance, expected_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
}
#[test]
fn exchange_assets_insufficient_assets() {
let transaction_fee = 1000;
let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0);
let permissions = TransactionPermissions::default();
let fixed = 10;
let creators_balance = 0;
let others_balance = 100_000;
let receiver_units = 10;
let senders_units = 8;
let sender_unit_exchange = senders_units - 2;
let recipients_units = 5;
let recipient_unit_exchange = recipients_units - 4;
let meta_data1 = "asset1";
let meta_data2 = "asset2";
let meta_data3 = "asset3";
let meta_data4 = "asset4";
let meta_data5 = "asset5";
let meta_data6 = "asset6";
let (sender_pk, sender_sk) = crypto::gen_keypair();
let (recipient_pk, recipient_sk) = crypto::gen_keypair();
let (creator_pk, _) = crypto::gen_keypair();
let (asset1, info1) = dmbc_testkit::create_asset(
meta_data1,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset2, info2) = dmbc_testkit::create_asset(
meta_data2,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset3, info3) = dmbc_testkit::create_asset(
meta_data3,
senders_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset4, info4) = dmbc_testkit::create_asset(
meta_data4,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset5, info5) = dmbc_testkit::create_asset(
meta_data5,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let (asset6, info6) = dmbc_testkit::create_asset(
meta_data6,
receiver_units,
dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()),
&creator_pk,
);
let mut testkit = DmbcTestApiBuilder::new()
.with_configuration(Configuration::new(config_fees, permissions))
.add_wallet_value(&sender_pk, Wallet::new(others_balance, vec![]))
.add_wallet_value(&recipient_pk, Wallet::new(others_balance, vec![]))
.add_asset_to_wallet(&sender_pk, (asset1.clone(), info1))
.add_asset_to_wallet(&sender_pk, (asset2.clone(), info2))
.add_asset_to_wallet(&sender_pk, (asset3.clone(), info3))
.add_asset_to_wallet(&recipient_pk, (asset4.clone(), info4))
.add_asset_to_wallet(&recipient_pk, (asset5.clone(), info5))
.add_asset_to_wallet(&recipient_pk, (asset6.clone(), info6))
.create();
let api = testkit.api();
let genesis_balance = api.get_wallet(&dmbc_testkit::default_genesis_key()).balance;
let tx_exchange_assets = transaction::Builder::new()
.keypair(recipient_pk, recipient_sk)
.tx_exchange()
.sender(sender_pk)
.sender_secret(sender_sk)
.fee_strategy(FeeStrategy::Sender)
.sender_add_asset_value(AssetBundle::new(asset1.id(), senders_units))
.sender_add_asset_value(AssetBundle::new(asset2.id(), sender_unit_exchange * 3))
.sender_add_asset_value(AssetBundle::new(asset3.id(), senders_units))
.recipient_add_asset_value(AssetBundle::new(asset4.id(), receiver_units))
.recipient_add_asset_value(AssetBundle::new(asset5.id(), recipient_unit_exchange))
.recipient_add_asset_value(AssetBundle::new(asset6.id(), recipient_unit_exchange))
.build();
let tx_hash = tx_exchange_assets.hash();
let (status, response) = api.post_tx(&tx_exchange_assets);
testkit.create_block();
// check post response
assert_eq!(status, StatusCode::Created);
assert_eq!(response, Ok(Ok(TransactionResponse { tx_hash })));
let (_, tx_status) = api.get_tx_status(&tx_exchange_assets);
assert_eq!(tx_status, Ok(Err(Error::InsufficientAssets)));
let sender_wallet = api.get_wallet(&sender_pk);
let recipient_wallet = api.get_wallet(&recipient_pk);
let genesis_wallet = api.get_wallet(&dmbc_testkit::default_genesis_key());
let creator_wallet = api.get_wallet(&creator_pk);
let expected_senders_balance = others_balance - transaction_fee;
let expected_balance = others_balance;
let expected_genesis_balance = genesis_balance + transaction_fee;
let expected_creator_balance = creators_balance;
assert_eq!(sender_wallet.balance, expected_senders_balance);
assert_eq!(recipient_wallet.balance, expected_balance);
assert_eq!(genesis_wallet.balance, expected_genesis_balance);
assert_eq!(creator_wallet.balance, expected_creator_balance);
} |
// Generated by `scripts/generate.js`
pub type VkTransformMatrix = super::super::khr::VkTransformMatrix;
#[doc(hidden)]
pub type RawVkTransformMatrix = super::super::khr::RawVkTransformMatrix; |
pub mod pathfinder;
|
mod abi;
mod crypto;
mod primitives;
|
//! Models for password reset
use std::fmt;
use std::time::SystemTime;
use base64::encode;
use uuid::Uuid;
use validator::Validate;
use stq_static_resources::TokenType;
use models::user::User;
use schema::reset_tokens;
#[derive(Serialize, Deserialize, Queryable, Insertable, Debug)]
#[table_name = "reset_tokens"]
pub struct ResetToken {
pub token: String,
pub email: String,
pub created_at: SystemTime,
pub token_type: TokenType,
pub uuid: Uuid,
pub updated_at: SystemTime,
}
impl ResetToken {
pub fn new(email: String, token_type: TokenType, uuid: Option<Uuid>) -> ResetToken {
let uuid = uuid.unwrap_or(Uuid::new_v4());
let token = encode(&Uuid::new_v4().to_string());
ResetToken {
token,
email,
token_type,
uuid,
created_at: SystemTime::now(),
updated_at: SystemTime::now(),
}
}
}
#[derive(Serialize, Deserialize, Validate, Debug)]
pub struct ResetRequest {
#[validate(email(code = "not_valid", message = "Invalid email format"))]
pub email: String,
pub uuid: Uuid,
}
#[derive(Serialize, Deserialize, Validate, Debug)]
pub struct VerifyRequest {
#[validate(email(code = "not_valid", message = "Invalid email format"))]
pub email: String,
}
#[derive(Serialize, Deserialize, Validate, Debug)]
pub struct ResetApply {
pub token: String,
#[validate(length(min = "8", max = "30", message = "Password should be between 8 and 30 symbols"))]
pub password: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ResetApplyToken {
pub email: String,
pub token: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ResetMail {
pub to: String,
pub subject: String,
pub text: String,
}
impl fmt::Display for ResetApply {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ResetApply {{ token: \"{}\", password: \"*****\" }}", self.token)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct EmailVerifyApplyToken {
pub user: User,
pub token: String,
}
|
#![feature(generators, try_trait)]
extern crate aoc_runner;
extern crate pest;
#[macro_use] extern crate pest_derive;
#[macro_use] extern crate failure;
#[macro_use] extern crate aoc_runner_derive;
extern crate gen_iter;
extern crate num_integer;
pub mod common;
pub mod day1;
pub mod day2;
pub mod day3;
pub mod day4;
pub mod day5;
pub mod day6;
pub mod day7;
pub mod day8;
pub mod day9;
pub mod day10;
pub mod day11;
pub mod day12;
pub mod day13;
pub mod day14;
pub mod day15;
pub mod day16;
aoc_lib!{ year = 2019 }
|
#[doc = "Register `FDCAN_TTTMK` reader"]
pub type R = crate::R<FDCAN_TTTMK_SPEC>;
#[doc = "Register `FDCAN_TTTMK` writer"]
pub type W = crate::W<FDCAN_TTTMK_SPEC>;
#[doc = "Field `TM` reader - Time Mark"]
pub type TM_R = crate::FieldReader<u16>;
#[doc = "Field `TM` writer - Time Mark"]
pub type TM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
#[doc = "Field `TICC` reader - Time Mark Cycle Code"]
pub type TICC_R = crate::FieldReader;
#[doc = "Field `TICC` writer - Time Mark Cycle Code"]
pub type TICC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>;
#[doc = "Field `LCKM` reader - TT Time Mark Register Locked"]
pub type LCKM_R = crate::BitReader;
#[doc = "Field `LCKM` writer - TT Time Mark Register Locked"]
pub type LCKM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:15 - Time Mark"]
#[inline(always)]
pub fn tm(&self) -> TM_R {
TM_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:22 - Time Mark Cycle Code"]
#[inline(always)]
pub fn ticc(&self) -> TICC_R {
TICC_R::new(((self.bits >> 16) & 0x7f) as u8)
}
#[doc = "Bit 31 - TT Time Mark Register Locked"]
#[inline(always)]
pub fn lckm(&self) -> LCKM_R {
LCKM_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:15 - Time Mark"]
#[inline(always)]
#[must_use]
pub fn tm(&mut self) -> TM_W<FDCAN_TTTMK_SPEC, 0> {
TM_W::new(self)
}
#[doc = "Bits 16:22 - Time Mark Cycle Code"]
#[inline(always)]
#[must_use]
pub fn ticc(&mut self) -> TICC_W<FDCAN_TTTMK_SPEC, 16> {
TICC_W::new(self)
}
#[doc = "Bit 31 - TT Time Mark Register Locked"]
#[inline(always)]
#[must_use]
pub fn lckm(&mut self) -> LCKM_W<FDCAN_TTTMK_SPEC, 31> {
LCKM_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "FDCAN TT Time Mark Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_tttmk::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fdcan_tttmk::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FDCAN_TTTMK_SPEC;
impl crate::RegisterSpec for FDCAN_TTTMK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fdcan_tttmk::R`](R) reader structure"]
impl crate::Readable for FDCAN_TTTMK_SPEC {}
#[doc = "`write(|w| ..)` method takes [`fdcan_tttmk::W`](W) writer structure"]
impl crate::Writable for FDCAN_TTTMK_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FDCAN_TTTMK to value 0"]
impl crate::Resettable for FDCAN_TTTMK_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// Generated by the capnpc-rust plugin to the Cap'n Proto schema compiler.
// DO NOT EDIT.
// source: protos/src/service.capnp
pub mod person {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_name(self) -> Result<text::Reader<'a>> {
self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
pub fn has_name(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
#[inline]
pub fn get_name(self) -> Result<text::Builder<'a>> {
self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
#[inline]
pub fn set_name(&mut self, value : text::Reader) {
self.builder.get_pointer_field(0).set_text(value);
}
#[inline]
pub fn init_name(self, size : u32) -> text::Builder<'a> {
self.builder.get_pointer_field(0).init_text(size)
}
pub fn has_name(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 1 };
pub const TYPE_ID: u64 = 0x88953d528f189d76;
}
}
pub mod person_service {
#![allow(unused_variables)]
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, Request, FromServer};
use capnp::private::capability::{ClientHook, ServerHook};
use capnp::capability;
pub type GetPersonContext<'a> = capability::CallContext<get_person_params::Reader<'a>, get_person_results::Builder<'a>>;
pub type MakePersonContext<'a> = capability::CallContext<make_person_params::Reader<'a>, make_person_results::Builder<'a>>;
pub type DoSomethingContext<'a> = capability::CallContext<do_something_params::Reader<'a>, do_something_results::Builder<'a>>;
pub struct Client{ pub client : ::capnp::private::capability::Client }
impl FromClientHook for Client {
fn new(hook : Box<ClientHook+Send>) -> Client {
Client { client : ::capnp::private::capability::Client::new(hook) }
}
}
pub struct ToClient<U>(pub U);
impl <T:ServerHook, U : Server + Send + 'static> FromServer<T, Client> for ToClient<U> {
fn from_server(self, _hook : Option<T>) -> Client {
Client { client : ServerHook::new_client(None::<T>, ::std::boxed::Box::new(ServerDispatch { server : ::std::boxed::Box::new(self.0)}))}
}
}
impl ::capnp::traits::HasTypeId for Client {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl Clone for Client {
fn clone(&self) -> Client {
Client { client : ::capnp::private::capability::Client::new(self.client.hook.copy()) }
}
}
impl Client {
pub fn get_person_request<'a>(&self) -> Request<get_person_params::Builder<'a>,get_person_results::Reader<'a>,get_person_results::Pipeline> {
self.client.new_call(_private::TYPE_ID, 0, None)
}
pub fn make_person_request<'a>(&self) -> Request<make_person_params::Builder<'a>,make_person_results::Reader<'a>,make_person_results::Pipeline> {
self.client.new_call(_private::TYPE_ID, 1, None)
}
pub fn do_something_request<'a>(&self) -> Request<do_something_params::Builder<'a>,do_something_results::Reader<'a>,do_something_results::Pipeline> {
self.client.new_call(_private::TYPE_ID, 2, None)
}
}
pub trait Server {
fn get_person<'a>(&mut self, GetPersonContext<'a>);
fn make_person<'a>(&mut self, MakePersonContext<'a>);
fn do_something<'a>(&mut self, DoSomethingContext<'a>);
}
pub struct ServerDispatch<T> {
pub server : Box<T>,
}
impl <T : Server> ::capnp::capability::Server for ServerDispatch<T> {
fn dispatch_call(&mut self, interface_id : u64, method_id : u16, context : capability::CallContext<::capnp::any_pointer::Reader, ::capnp::any_pointer::Builder>) {
match interface_id {
_private::TYPE_ID => ServerDispatch::<T>::dispatch_call_internal(&mut *self.server, method_id, context),
_ => {}
}
}
}
impl <T : Server> ServerDispatch<T> {
pub fn dispatch_call_internal(server :&mut T, method_id : u16, context : capability::CallContext<::capnp::any_pointer::Reader, ::capnp::any_pointer::Builder>) {
match method_id {
0 => server.get_person(::capnp::private::capability::internal_get_typed_context(context)),
1 => server.make_person(::capnp::private::capability::internal_get_typed_context(context)),
2 => server.do_something(::capnp::private::capability::internal_get_typed_context(context)),
_ => {}
}
}
}
pub mod _private {
pub const TYPE_ID: u64 = 0x9b4dd1de58fa3e09;
}
pub mod get_person_params {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 0 };
pub const TYPE_ID: u64 = 0x883676415a6cd514;
}
}
pub mod get_person_results {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_person(self) -> Result<::service_capnp::person::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0))
}
pub fn has_person(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
#[inline]
pub fn get_person(self) -> Result<::service_capnp::person::Builder<'a>> {
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0))
}
#[inline]
pub fn set_person(&mut self, value : ::service_capnp::person::Reader) -> Result<()> {
::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value)
}
#[inline]
pub fn init_person(self, ) -> ::service_capnp::person::Builder<'a> {
::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0)
}
pub fn has_person(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
pub fn get_person(&self) -> ::service_capnp::person::Pipeline {
FromTypelessPipeline::new(self._typeless.get_pointer_field(0))
}
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 1 };
pub const TYPE_ID: u64 = 0xa5df98f115cfee4c;
}
}
pub mod make_person_params {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_name(self) -> Result<text::Reader<'a>> {
self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
pub fn has_name(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
#[inline]
pub fn get_name(self) -> Result<text::Builder<'a>> {
self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
#[inline]
pub fn set_name(&mut self, value : text::Reader) {
self.builder.get_pointer_field(0).set_text(value);
}
#[inline]
pub fn init_name(self, size : u32) -> text::Builder<'a> {
self.builder.get_pointer_field(0).init_text(size)
}
pub fn has_name(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 1 };
pub const TYPE_ID: u64 = 0xccaba46b8cd01370;
}
}
pub mod make_person_results {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_person(self) -> Result<::service_capnp::person::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0))
}
pub fn has_person(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
#[inline]
pub fn get_person(self) -> Result<::service_capnp::person::Builder<'a>> {
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0))
}
#[inline]
pub fn set_person(&mut self, value : ::service_capnp::person::Reader) -> Result<()> {
::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value)
}
#[inline]
pub fn init_person(self, ) -> ::service_capnp::person::Builder<'a> {
::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0)
}
pub fn has_person(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
pub fn get_person(&self) -> ::service_capnp::person::Pipeline {
FromTypelessPipeline::new(self._typeless.get_pointer_field(0))
}
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 1 };
pub const TYPE_ID: u64 = 0xa6b484f744d24f29;
}
}
pub mod do_something_params {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 0 };
pub const TYPE_ID: u64 = 0x995ac8a78b5e16d5;
}
}
pub mod do_something_results {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::traits::{FromStructBuilder, FromStructReader};
use capnp::{primitive_list, enum_list, struct_list, text_list, data_list, list_list};
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader : layout::StructReader<'a> }
impl <'a> ::capnp::traits::HasTypeId for Reader<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructReader<'a> for Reader<'a> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a> {
Reader { reader : reader }
}
}
impl <'a> ::capnp::traits::FromPointerReader<'a> for Reader<'a> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> Result<Reader<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(try!(reader.get_struct(::std::ptr::null()))))
}
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Reader<'a>> for Reader<'b> {
fn cast(self) -> Reader<'a> { Reader { reader : self.reader } }
}
impl <'a> Reader<'a> {
pub fn borrow<'b>(&'b self) -> Reader<'b> {
Reader { reader : self.reader}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.reader.total_size()
}
}
pub struct Builder<'a> { builder : ::capnp::private::layout::StructBuilder<'a> }
impl <'a> ::capnp::traits::HasStructSize for Builder<'a> {
#[inline]
fn struct_size() -> layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a> ::capnp::traits::HasTypeId for Builder<'a> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a> ::capnp::traits::FromStructBuilder<'a> for Builder<'a> {
fn new(builder : ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a> {
Builder { builder : builder }
}
}
impl <'a> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size : u32) -> Builder<'a> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> Result<Builder<'a>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(try!(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null()))))
}
}
impl <'a> ::capnp::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> {
fn set_pointer_builder<'b>(pointer : ::capnp::private::layout::PointerBuilder<'b>, value : Reader<'a>) -> Result<()> { pointer.set_struct(&value.reader) }
}
impl <'a, 'b : 'a> ::capnp::traits::CastableTo<Builder<'a>> for Builder<'b> {
fn cast(self) -> Builder<'a> { Builder { builder : self.builder } }
}
impl <'a> Builder<'a> {
pub fn as_reader(self) -> Reader<'a> {
::capnp::traits::FromStructReader::new(self.builder.as_reader())
}
pub fn borrow<'b>(&'b mut self) -> Builder<'b> {
Builder { builder : self.builder}
}
pub fn total_size(&self) -> Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
}
pub struct Pipeline { _typeless : ::capnp::any_pointer::Pipeline }
impl FromTypelessPipeline for Pipeline {
fn new(typeless : ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless : typeless }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE : layout::StructSize = layout::StructSize { data : 0, pointers : 0 };
pub const TYPE_ID: u64 = 0x89e635625cdc9d49;
}
}
}
|
use std::io::{BufReader, BufferedReader, Buffer, File, EndOfFile};
use std::comm::{channel, Sender, Receiver};
use std::vec::Vec;
use std::char;
use token::Token;
use token;
pub fn tokenize_str(code : &str) -> Vec<Token> {
let reader = BufReader::new(code.as_bytes());
let buf_reader = BufferedReader::new(reader);
let mut scanner = Scanner::new(buf_reader);
scanner.collect()
}
pub fn tokenize_file(path_str : &str) -> Vec<Token> {
let path = &Path::new(path_str);
let mut file = match File::open(path) {
Ok(f) => BufferedReader::new(f),
Err(msg) => fail!(msg)
};
let mut scanner = Scanner::new(file);
scanner.collect()
}
pub fn stream_from_str(code : &str) -> Receiver<Token> {
let (sendr, recvr) = channel();
let code = code.to_string();
spawn(proc(){
let reader = BufReader::new(code.as_bytes());
let buf_reader = BufferedReader::new(reader);
let mut scanner = Scanner::new(buf_reader);
scanner.stream(sendr);
});
recvr
}
pub fn stream_from_file(path_str : &str) -> Receiver<Token> {
let (sendr, recvr) = channel();
let path_str = path_str.to_string();
spawn(proc(){
let path = &Path::new(path_str);
let mut file = match File::open(path) {
Ok(f) => BufferedReader::new(f),
Err(msg) => fail!(msg)
};
let mut scanner = Scanner::new(file);
scanner.stream(sendr);
});
recvr
}
struct Scanner<B> {
input : B,
peek_buff : String,
text_buff : String,
line : uint,
col : uint,
buf_offset : uint
}
impl<B: Buffer> Scanner<B> {
pub fn new(input : B) -> Scanner<B>{
Scanner {
peek_buff : String::new(),
text_buff : String::new(),
input : input,
line : 1,
col : 1,
buf_offset : 0
}
}
fn tok(&mut self) -> Token {
let text = self.text_buff.as_slice().to_string();
let l = self.col - text.len();
let offset = self.buf_offset - text.as_bytes().len();
let typ = token::str_to_type(text.as_slice());
self.text_buff.clear();
Token {
text : text,
typ : typ,
line : self.line,
col : l,
buf_offset : offset
}
}
fn for_each_token(&mut self, cb : |Token|) {
loop {
match self.next_token() {
Some(tok) => cb(tok),
None => break
}
}
}
fn stream(&mut self, sendr : Sender<Token>) {
self.for_each_token(|tok : Token|{
sendr.send(tok);
});
}
fn collect(&mut self) -> Vec<Token> {
let mut tokens = Vec::new();
self.for_each_token(|tok : Token|{
tokens.push(tok);
});
tokens
}
fn consume(&mut self, c : char) {
self.change_pos(c);
self.text_buff.push_char(c);
}
fn consume_while(&mut self, condition : |char| -> bool) {
loop {
match self.next_char() {
Some(c) => {
if condition(c) {
self.consume(c);
} else {
self.peek_buff.push_char(c);
break;
}
}
None => break
};
}
}
fn change_pos(&mut self, c : char) {
if c == '\n' {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
};
}
fn next_char(&mut self) -> Option<char> {
let result = if self.peek_buff.is_empty() {
match self.input.read_char() {
Ok(c) => Some(c),
Err(e) => {
if e.kind != EndOfFile {
fail!(e);
}
None
}
}
} else {
Some(self.peek_buff.pop_char().unwrap())
};
if result.is_some() {
self.buf_offset += char::len_utf8_bytes(result.unwrap());
}
result
}
fn consume_next_if(&mut self, c : char) {
self.next_char_is(c);
}
fn next_char_is(&mut self, target : char) -> bool {
if self.peek_buff.is_empty() {
match self.input.read_char() {
Ok(next_char) => {
if next_char == target {
self.consume(target);
true
} else {
self.peek_buff.push_char(next_char);
false
}
},
_ => false
}
} else {
let l = self.peek_buff.len() - 1;
let next_char = self.peek_buff.as_slice().char_at(l);
if next_char == target {
self.peek_buff.pop_char();
self.consume(target);
true
} else {
false
}
}
}
fn int_or_float_token(&mut self, start : char) -> Option<Token> {
self.consume(start);
self.consume_while(|c : char| -> bool {
char::is_digit(c)
});
if self.next_char_is('.') {
self.consume_while(|c : char| -> bool {
char::is_digit(c)
});
}
Some(self.tok())
}
fn ident_or_keyword_token(&mut self, start : char) -> Option<Token> {
self.consume(start);
self.consume_while(|c : char|{
(char::is_alphanumeric(c) || c == '?' || c == '!' || c == '_')
});
Some(self.tok())
}
fn binary_token(&mut self) -> Option<Token> {
self.consume_while(|c : char| -> bool {
char::is_digit_radix(c, 2)
});
if self.text_buff.len() < 3 {
fail!("Binary prefix not followed by any binary digits.");
}
Some(self.tok())
}
fn hex_token(&mut self) -> Option<Token> {
self.consume_while(|c : char| -> bool {
char::is_digit_radix(c, 16)
});
if self.text_buff.len() < 3 {
fail!("Hex prefix not followed by any hex digits.");
}
Some(self.tok())
}
fn period_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
if self.next_char_is(c) {
self.consume_next_if(c);
}
Some(self.tok())
}
fn equal_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
self.consume_next_if('=');
Some(self.tok())
}
fn pipe_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
self.consume_next_if('|');
self.consume_next_if('=');
Some(self.tok())
}
fn double_or_equal_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
if !self.next_char_is(c) {
self.consume_next_if('=')
}
Some(self.tok())
}
fn dash_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
if !self.next_char_is(c){
if !self.next_char_is('>'){
self.consume_next_if('=');
}
}
Some(self.tok())
}
fn less_than_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
if !self.next_char_is(c){
if !self.next_char_is('-'){
self.consume_next_if('=');
}
}
Some(self.tok())
}
fn class_inst_var_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
self.consume_next_if('_');
Some(self.tok())
}
fn string_lit_token(&mut self, quote : char) -> Option<Token> {
self.consume(quote);
self.consume_while(|c : char| -> bool {
c != quote
});
self.consume_next_if(quote);
Some(self.tok())
}
fn backslash_token(&mut self, c : char) -> Option<Token> {
self.consume(c);
if !self.next_char_is('='){
//TODO: validate escaped strings
if self.next_char_is('*'){
let mut last_char = ' ';
self.consume_while(|c : char| -> bool {
let continu = if c == '/' && last_char == '*' {
false
} else {
true
};
last_char = c;
continu
});
self.consume_next_if('/');
if !self.text_buff.as_slice().contains("*/") {
fail!("Failed to end multiline comment");
}
} else if self.next_char_is(c) {
self.consume_while(|c : char| -> bool {
c != '\n'
});
}
}
Some(self.tok())
}
fn next_token(&mut self) -> Option<Token> {
match self.next_char() {
Some(c) => {
match c {
'?' | ',' | ';' | ':' | '~' | '{' | '}' | '[' | ']' | '(' | ')' => {
self.consume(c);
Some(self.tok())
},
'.' => {
//., .., ...
self.period_token(c)
},
'*' | '%' | '^' | '!' | '=' => {
//*, *=, %, %=, /, /=, !, != ...etc
self.equal_token(c)
},
'|' => {
//|, ||, |=, ||=
self.pipe_token(c)
},
'+' | '&' | '>' => {
//++, +=, +, &&, &=, &
self.double_or_equal_token(c)
},
'-' => {
//-, -=, ->, --
self.dash_token(c)
},
'<' => {
//<, <<, <=, <-
self.less_than_token(c)
},
'@' | '#' => {
//@, @_, #, #_
self.class_inst_var_token(c)
},
'\'' | '"' => {
//'myString', "myString"
self.string_lit_token(c)
},
'/' => {
// /, /=, //, /*
self.backslash_token(c)
},
'0' => {
//0b10110, 0B101001, 0xdeadBeef, 0XDeadBEEf
self.consume(c);
if self.next_char_is('b') || self.next_char_is('B') {
self.binary_token()
} else if self.next_char_is('x') || self.next_char_is('X') {
self.hex_token()
} else {
Some(self.tok())
}
},
'_' => {
self.ident_or_keyword_token(c)
},
_ if char::is_digit(c) => {
self.int_or_float_token(c)
},
_ if char::is_alphabetic(c) => {
self.ident_or_keyword_token(c)
},
_ if char::is_whitespace(c) => {
//may not want to skip...
if c == '\n' {
self.consume(c);
Some(self.tok())
} else {
self.change_pos(c);
self.next_token()
}
},
_ => fail!("Unrecognized character at {}:{}", self.line, self.col)
}
},
None => None
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Tests //
////////////////////////////////////////////////////////////////////////////////
macro_rules! test_types(
($code:expr -> [ $($tok_typ:ident),+ ]) => (
{
let mut i = 0;
let tokens = tokenize_str($code);
$(
let t = tokens.get(i);
match t.typ {
token::$tok_typ => {},
_ => fail!("Expected token at {} to be {:?} but it was {}", i + 1, token::$tok_typ, t.typ)
}
i += 1;
)+
}
);
)
#[test]
fn single_char_tokens(){
test_types!("?,~;:{}()[]" -> [
Question, Comma, Bit_Negate, Semicolon, Colon,
Lcurly, Rcurly, Lparen, Rparen, Lbracket, Rbracket
]);
}
#[test]
fn num_tokens(){
test_types!("0 123 1.2 2334.2313 0XDeadBEEf 0x123abc 0x5 0b0100 0B1010 0b1" -> [
Int_Literal, Int_Literal, Float_Literal, Float_Literal, Hex_Literal,
Hex_Literal, Hex_Literal, Binary_Literal, Binary_Literal, Binary_Literal
]);
}
#[test]
#[should_fail]
fn hex_token_fail() {
tokenize_str("0x");
}
#[test]
#[should_fail]
fn binary_token_fail() {
tokenize_str("0b");
}
#[test]
fn period_tokens() {
test_types!(". .. ..." -> [Period, Excl_Range, Incl_Range]);
}
#[test]
fn pipe_tokens(){
test_types!("| || |= ||=" -> [
Bit_Or, Logical_Or, Bit_Or_Eq, Logical_Or_Eq
])
}
#[test]
fn equal_tokens(){
test_types!("* *= % %= ^ ^= ! != = ==" -> [
Mult_Op, Times_Eq, Mod_Op, Mod_Eq, Power_Op, Power_Eq, Bang,
Bang_Eq, Assign, Equal
]);
}
#[test]
fn double_or_equal_tokens(){
test_types!("+ ++ += & && &= > >> >=" -> [
Add_Op, Increment, Plus_Eq, Bit_And, Logical_And, Bit_And_Eq,
Greater_Than, Rshovel, Greater_Than_Eq
]);
}
#[test]
fn dash_tokens(){
test_types!("- -- -= ->" -> [
Min_Op, Decrement, Min_Eq, Chan_Send
]);
}
#[test]
fn less_than_tokens(){
test_types!("< << <= <-" -> [
Less_Than, Lshovel, Less_Than_Eq, Chan_Recv
]);
}
#[test]
fn class_inst_var_tokens(){
test_types!("@ @_ # #_" -> [
Pub_Inst_Var, Priv_Inst_Var, Pub_Class_Var, Priv_Class_Var
]);
}
#[test]
fn string_lit_tokens(){
test_types!("'abc123$%^&* ' \"abc123#$%&* \" " -> [
String_Literal, String_Literal
]);
}
#[test]
fn backslash_tokens(){
test_types!("/ /= /****This is a \n multiline comment****///this is a comment\n/****This is a \n multiline comment****/" -> [
Div_Op, Div_Eq, Multiline_Comment, Singleline_Comment, NewLine, Multiline_Comment
])
}
#[test]
fn keyword_tokens() {
test_types!("function spawn if else then for in while do not and or from to by
end class import as export super supers this return operator extends
gen either wait_for break continue yield given is var true false new
upto through" -> [
Function, Spawn, If, Else, Then, For, In, While, Do, Not, And, Or, From, To, By, NewLine,
End, Class, Import, As, Export, Super, Supers, This, Return, Operator, Extends, NewLine,
Generator, Either, Wait_For, Break, Continue, Yield, Given, Is, Var, True,
False, New, NewLine, Upto, Through
]);
}
#[test]
fn ident_tokens(){
test_types!("abc _cat cat_in_a_hat? cat_in_2_hats!" -> [
Identifier, Identifier, Identifier, Identifier
]);
}
#[test]
fn newline_token(){
test_types!("abc \n\n" -> [
Identifier, NewLine, NewLine
]);
} |
use lazy_static::*;
use regex::Regex;
use std::collections::HashMap;
use crate::common::str_to_numbers;
pub fn get_rule_set(input: &str) -> HashMap<Vec<u8>, u8> {
lazy_static! {
static ref PARSING_EXPR: Regex =
Regex::new(r"^(?P<input>[#.]{5}) => (?P<output>[#.])").unwrap();
}
let mut map = HashMap::new();
for line in input.lines() {
let captures = PARSING_EXPR
.captures(line)
.unwrap_or_else(|| panic!(format!("Invalid line \"{}\"", line)));
map.insert(
str_to_numbers(&captures["input"]),
str_to_numbers(&captures["output"])[0],
);
}
map
}
|
// q0002_add_two_numbers
use crate::util::ListNode;
struct Solution;
impl Solution {
pub fn add_two_numbers(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut ret = vec![];
let mut flag = 0;
let mut l1 = l1;
let mut l2 = l2;
let mut output = None;
loop {
if l1 == None && l2 == None {
break;
}
let c1 = if l1 == None {
0
} else {
let t1 = l1.unwrap();
l1 = t1.next;
t1.val
};
let c2 = if l2 == None {
0
} else {
let t2 = l2.unwrap();
l2 = t2.next;
t2.val
};
let mut n = c1 + c2 + flag;
if n >= 10 {
n -= 10;
flag = 1;
} else {
flag = 0;
}
ret.push(n)
}
if flag == 1 {
ret.push(1)
}
while let Some(n) = ret.pop() {
output = Some(Box::new(ListNode {
val: n,
next: output,
}));
}
output
}
}
#[cfg(test)]
mod tests {
use super::Solution;
use crate::util::ListNode;
#[test]
fn it_works() {
assert_eq!(
Solution::add_two_numbers(
ListNode::build(vec![2, 4, 3]),
ListNode::build(vec![5, 6, 4])
),
ListNode::build(vec![7, 0, 8])
);
}
}
|
use std::path::Path;
use anyhow::Result;
#[allow(dead_code)]
#[allow(unused_variables)]
pub fn parse_args(in_graph: &Path, rank_cutoff: Option<&f64>) -> Result<()> {
error!("Not implemented yet");
Ok(())
}
|
// q0164_maximum_gap
struct Solution;
impl Solution {
pub fn maximum_gap(mut nums: Vec<i32>) -> i32 {
if nums.len() < 2 {
return 0;
}
let build_buf = || {
let mut r = Vec::with_capacity(10);
for _ in 0..10 {
r.push(vec![]);
}
r
};
let mut swap_nums = Vec::with_capacity(nums.len());
for i in 0..10 {
let mut base = 1;
for _ in 0..i {
base *= 10;
}
let mut buf = build_buf();
for n in nums.iter().cloned() {
let bi = n / base % 10;
buf[bi as usize].push(n);
}
swap_nums.clear();
for vi in buf.iter() {
for n in vi.iter().cloned() {
swap_nums.push(n);
}
}
std::mem::swap(&mut swap_nums, &mut nums);
}
let mut max_gap = 0;
for i in 0..nums.len() - 1 {
max_gap = max_gap.max(nums[i + 1] - nums[i]);
}
max_gap
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
assert_eq!(0, Solution::maximum_gap(vec![1, 1]));
assert_eq!(3, Solution::maximum_gap(vec![3, 6, 9, 1]));
assert_eq!(
i32::max_value(),
Solution::maximum_gap(vec![0, i32::max_value()])
);
}
}
|
use std::fs::File;
use resol_vbus::{DataSet, RecordingWriter};
use tokio::{net::TcpStream, prelude::*};
use tokio_resol_vbus::{Error, LiveDataStream, TcpClientHandshake};
fn main() {
// Create an recording file and hand it to a `RecordingWriter`
let file = File::create("test.vbus").expect("Unable to create output file");
let mut rw = RecordingWriter::new(file);
let addr = "192.168.13.45:7053"
.parse()
.expect("Unable to parse address");
let handler = TcpStream::connect(&addr)
.map_err(Error::from)
.and_then(TcpClientHandshake::start)
.and_then(|hs| hs.send_pass_command("vbus"))
.and_then(|hs| hs.send_data_command())
.and_then(|socket| {
let (reader, writer) = socket.split();
let stream = LiveDataStream::new(reader, writer, 0, 0x0020);
// Read VBus `Data` values from the `LiveDataStream`
stream.for_each(move |data| {
println!("{}", data.id_string());
// Add `Data` value into `DataSet` to be stored
let mut data_set = DataSet::new();
data_set.timestamp = data.as_ref().timestamp;
data_set.add_data(data);
// Write the `DataSet` into the `RecordingWriter` for permanent storage
rw.write_data_set(&data_set)
.expect("Unable to write data set");
Ok(())
})
})
.map_err(|err| {
eprintln!("{}", err);
});
tokio::run(handler);
}
|
use regex::Regex;
use std::fs::File;
use std::io::Read;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Action {
MoveNorth,
MoveSouth,
MoveEast,
MoveWest,
TurnRight,
TurnLeft,
MoveForward,
}
#[derive(Debug)]
pub struct BoatPart1 {
angle: i32,
orientation_y: i32,
orientation_x: i32,
position_y: i32,
position_x: i32,
}
impl BoatPart1 {
pub fn new() -> BoatPart1 {
BoatPart1 {
angle: 90,
orientation_y: 0,
orientation_x: 1, // the boat starts facing east
position_y: 0,
position_x: 0,
}
}
pub fn get_dist_from_start(&self) -> i32 {
self.position_x.abs() + self.position_y.abs()
}
pub fn do_action(&mut self, action: Action, value: i32) {
match action {
Action::MoveNorth => self.move_north(value),
Action::MoveSouth => self.move_south(value),
Action::MoveEast => self.move_east(value),
Action::MoveWest => self.move_west(value),
Action::TurnLeft => self.turn_left(value),
Action::TurnRight => self.turn_right(value),
Action::MoveForward => self.move_forward(value),
}
}
fn move_south(&mut self, value: i32) {
self.position_y -= value
}
fn move_north(&mut self, value: i32) {
self.position_y += value
}
fn move_east(&mut self, value: i32) {
self.position_x += value
}
fn move_west(&mut self, value: i32) {
self.position_x -= value
}
fn turn_left(&mut self, value: i32) {
self.angle -= value;
self.orientation_y = (self.angle as f64).to_radians().cos() as i32;
self.orientation_x = (self.angle as f64).to_radians().sin() as i32;
}
fn turn_right(&mut self, value: i32) {
self.angle += value;
self.orientation_y = (self.angle as f64).to_radians().cos() as i32;
self.orientation_x = (self.angle as f64).to_radians().sin() as i32;
}
fn move_forward(&mut self, value: i32) {
self.position_x += self.orientation_x * value;
self.position_y += self.orientation_y * value;
}
}
struct BoatPart2 {
position_y: i32,
position_x: i32,
waypoint_y: i32,
waypoint_x: i32,
}
impl BoatPart2 {
pub fn new() -> BoatPart2 {
BoatPart2 {
position_y: 0,
position_x: 0,
waypoint_y: 1,
waypoint_x: 10,
}
}
pub fn get_dist_from_start(&self) -> i32 {
self.position_x.abs() + self.position_y.abs()
}
pub fn do_action(&mut self, action: Action, value: i32) {
match action {
Action::MoveNorth => self.move_north(value),
Action::MoveSouth => self.move_south(value),
Action::MoveEast => self.move_east(value),
Action::MoveWest => self.move_west(value),
Action::TurnLeft => self.turn_left(value),
Action::TurnRight => self.turn_right(value),
Action::MoveForward => self.move_forward(value),
}
}
fn move_south(&mut self, value: i32) {
self.waypoint_y -= value
}
fn move_north(&mut self, value: i32) {
self.waypoint_y += value
}
fn move_east(&mut self, value: i32) {
self.waypoint_x += value
}
fn move_west(&mut self, value: i32) {
self.waypoint_x -= value
}
fn turn_left(&mut self, value: i32) {
let cos = (value as f64).to_radians().cos() as i32;
let sin = (value as f64).to_radians().sin() as i32;
let new_x = self.waypoint_x * cos - self.waypoint_y * sin;
let new_y = self.waypoint_x * sin + self.waypoint_y * cos;
self.waypoint_x = new_x;
self.waypoint_y = new_y;
}
fn turn_right(&mut self, value: i32) {
let cos = (-value as f64).to_radians().cos() as i32;
let sin = (-value as f64).to_radians().sin() as i32;
let new_x = self.waypoint_x * cos - self.waypoint_y * sin;
let new_y = self.waypoint_x * sin + self.waypoint_y * cos;
self.waypoint_x = new_x;
self.waypoint_y = new_y;
}
fn move_forward(&mut self, value: i32) {
self.position_x += self.waypoint_x * value;
self.position_y += self.waypoint_y * value;
}
}
pub fn parse_input(input: &str) -> Vec<(Action, i32)> {
lazy_static! {
static ref RE: Regex = Regex::new(r"(?P<action>N|S|E|W|L|R|F)(?P<value>\d+)").unwrap();
}
input
.lines()
.map(|line| {
let captures = RE.captures(line).unwrap();
(
match &captures["action"] {
"N" => Action::MoveNorth,
"E" => Action::MoveEast,
"S" => Action::MoveSouth,
"W" => Action::MoveWest,
"L" => Action::TurnLeft,
"R" => Action::TurnRight,
"F" => Action::MoveForward,
_ => panic!(),
},
captures["value"].parse().unwrap(),
)
})
.collect()
}
pub fn solve_part1(input: &[(Action, i32)]) -> i32 {
let mut boat = BoatPart1::new();
input
.iter()
.for_each(|(action, value)| boat.do_action(*action, *value));
boat.get_dist_from_start()
}
pub fn part1() {
let mut file = File::open("input/2020/day12.txt").unwrap();
let mut input = String::new();
file.read_to_string(&mut input).unwrap();
println!("{}", solve_part1(&parse_input(&input)));
}
pub fn solve_part2(input: &[(Action, i32)]) -> i32 {
let mut boat = BoatPart2::new();
input
.iter()
.for_each(|(action, value)| boat.do_action(*action, *value));
boat.get_dist_from_start()
}
pub fn part2() {
let mut file = File::open("input/2020/day12.txt").unwrap();
let mut input = String::new();
file.read_to_string(&mut input).unwrap();
println!("{}", solve_part2(&parse_input(&input)));
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_example() {
assert_eq!(
parse_input("F10\nN3\nF7\nR90\nF11"),
vec![
(Action::MoveForward, 10),
(Action::MoveNorth, 3),
(Action::MoveForward, 7),
(Action::TurnRight, 90),
(Action::MoveForward, 11)
]
);
}
#[test]
fn test_part1_example_actions() {
let mut boat = BoatPart1::new();
boat.do_action(Action::MoveForward, 10);
assert_eq!((boat.position_y, boat.position_x), (0, 10));
boat.do_action(Action::MoveNorth, 3);
assert_eq!((boat.position_y, boat.position_x), (3, 10));
boat.do_action(Action::MoveForward, 7);
assert_eq!((boat.position_y, boat.position_x), (3, 17));
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.orientation_y, boat.orientation_x), (-1, 0));
boat.do_action(Action::MoveForward, 11);
assert_eq!((boat.position_y, boat.position_x), (-8, 17));
}
#[test]
fn test_part2_example_actions() {
let mut boat = BoatPart2::new();
boat.do_action(Action::MoveForward, 10);
assert_eq!((boat.position_y, boat.position_x), (10, 100));
assert_eq!((boat.waypoint_y, boat.waypoint_x), (1, 10));
boat.do_action(Action::MoveNorth, 3);
assert_eq!((boat.position_y, boat.position_x), (10, 100));
assert_eq!((boat.waypoint_y, boat.waypoint_x), (4, 10));
boat.do_action(Action::MoveForward, 7);
assert_eq!((boat.position_y, boat.position_x), (38, 170));
assert_eq!((boat.waypoint_y, boat.waypoint_x), (4, 10));
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.position_y, boat.position_x), (38, 170));
assert_eq!((boat.waypoint_y, boat.waypoint_x), (-10, 4));
boat.do_action(Action::MoveForward, 11);
assert_eq!((boat.position_y, boat.position_x), (-72, 214));
assert_eq!((boat.waypoint_y, boat.waypoint_x), (-10, 4));
}
#[test]
fn test_part1_solve_example() {
assert_eq!(solve_part1(&parse_input("F10\nN3\nF7\nR90\nF11")), 25)
}
#[test]
fn test_part1_rotation() {
let mut boat = BoatPart1::new();
assert_eq!((boat.orientation_y, boat.orientation_x), (0, 1));
boat.do_action(Action::TurnLeft, 180);
assert_eq!((boat.orientation_y, boat.orientation_x), (0, -1));
boat.do_action(Action::TurnLeft, 180);
assert_eq!((boat.orientation_y, boat.orientation_x), (0, 1));
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.orientation_y, boat.orientation_x), (-1, 0));
boat.do_action(Action::TurnLeft, 180);
assert_eq!((boat.orientation_y, boat.orientation_x), (1, 0));
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.orientation_y, boat.orientation_x), (0, 1));
boat.do_action(Action::TurnRight, 270);
assert_eq!((boat.orientation_y, boat.orientation_x), (1, 0));
boat.do_action(Action::TurnLeft, 90);
assert_eq!((boat.orientation_y, boat.orientation_x), (0, -1));
boat.do_action(Action::TurnRight, 180);
assert_eq!((boat.orientation_y, boat.orientation_x), (0, 1));
boat.do_action(Action::TurnRight, 360);
assert_eq!((boat.orientation_y, boat.orientation_x), (0, 1));
}
#[test]
fn test_part2_rotation() {
let mut boat = BoatPart2::new();
assert_eq!((boat.waypoint_y, boat.waypoint_x), (1, 10));
boat.do_action(Action::TurnLeft, 180);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (-1, -10));
boat.do_action(Action::TurnRight, 180);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (1, 10));
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (-10, 1));
boat.do_action(Action::TurnLeft, 180);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (10, -1));
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (1, 10));
boat.do_action(Action::TurnRight, 270);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (10, -1));
boat.do_action(Action::TurnLeft, 90);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (-1, -10));
boat.do_action(Action::TurnRight, 180);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (1, 10));
boat.do_action(Action::TurnRight, 360);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (1, 10));
boat.waypoint_y = 4;
boat.waypoint_x = 10;
boat.do_action(Action::TurnRight, 90);
assert_eq!((boat.waypoint_y, boat.waypoint_x), (-10, 4));
}
}
|
mod util;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::io::BufRead;
use util::*;
struct Node {
children: HashSet<String>,
parent: HashSet<String>,
}
impl Node {
fn new() -> Node {
Node { children: HashSet::new(), parent: HashSet::new() }
}
}
type Graph = HashMap<String, Node>;
macro_rules! G {
($graph:expr, Add $name:expr) => {
$graph.insert($name.to_string(), Node::new());
};
($graph:expr, Insert $child:expr, Into $parent:expr) => {
match $graph.get_mut($parent) {
Some(node) => node.children.insert($child.to_string()),
None => error_exit(&format!("{} don't exist", $parent)),
};
match $graph.get_mut($child) {
Some(node) => node.parent.insert($parent.to_string()),
None => error_exit(&format!("{} don't exist", $child)),
};
};
}
fn parse_node_list() -> Graph {
let mut graph: Graph = Graph::new();
for line in lines_from_stdin!() {
let mut tokens = line.split(')').take(2);
let child = tokens.next().unwrap();
let parent = tokens.next().unwrap();
if !graph.contains_key(child) {
G!(graph, Add child);
};
if !graph.contains_key(parent) {
G!(graph, Add parent);
};
G!(graph, Insert child, Into parent);
}
graph
}
fn count_path(node: &str, graph: &Graph, mem: &mut HashMap<String, usize>) -> usize {
if mem.contains_key(node) {
return mem[node];
};
let count = match graph[node].children.len() {
0 => 0, // COM
_ => graph[node]
.children
.iter()
.map(|child| count_path(child, graph, mem) + 1)
.sum(),
};
mem.insert(node.to_string(), count);
count
}
fn total_orbits(graph: &Graph) -> usize {
let mut mem = HashMap::new();
let total_count = graph
.keys()
.map(|key| count_path(key, graph, &mut mem))
.sum();
mem.iter()
.for_each(|(key, value)| println!("{} : {}", key, value));
total_count
}
fn shortest_path(graph: &Graph, start: &str, end: &str) -> usize {
let mut distances: HashMap<String, usize> = HashMap::new();
for key in graph.keys() {
distances.insert(
key.to_string(),
if key == start { 0 } else { std::usize::MAX },
);
}
let mut visited : HashSet<String> = HashSet::new();
visited.insert(start.to_string());
let mut queue : VecDeque<&str> = VecDeque::new();
queue.push_back(start);
while queue.len() > 0 {
let node_name = queue.pop_front().unwrap();
eprintln!("Visiting {}", node_name);
let node = &graph[node_name];
let distance = distances[node_name] + 1;
for neighbor in node.children
.iter()
.chain(node.parent.iter())
.filter(|&node_name| !visited.contains(node_name))
{
let d = distances.get_mut(neighbor).unwrap();
*d = (*d).min(distance);
queue.push_back(neighbor);
};
visited.insert(node_name.to_string());
}
distances[end]
}
fn main() {
let graph = parse_node_list();
match part_id_from_cli() {
PartID::One => println!("{}", total_orbits(&graph)),
PartID::Two => {
let start = graph["YOU"].children.iter().next().unwrap();
let end = graph["SAN"].children.iter().next().unwrap();
println!("{}", shortest_path(&graph, start, end));
},
};
}
|
use core::f64::consts::*;
use crate::coord_plane::CartPoint;
use crate::coord_plane::PolarPoint;
use crate::projections::projection_types::ProjectionParams;
pub fn simple_equidistant_conic(params: ProjectionParams) -> Vec<CartPoint> {
match params {
ProjectionParams::PointsTwoStandardPar(points, phi_1, phi_2) => {
let temp = (phi_2 * phi_1.cos() -
phi_1 * phi_2.cos())
/ (phi_1.cos() - phi_2.cos());
let n = (phi_1.cos() - phi_2.cos())/(phi_2 - phi_1);
points.iter().map(
|llpoint| {
let rho = temp - llpoint.phi;
let theta = n * llpoint.lambda;
PolarPoint { rho: rho, theta: theta }.to_cart()
}).collect()
},
_ => panic!("Invalid parameters {:?} passed in"),
}
}
pub fn lambert_conformal_conic(params: ProjectionParams) -> Vec<CartPoint> {
match params {
ProjectionParams::PointsTwoStandardPar(points, phi_1, phi_2) => {
let n = (
(phi_1.cos().ln() -
phi_2.cos().ln())
) / (
(FRAC_PI_4 + phi_2).tan().ln() -
(FRAC_PI_4 + phi_1).tan().ln());
points.iter().map(
|llpoint| {
let theta = n * llpoint.lambda;
let rho =
phi_1.cos() *
(FRAC_PI_4 + phi_1/2.0).tan().powf(n)
/
(n * (FRAC_PI_4 + llpoint.phi/2.0).tan().powf(n));
PolarPoint { rho: rho, theta: theta }.to_cart()
}).collect()
},
_ => panic!("Invalid parameters {:?} passed in"),
}
}
|
use bytes::BufMut;
use futures::future::{self, Future};
use futures::sync::oneshot;
use futures::task;
use std::collections::{HashMap, VecDeque};
use std::iter;
use std::sync::{Arc, Mutex};
use super::{QuicError, QuicResult};
use codec::{BufLen, Codec};
use frame::{Frame, StreamFrame, StreamIdBlockedFrame};
use types::Side;
#[derive(Clone)]
pub struct Streams {
inner: Arc<Mutex<Inner>>,
}
impl Streams {
pub fn new(side: Side) -> Self {
let mut open = [
OpenStreams::new(),
OpenStreams::new(),
OpenStreams::new(),
OpenStreams::new(),
];
open[0].next = Some(0);
Self {
inner: Arc::new(Mutex::new(Inner {
side,
task: None,
streams: HashMap::new(),
open,
control: VecDeque::new(),
send_queue: VecDeque::new(),
})),
}
}
pub fn set_task(&mut self, task: task::Task) {
let mut me = self.inner.lock().unwrap();
me.task = Some(task);
}
pub fn poll_send<T: BufMut>(&mut self, payload: &mut T) {
let mut me = self.inner.lock().unwrap();
while let Some(frame) = me.control.pop_front() {
frame.encode(payload);
}
while let Some((id, start, mut end)) = me.send_queue.pop_front() {
if payload.remaining_mut() < 16 {
me.send_queue.push_front((id, start, end));
break;
}
let mut frame = StreamFrame {
id,
fin: false,
offset: start as u64,
len: Some((end - start) as u64),
data: Vec::new(),
};
let len = end - start;
if len > payload.remaining_mut() {
let pivot = start + payload.remaining_mut() - frame.buf_len();
me.send_queue.push_front((id, pivot, end));
end = pivot;
frame.len = Some((end - start) as u64);
}
let mut stream = &me.streams[&id];
let offset = stream.send_offset;
let (start, mut end) = (start - offset, end - offset);
let slices = stream.queued.as_slices();
if start < slices.0.len() && end <= slices.0.len() {
frame.data.extend(&slices.0[start..end]);
} else if start < slices.0.len() {
frame.data.extend(&slices.0[start..]);
end -= slices.0.len();
frame.data.extend(&slices.1[..end]);
} else {
let (start, end) = (start - slices.0.len(), end - slices.0.len());
frame.data.extend(&slices.1[start..end]);
}
debug_assert_eq!(frame.len, Some((end - start) as u64));
let frame = Frame::Stream(frame);
frame.encode(payload);
}
println!("debug : streams poll_send");
}
pub fn get_stream(&self, id: u64) -> Option<StreamRef> {
let me = self.inner.lock().unwrap();
if me.streams.contains_key(&id) {
Some(StreamRef {
inner: self.inner.clone(),
id,
})
} else {
None
}
}
pub fn init_send(&self, dir: Dir) -> QuicResult<StreamRef> {
let mut me = self.inner.lock().unwrap();
let stype = (me.side.to_bit() + dir.to_bit()) as usize;
let next = me.open[stype].next;
if let Some(id) = next {
me.open[stype].next = if id + 4 < me.open[stype].max {
Some(id + 4)
} else {
None
};
}
next.map(|id| {
me.streams.insert(id, Stream::new());
StreamRef {
inner: self.inner.clone(),
id,
}
}).ok_or_else(|| {
QuicError::General(format!(
"{:?} not allowed to send on stream {:?} [init send]",
me.side, next
))
})
}
pub fn update_max_id(&mut self, id: u64) {
let mut me = self.inner.lock().unwrap();
me.open[(id % 4) as usize].max = id;
}
pub fn received(&mut self, frame: &StreamFrame) -> QuicResult<()> {
let mut me = self.inner.lock().unwrap();
let id = frame.id;
if Dir::from_id(id) == Dir::Uni && Side::from_id(id) == me.side {
return Err(QuicError::General(format!(
"{:?} not allowed to receive on stream {:?} [direction]",
me.side, id
)));
}
if !me.streams.contains_key(&id) {
let stype = (id % 4) as usize;
if let Some(id) = me.open[stype].next {
me.open[stype].next = if id + 4 <= me.open[stype].max {
Some(id + 4)
} else {
None
};
} else {
return Err(QuicError::General(format!(
"{:?} not allowed to receive on stream {:?} [limited]",
me.side, id
)));
}
}
let stream = me.streams.entry(id).or_insert_with(Stream::new);
let offset = frame.offset as usize;
let expected = stream.recv_offset + stream.received.len();
if offset == expected {
stream.received.extend(&frame.data);
} else if offset > expected {
stream
.received
.extend(iter::repeat(0).take(offset - expected));
stream.received.extend(&frame.data);
} else {
return Err(QuicError::General(format!(
"unhandled receive: {:?} {:?} {:?}",
frame.offset, frame.len, expected
)));
}
Ok(())
}
pub fn request_stream(self, id: u64) -> Box<Future<Item = Streams, Error = QuicError>> {
let consumer = {
let mut me = self.inner.lock().unwrap();
let consumer = {
let open = me.open.get_mut((id % 4) as usize).unwrap();
if id > open.max {
let (p, c) = oneshot::channel::<u64>();
open.updates.push(p);
Some(c)
} else {
None
}
};
if consumer.is_some() {
me.control
.push_back(Frame::StreamIdBlocked(StreamIdBlockedFrame(id)));
if let Some(ref mut task) = me.task {
task.notify();
}
}
consumer
};
match consumer {
Some(c) => Box::new(
c.map(|_| self)
.map_err(|_| QuicError::General("StreamIdBlocked future canceled".into())),
),
None => Box::new(future::ok(self)),
}
}
}
pub struct StreamRef {
inner: Arc<Mutex<Inner>>,
pub id: u64,
}
impl StreamRef {
pub fn send(&self, buf: &[u8]) -> QuicResult<()> {
if buf.is_empty() {
return Ok(());
}
let mut me = self.inner.lock().unwrap();
if Dir::from_id(self.id) == Dir::Uni && Side::from_id(self.id) != me.side {
return Err(QuicError::General(format!(
"{:?} not allowed to send on stream {:?} [send]",
me.side, self.id
)));
}
let (start, end) = {
let stream = me.streams.get_mut(&self.id).unwrap();
let start = stream.send_offset + stream.queued.len();
stream.queued.extend(buf);
(start, start + buf.len())
};
me.send_queue.push_back((self.id, start, end));
Ok(())
}
pub fn received(&self) -> QuicResult<Vec<u8>> {
let mut me = self.inner.lock().unwrap();
if Dir::from_id(self.id) == Dir::Uni && Side::from_id(self.id) == me.side {
return Err(QuicError::General(format!(
"{:?} not allowed to receive on stream {:?}",
me.side, self.id
)));
}
let stream = me.streams.get_mut(&self.id).unwrap();
let vec = stream.received.drain(..).collect::<Vec<u8>>();
stream.recv_offset += vec.len();
Ok(vec)
}
}
struct Inner {
side: Side,
task: Option<task::Task>,
streams: HashMap<u64, Stream>,
open: [OpenStreams; 4],
control: VecDeque<Frame>,
send_queue: VecDeque<(u64, usize, usize)>,
}
#[derive(Default)]
struct Stream {
send_offset: usize,
recv_offset: usize,
queued: VecDeque<u8>,
received: VecDeque<u8>,
}
impl Stream {
fn new() -> Self {
Self {
..Default::default()
}
}
}
#[derive(Debug)]
struct OpenStreams {
next: Option<u64>,
max: u64,
updates: Vec<oneshot::Sender<u64>>,
}
impl OpenStreams {
fn new() -> Self {
Self {
next: None,
max: 0,
updates: Vec::new(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Dir {
Bidi,
Uni,
}
impl Dir {
fn from_id(id: u64) -> Self {
if id & 2 == 2 {
Dir::Uni
} else {
Dir::Bidi
}
}
fn to_bit(&self) -> u64 {
match self {
Dir::Bidi => 0,
Dir::Uni => 2,
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.