text stringlengths 8 4.13M |
|---|
use eosio::*;
use std::collections::VecDeque;
/// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L216-L227>
#[derive(Read, Write, NumBytes, Debug, Clone)]
pub struct RexPool {
pub version: u8,
/// total amount of CORE_SYMBOL in open rex_loans
pub total_lent: Asset,
/// total amount of CORE_SYMBOL available to be lent (connector)
pub total_unlent: Asset,
/// fees received in exchange for lent (connector)
pub total_rent: Asset,
/// total amount of CORE_SYMBOL that have been lent (total_unlent + total_lent)
pub total_lendable: Asset,
/// total number of REX shares allocated to contributors to total_lendable
pub total_rex: Asset,
/// the amount of CORE_SYMBOL to be transferred from namebids to REX pool
pub namebid_proceeds: Asset,
/// increments with each new loan
pub loan_num: u64,
}
impl Table for RexPool {
const NAME: TableName = TableName::new(n!("rexpool"));
type Row = Self;
fn primary_key(_row: &Self::Row) -> u64 {
0
}
}
/// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L231-L237>
#[derive(Table, Read, Write, NumBytes, Debug, Clone)]
#[eosio(table_name = "rexfund")]
pub struct RexFund {
pub version: u8,
/// owner of the rex fund
#[eosio(primary_key)]
pub owner: AccountName,
/// balance of the fund.
pub balance: Asset,
}
/// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L241-L250>
#[derive(Table, Read, Write, NumBytes, Debug, Clone)]
#[eosio(table_name = "rexbal")]
pub struct RexBalance {
pub version: u8,
/// owner of the rex fund
#[eosio(primary_key)]
pub owner: AccountName,
/// the amount of CORE_SYMBOL currently included in owner's vote
pub vote_stake: Asset,
/// the amount of REX owned by owner
pub rex_balance: Asset,
/// matured REX available for selling
pub matured_rex: i64,
/// REX daily maturity buckets
pub rex_maturities: VecDeque<(TimePointSec, i64)>,
}
/// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L254-L267>
#[derive(Read, Write, NumBytes, Debug, Clone)]
pub struct RexLoan {
pub version: u8,
pub from: AccountName,
pub receiver: AccountName,
pub payment: Asset,
pub balance: Asset,
pub total_staked: Asset,
pub loan_num: u64,
pub expiration: TimePoint,
}
/// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L279-L291>
#[derive(Read, Write, NumBytes, Debug, Clone)]
pub struct RexOrder {
pub version: u8,
pub owner: AccountName,
pub rex_requested: Asset,
pub proceeds: Asset,
pub stake_change: Asset,
pub order_time: TimePoint,
pub is_open: bool,
}
/// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L296-L300>
pub struct RexOrderOutcome {
pub success: bool,
pub proceeds: Asset,
pub stake_change: Asset,
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L10-L22>
#[eosio::action]
pub fn deposit(owner: AccountName, amount: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L24-L37>
#[eosio::action]
pub fn withdraw(owner: AccountName, amount: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L39-L54>
#[eosio::action]
pub fn buyrex(from: AccountName, amount: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L56-L94>
#[eosio::action]
pub fn unstaketorex(
owner: AccountName,
receiver: AccountName,
from_net: Asset,
from_cpu: Asset,
) {
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L96-L144>
#[eosio::action]
pub fn sellrex(from: AccountName, rex: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L146-L153>
#[eosio::action]
pub fn cnclrexorder(owner: AccountName) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L155-L162>
#[eosio::action]
pub fn rentcpu(
from: AccountName,
receiver: AccountName,
loan_payment: Asset,
loan_fund: Asset,
) {
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L164-L171>
#[eosio::action]
pub fn rentnet(
from: AccountName,
receiver: AccountName,
loan_payment: Asset,
loan_fund: Asset,
) {
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L173-L179>
#[eosio::action]
pub fn fundcpuloan(from: AccountName, loan_num: u64, payment: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L181-L187>
#[eosio::action]
pub fn fundnetloan(from: AccountName, loan_num: u64, payment: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L189-L195>
#[eosio::action]
pub fn defcpuloan(from: AccountName, loan_num: u64, amount: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L197-L203>
#[eosio::action]
pub fn defnetloan(from: AccountName, loan_num: u64, amount: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L205-L229>
#[eosio::action]
pub fn updaterex(owner: AccountName) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L231-L241>
#[eosio::action]
pub fn setrex(balance: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L243-L248>
#[eosio::action]
pub fn rexexec(user: AccountName, max: u16) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L250-L259>
#[eosio::action]
pub fn consolidate(owner: AccountName) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L261-L293>
#[eosio::action]
pub fn mvtosavings(owner: AccountName, rex: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L295-L316>
#[eosio::action]
pub fn mvfrsavings(owner: AccountName, rex: Asset) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/rex.cpp#L318-L353>
#[eosio::action]
pub fn closerex(owner: AccountName) {}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use crypto::HashValue;
use starcoin_config::ChainConfig;
use starcoin_state_api::ChainState;
use types::{
account_address::AccountAddress,
state_set::ChainStateSet,
transaction::{RawUserTransaction, SignedUserTransaction, Transaction, TransactionOutput},
vm_error::VMStatus,
};
pub mod block_executor;
pub mod executor;
#[cfg(test)]
pub mod executor_test;
pub mod mock_executor;
pub trait TransactionExecutor: std::marker::Unpin + Clone {
/// Create genesis state, return state root and state set.
fn init_genesis(config: &ChainConfig) -> Result<(HashValue, ChainStateSet)>;
/// Execute transaction, update state to state_store, and return events and TransactionStatus.
fn execute_transaction(
chain_state: &dyn ChainState,
txn: Transaction,
) -> Result<TransactionOutput>;
/// Executes the prologue and verifies that the transaction is valid.
fn validate_transaction(
chain_state: &dyn ChainState,
txn: SignedUserTransaction,
) -> Option<VMStatus>;
fn build_mint_txn(
addr: AccountAddress,
auth_key_prefix: Vec<u8>,
seq_num: u64,
amount: u64,
) -> Transaction;
fn build_transfer_txn(
sender: AccountAddress,
sender_auth_key_prefix: Vec<u8>,
receiver: AccountAddress,
receiver_auth_key_prefix: Vec<u8>,
seq_num: u64,
amount: u64,
) -> RawUserTransaction;
}
|
use advent::helpers;
use anyhow::{Context, Result};
use derive_more::Display;
use itertools::Itertools;
use lazy_static::lazy_static;
use regex::Regex;
use std::str::FromStr;
#[derive(Debug, Display, Clone)]
enum BitOp {
#[display(fmt = "{}", _0)]
Override(char),
#[display(fmt = "X")]
Pass,
}
type BitOps = Vec<BitOp>;
#[derive(Debug, Display, Clone)]
enum BitOpV2 {
#[display(fmt = "0")]
Pass,
#[display(fmt = "1")]
OverrideWithOne,
#[display(fmt = "X")]
Floating,
}
type BitOpsV2 = Vec<BitOpV2>;
#[derive(Debug, Display)]
enum Op {
#[display(fmt = "mask = {}", _0)]
SetMask(Mask),
#[display(fmt = "{}", _0)]
WriteMemory(WriteMemoryArgs),
}
type Ops = Vec<Op>;
#[derive(Debug, Display)]
enum OpV2 {
#[display(fmt = "mask = {}", _0)]
SetMask(MaskV2),
#[display(fmt = "{}", _0)]
WriteMemory(WriteMemoryArgs),
}
type OpsV2 = Vec<OpV2>;
#[derive(Debug, Clone)]
struct Mask {
bit_ops: BitOps,
}
#[derive(Debug, Clone)]
struct MaskV2 {
bit_ops: BitOpsV2,
floating_op_indices: Vec<usize>,
}
#[derive(Debug, Display)]
#[display(fmt = "mem[{}] = {}", address, value)]
struct WriteMemoryArgs {
address: u64,
value: u64,
}
#[derive(Debug, Default, Display)]
#[display(fmt = "{}\n{:?}", mask, memory)]
struct Memory {
memory: std::collections::HashMap<u64, u64>,
mask: Mask,
}
#[derive(Debug, Default, Display)]
#[display(fmt = "{}\n{:?}", mask, memory)]
struct MemoryV2 {
memory: std::collections::HashMap<u64, u64>,
mask: MaskV2,
}
impl FromStr for BitOp {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.chars().next() {
None => anyhow::bail!("No mask character"),
Some('X') => Ok(BitOp::Pass),
Some('0') => Ok(BitOp::Override('0')),
Some('1') => Ok(BitOp::Override('1')),
Some(e) => anyhow::bail!(format!("Invalid mask character: {}", e)),
}
}
}
impl FromStr for BitOpV2 {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(BitOpV2::from_bit_op(s.parse::<BitOp>()?))
}
}
impl BitOpV2 {
fn from_bit_op(op: BitOp) -> BitOpV2 {
match op {
BitOp::Pass => BitOpV2::Floating,
BitOp::Override(c) => match c {
'0' => BitOpV2::Pass,
'1' => BitOpV2::OverrideWithOne,
_ => unreachable!(),
},
}
}
}
impl FromStr for WriteMemoryArgs {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
lazy_static! {
static ref RE: Regex = Regex::new(r"mem\[(\d+)\] = (\d+)").unwrap();
}
// let re: Regex = Regex::new(r"mem\[(\d+)\] = (\d+)").unwrap();
// mem[7001] = 347
let caps = RE
.captures(s)
.ok_or_else(|| anyhow::anyhow!("No regex match found for memory args"))?;
let address = caps
.get(1)
.ok_or_else(|| anyhow::anyhow!("No match for address"))?
.as_str()
.parse::<u64>()?;
let value = caps
.get(2)
.ok_or_else(|| anyhow::anyhow!("No match for value"))?
.as_str()
.parse::<u64>()?;
Ok(WriteMemoryArgs { address, value })
}
}
impl FromStr for Mask {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
lazy_static! {
static ref RE: Regex = Regex::new(r"mask = ([01X]+)").unwrap();
}
// let re: Regex = Regex::new(r"mask = ([01X]+)").unwrap();
// mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
let caps = RE
.captures(s)
.ok_or_else(|| anyhow::anyhow!("No regex match found for mask"))?;
let maybe_mask = caps
.get(1)
.ok_or_else(|| anyhow::anyhow!("No match for mask"))?
.as_str();
if maybe_mask.len() != 36 {
anyhow::bail!(format!(
"Mask {} has invalid length: {}",
maybe_mask,
maybe_mask.len()
));
}
let bit_ops = maybe_mask
.trim()
.chars()
.map(|c| c.to_string().parse::<BitOp>())
.try_collect()?;
Ok(Mask { bit_ops })
}
}
impl FromStr for MaskV2 {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(MaskV2::from_mask(s.parse::<Mask>()?))
}
}
impl MaskV2 {
fn from_mask(mask: Mask) -> MaskV2 {
let bit_ops = mask
.bit_ops
.into_iter()
.map(BitOpV2::from_bit_op)
.collect_vec();
// Pre-compute floating bit indicies, which will be modified
// when applying the mask to an address.
let floating_op_indices = bit_ops
.iter()
.enumerate()
.filter_map(|(index, op)| {
if let BitOpV2::Floating = op {
Some(index)
} else {
None
}
})
.collect_vec();
MaskV2 {
bit_ops,
floating_op_indices,
}
}
}
impl FromStr for Op {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match &s[0..3] {
"mas" => Ok(Op::SetMask(s.parse()?)),
"mem" => Ok(Op::WriteMemory(s.parse()?)),
_ => anyhow::bail!("Invalid operation"),
}
}
}
impl FromStr for OpV2 {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match &s[0..3] {
"mas" => Ok(OpV2::SetMask(s.parse()?)),
"mem" => Ok(OpV2::WriteMemory(s.parse()?)),
_ => anyhow::bail!("Invalid operation"),
}
}
}
impl std::fmt::Display for Mask {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for op in &self.bit_ops {
write!(f, "{}", op)?;
}
Ok(())
}
}
impl Default for Mask {
fn default() -> Self {
Mask {
bit_ops: vec![BitOp::Pass; 36],
}
}
}
impl std::fmt::Display for MaskV2 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for op in &self.bit_ops {
write!(f, "{}", op)?;
}
Ok(())
}
}
impl Default for MaskV2 {
fn default() -> Self {
MaskV2 {
bit_ops: vec![BitOpV2::Pass; 36],
floating_op_indices: vec![],
}
}
}
#[allow(unused)]
fn print_ops(ops: &[Op]) {
for op in ops {
println!("{}", op);
}
}
#[allow(unused)]
fn print_memory(mem: &Memory) {
println!("{}", mem);
}
impl Memory {
fn apply_ops(&mut self, ops: &[Op]) {
ops.iter().for_each(|op| match op {
Op::SetMask(mask) => self.mask = mask.clone(),
Op::WriteMemory(args) => {
self.memory
.insert(args.address, apply_mask(args.value, &self.mask));
}
});
}
}
impl MemoryV2 {
fn apply_ops(&mut self, ops: &[OpV2]) {
ops.iter().for_each(|op| match op {
OpV2::SetMask(mask) => self.mask = mask.clone(),
OpV2::WriteMemory(args) => {
let mask = self.mask.clone();
apply_mask_v2(args.address, &mask).for_each(|address| {
self.memory.insert(address, args.value);
})
}
});
}
}
fn apply_mask(value: u64, mask: &Mask) -> u64 {
let value_str = format!("{:036b}", value);
let masked_value_str = value_str
.chars()
.zip(mask.bit_ops.iter())
.map(|(digit, bit_op)| match bit_op {
BitOp::Pass => digit,
BitOp::Override(o) => *o,
})
.collect::<String>();
u64::from_str_radix(&masked_value_str, 2).expect("Invalid string to int conversion")
}
fn apply_mask_v2(value: u64, mask: &MaskV2) -> impl Iterator<Item = u64> + '_ {
let value_str = format!("{:036b}", value);
let masked_value_str = value_str
.chars()
.zip(mask.bit_ops.iter())
.map(|(digit, bit_op)| match bit_op {
BitOpV2::Pass => digit,
BitOpV2::OverrideWithOne => '1',
BitOpV2::Floating => '0',
})
.collect::<String>();
// Generate all subsets of indices that should be set to 1
// and modify a clone of the mask string with the modified indices.
mask.floating_op_indices
.iter()
.powerset()
.map(move |indices| {
let mut mask_str = masked_value_str.clone();
let mut bytes = std::mem::take(&mut mask_str).into_bytes();
indices.iter().for_each(|&i| bytes[*i] = b'1');
let mask_str =
String::from_utf8(bytes).expect("Invalid utf8 bytes to string conversion");
u64::from_str_radix(&mask_str, 2).expect("Invalid string to int conversion")
})
}
fn parse_writes_and_masks(s: &str) -> anyhow::Result<Ops> {
s.trim().lines().map(|l| l.parse::<Op>()).try_collect()
}
fn parse_writes_and_masks_v2(s: &str) -> anyhow::Result<OpsV2> {
s.trim().lines().map(|l| l.parse::<OpV2>()).try_collect()
}
fn compute_sum_of_all_values_in_memory(s: &str) -> u64 {
let ops = parse_writes_and_masks(s).expect("Invalid ops");
let mut memory = Memory::default();
memory.apply_ops(&ops);
memory.memory.iter().map(|e| e.1).sum()
}
fn compute_sum_of_all_values_in_memory_v2(s: &str) -> u64 {
let ops = parse_writes_and_masks_v2(s).expect("Invalid ops");
let mut memory = MemoryV2::default();
memory.apply_ops(&ops);
memory.memory.iter().map(|e| e.1).sum()
}
fn solve_p1() -> Result<()> {
let input = helpers::get_data_from_file_res("d14").context("Coudn't read file contents.")?;
let result = compute_sum_of_all_values_in_memory(&input);
println!("The sum of all values in memory is: {}", result);
Ok(())
}
fn solve_p2() -> Result<()> {
let input = helpers::get_data_from_file_res("d14").context("Coudn't read file contents.")?;
let result = compute_sum_of_all_values_in_memory_v2(&input);
println!(
"The sum of all values in memory using decoder V2 is: {}",
result
);
Ok(())
}
fn main() -> Result<()> {
solve_p1().ok();
solve_p2()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_p1() {
let input = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0";
let result = compute_sum_of_all_values_in_memory(input);
assert_eq!(result, 165);
}
#[test]
fn test_p2() {
let input = "mask = 000000000000000000000000000000X1001X
mem[42] = 100
mask = 00000000000000000000000000000000X0XX
mem[26] = 1";
let result = compute_sum_of_all_values_in_memory_v2(input);
assert_eq!(result, 208);
}
}
|
#[cfg(test)]
mod tests {
struct Context<'a>(&'a str);
// 'b >= 'a
struct Parser<'a, 'b: 'a> {
context: &'a Context<'b>,
}
impl<'a, 'b> Parser<'a, 'b> {
fn parse(&self) -> Result<(), &'b str> {
Err(&self.context.0[1..])
}
}
//获得了所有权
fn parse_context(context: Context) -> Result<(), &str> {
Parser { context: &context }.parse()
}
#[test]
fn work() {}
mod generic {
//指定 T 中的任何引用需至少与 'a 存活的一样久
// T >= 'a
struct Ref<'a, T: 'a>(&'a T);
//T 包含任何引用,他们必须有 'static 生命周期
struct StaticRef<T: 'static>(&'static T);
}
mod trait_demo {
trait Red {}
struct Ball<'a> {
diameter: &'a i32,
}
impl<'a> Red for Ball<'a> {}
#[test]
fn main() {
let num = 5;
let _obj = Box::new(Ball { diameter: &num }) as Box<dyn Red>;
}
}
mod noname {
use std::fmt;
use std::fmt::{Error, Formatter};
struct StrWrap<'a>(&'a str);
fn foo<'a>(string: &'a str) -> StrWrap<'a> {
StrWrap(string)
}
fn foo2(string: &str) -> StrWrap<'_> {
StrWrap(string)
}
fn foo3(string: &str) -> StrWrap {
StrWrap(string)
}
// // 冗余
// impl<'a> fmt::Debug for StrWrap<'a> {
// fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
// unimplemented!()
// }
// }
//
// // 省略
// impl fmt::Debug for StrWrap<'_> {
// fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
// unimplemented!()
// }
// }
// 省略
impl fmt::Debug for StrWrap<'_> {
fn fmt(&self, _f: &mut Formatter<'_>) -> Result<(), Error> {
unimplemented!()
}
}
}
}
|
extern crate reqwest;
extern crate serde_json;
extern crate ws;
extern crate stellar_client;
extern crate futures;
extern crate futures_timer;
pub mod meetup;
|
use super::interfaces::block::BlockState;
use super::interfaces::messenger::{Messenger, SubscriberType};
use super::interfaces::patchwork::PatchworkState;
use super::interfaces::player::{Angle, Player, PlayerState, Position};
use super::packet;
use super::packet::Packet;
use super::translation::TranslationUpdates;
use uuid::Uuid;
pub fn handle_login_packet<
M: Messenger + Clone,
P: PlayerState + Clone,
PA: PatchworkState + Clone,
B: BlockState + Clone,
>(
p: Packet,
conn_id: Uuid,
messenger: M,
player_state: P,
block_state: B,
patchwork_state: PA,
) -> TranslationUpdates {
match p {
Packet::LoginStart(login_start) => {
confirm_login(
conn_id,
messenger,
login_start,
player_state,
block_state,
patchwork_state,
);
TranslationUpdates::State(3)
}
_ => {
panic!("Login failed");
}
}
}
fn confirm_login<
M: Messenger + Clone,
P: PlayerState + Clone,
PA: PatchworkState + Clone,
B: BlockState + Clone,
>(
conn_id: Uuid,
messenger: M,
login_start: packet::LoginStart,
player_state: P,
block_state: B,
patchwork_state: PA,
) {
let player = Player {
conn_id,
uuid: Uuid::new_v4(),
name: login_start.username,
entity_id: 0, // replaced by player state
position: Position {
x: 5.0,
y: 16.0,
z: 5.0,
},
angle: Angle {
pitch: 0.0,
yaw: 0.0,
},
};
//protocol
login_success(conn_id, messenger.clone(), player.clone());
//update the gamestate with this new player
player_state.new_player(conn_id, player);
block_state.report(conn_id);
messenger.subscribe(conn_id, SubscriberType::All);
player_state.report(conn_id);
patchwork_state.report();
}
fn login_success<M: Messenger>(conn_id: Uuid, messenger: M, player: Player) {
let login_success = packet::LoginSuccess {
uuid: player.uuid.to_hyphenated().to_string(),
username: player.name,
};
messenger.send_packet(conn_id, Packet::LoginSuccess(login_success));
}
|
#![feature(unchecked_math)]
mod basic;
mod cache;
mod combinatorics;
mod digits;
mod error;
mod gamma;
mod linear;
mod prime;
pub use basic::*;
pub use cache::{Cache, GlobalCache};
pub use error::{Error, Result};
pub use gamma::*;
pub use linear::*;
pub use prime::*;
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const Catalog: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22881_8a19_11d0_81b6_00a0c9231c29);
pub const CatalogCollection: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22883_8a19_11d0_81b6_00a0c9231c29);
pub const CatalogObject: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22882_8a19_11d0_81b6_00a0c9231c29);
pub const ComponentUtil: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22884_8a19_11d0_81b6_00a0c9231c29);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ICatalog(pub ::windows::core::IUnknown);
impl ICatalog {
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn GetCollection<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrcollname: Param0) -> ::windows::core::Result<super::Com::IDispatch> {
let mut result__: <super::Com::IDispatch as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrcollname.into_param().abi(), &mut result__).from_abi::<super::Com::IDispatch>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn Connect<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrconnectstring: Param0) -> ::windows::core::Result<super::Com::IDispatch> {
let mut result__: <super::Com::IDispatch as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrconnectstring.into_param().abi(), &mut result__).from_abi::<super::Com::IDispatch>(result__)
}
pub unsafe fn MajorVersion(&self, retval: *mut i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(retval)).ok()
}
pub unsafe fn MinorVersion(&self, retval: *mut i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(retval)).ok()
}
}
unsafe impl ::windows::core::Interface for ICatalog {
type Vtable = ICatalog_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22870_8a19_11d0_81b6_00a0c9231c29);
}
impl ::core::convert::From<ICatalog> for ::windows::core::IUnknown {
fn from(value: ICatalog) -> Self {
value.0
}
}
impl ::core::convert::From<&ICatalog> for ::windows::core::IUnknown {
fn from(value: &ICatalog) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICatalog {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ICatalog {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ICatalog> for super::Com::IDispatch {
fn from(value: ICatalog) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ICatalog> for super::Com::IDispatch {
fn from(value: &ICatalog) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for ICatalog {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for &ICatalog {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ICatalog_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pctinfo: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcollname: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppcatalogcollection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrconnectstring: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppcatalogcollection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, retval: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, retval: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IComponentUtil(pub ::windows::core::IUnknown);
impl IComponentUtil {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn InstallComponent<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrdllfile: Param0, bstrtypelibfile: Param1, bstrproxystubdllfile: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrdllfile.into_param().abi(), bstrtypelibfile.into_param().abi(), bstrproxystubdllfile.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ImportComponent<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrclsid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrclsid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ImportComponentByName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrprogid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), bstrprogid.into_param().abi()).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn GetCLSIDs<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrdllfile: Param0, bstrtypelibfile: Param1, aclsids: *mut *mut super::Com::SAFEARRAY) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), bstrdllfile.into_param().abi(), bstrtypelibfile.into_param().abi(), ::core::mem::transmute(aclsids)).ok()
}
}
unsafe impl ::windows::core::Interface for IComponentUtil {
type Vtable = IComponentUtil_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22873_8a19_11d0_81b6_00a0c9231c29);
}
impl ::core::convert::From<IComponentUtil> for ::windows::core::IUnknown {
fn from(value: IComponentUtil) -> Self {
value.0
}
}
impl ::core::convert::From<&IComponentUtil> for ::windows::core::IUnknown {
fn from(value: &IComponentUtil) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<IComponentUtil> for super::Com::IDispatch {
fn from(value: IComponentUtil) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&IComponentUtil> for super::Com::IDispatch {
fn from(value: &IComponentUtil) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for IComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for &IComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IComponentUtil_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pctinfo: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrdllfile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrtypelibfile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrproxystubdllfile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrclsid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrprogid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrdllfile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrtypelibfile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, aclsids: *mut *mut super::Com::SAFEARRAY) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IPackageUtil(pub ::windows::core::IUnknown);
impl IPackageUtil {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn InstallPackage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrpackagefile: Param0, bstrinstallpath: Param1, loptions: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrpackagefile.into_param().abi(), bstrinstallpath.into_param().abi(), ::core::mem::transmute(loptions)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ExportPackage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrpackageid: Param0, bstrpackagefile: Param1, loptions: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrpackageid.into_param().abi(), bstrpackagefile.into_param().abi(), ::core::mem::transmute(loptions)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ShutdownPackage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrpackageid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), bstrpackageid.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IPackageUtil {
type Vtable = IPackageUtil_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22874_8a19_11d0_81b6_00a0c9231c29);
}
impl ::core::convert::From<IPackageUtil> for ::windows::core::IUnknown {
fn from(value: IPackageUtil) -> Self {
value.0
}
}
impl ::core::convert::From<&IPackageUtil> for ::windows::core::IUnknown {
fn from(value: &IPackageUtil) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPackageUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IPackageUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<IPackageUtil> for super::Com::IDispatch {
fn from(value: IPackageUtil) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&IPackageUtil> for super::Com::IDispatch {
fn from(value: &IPackageUtil) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for IPackageUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for &IPackageUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IPackageUtil_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pctinfo: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpackagefile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrinstallpath: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, loptions: i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpackageid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrpackagefile: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, loptions: i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpackageid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IRemoteComponentUtil(pub ::windows::core::IUnknown);
impl IRemoteComponentUtil {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn InstallRemoteComponent<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrserver: Param0, bstrpackageid: Param1, bstrclsid: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrserver.into_param().abi(), bstrpackageid.into_param().abi(), bstrclsid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn InstallRemoteComponentByName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrserver: Param0, bstrpackagename: Param1, bstrprogid: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrserver.into_param().abi(), bstrpackagename.into_param().abi(), bstrprogid.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IRemoteComponentUtil {
type Vtable = IRemoteComponentUtil_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22875_8a19_11d0_81b6_00a0c9231c29);
}
impl ::core::convert::From<IRemoteComponentUtil> for ::windows::core::IUnknown {
fn from(value: IRemoteComponentUtil) -> Self {
value.0
}
}
impl ::core::convert::From<&IRemoteComponentUtil> for ::windows::core::IUnknown {
fn from(value: &IRemoteComponentUtil) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRemoteComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRemoteComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<IRemoteComponentUtil> for super::Com::IDispatch {
fn from(value: IRemoteComponentUtil) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&IRemoteComponentUtil> for super::Com::IDispatch {
fn from(value: &IRemoteComponentUtil) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for IRemoteComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for &IRemoteComponentUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IRemoteComponentUtil_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pctinfo: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrserver: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrpackageid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrclsid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrserver: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrpackagename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, bstrprogid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IRoleAssociationUtil(pub ::windows::core::IUnknown);
impl IRoleAssociationUtil {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn AssociateRole<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrroleid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrroleid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn AssociateRoleByName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrrolename: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrrolename.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IRoleAssociationUtil {
type Vtable = IRoleAssociationUtil_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22876_8a19_11d0_81b6_00a0c9231c29);
}
impl ::core::convert::From<IRoleAssociationUtil> for ::windows::core::IUnknown {
fn from(value: IRoleAssociationUtil) -> Self {
value.0
}
}
impl ::core::convert::From<&IRoleAssociationUtil> for ::windows::core::IUnknown {
fn from(value: &IRoleAssociationUtil) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRoleAssociationUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRoleAssociationUtil {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<IRoleAssociationUtil> for super::Com::IDispatch {
fn from(value: IRoleAssociationUtil) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&IRoleAssociationUtil> for super::Com::IDispatch {
fn from(value: &IRoleAssociationUtil) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for IRoleAssociationUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::Com::IDispatch> for &IRoleAssociationUtil {
fn into_param(self) -> ::windows::core::Param<'a, super::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IRoleAssociationUtil_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pctinfo: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrroleid: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrrolename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
pub const PackageUtil: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22885_8a19_11d0_81b6_00a0c9231c29);
pub const RemoteComponentUtil: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22886_8a19_11d0_81b6_00a0c9231c29);
pub const RoleAssociationUtil: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22887_8a19_11d0_81b6_00a0c9231c29);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct __MIDL___MIDL_itf_mtxadmin_0107_0001(pub i32);
pub const mtsInstallUsers: __MIDL___MIDL_itf_mtxadmin_0107_0001 = __MIDL___MIDL_itf_mtxadmin_0107_0001(1i32);
impl ::core::convert::From<i32> for __MIDL___MIDL_itf_mtxadmin_0107_0001 {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for __MIDL___MIDL_itf_mtxadmin_0107_0001 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct __MIDL___MIDL_itf_mtxadmin_0107_0002(pub i32);
pub const mtsExportUsers: __MIDL___MIDL_itf_mtxadmin_0107_0002 = __MIDL___MIDL_itf_mtxadmin_0107_0002(1i32);
impl ::core::convert::From<i32> for __MIDL___MIDL_itf_mtxadmin_0107_0002 {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for __MIDL___MIDL_itf_mtxadmin_0107_0002 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct __MIDL___MIDL_itf_mtxadmin_0107_0003(pub i32);
pub const mtsErrObjectErrors: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368511i32);
pub const mtsErrObjectInvalid: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368510i32);
pub const mtsErrKeyMissing: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368509i32);
pub const mtsErrAlreadyInstalled: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368508i32);
pub const mtsErrDownloadFailed: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368507i32);
pub const mtsErrPDFWriteFail: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368505i32);
pub const mtsErrPDFReadFail: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368504i32);
pub const mtsErrPDFVersion: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368503i32);
pub const mtsErrCoReqCompInstalled: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368496i32);
pub const mtsErrBadPath: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368502i32);
pub const mtsErrPackageExists: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368501i32);
pub const mtsErrRoleExists: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368500i32);
pub const mtsErrCantCopyFile: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368499i32);
pub const mtsErrNoTypeLib: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368498i32);
pub const mtsErrNoUser: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368497i32);
pub const mtsErrInvalidUserids: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368496i32);
pub const mtsErrNoRegistryCLSID: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368495i32);
pub const mtsErrBadRegistryProgID: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368494i32);
pub const mtsErrAuthenticationLevel: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368493i32);
pub const mtsErrUserPasswdNotValid: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368492i32);
pub const mtsErrNoRegistryRead: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368491i32);
pub const mtsErrNoRegistryWrite: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368490i32);
pub const mtsErrNoRegistryRepair: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368489i32);
pub const mtsErrCLSIDOrIIDMismatch: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368488i32);
pub const mtsErrRemoteInterface: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368487i32);
pub const mtsErrDllRegisterServer: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368486i32);
pub const mtsErrNoServerShare: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368485i32);
pub const mtsErrNoAccessToUNC: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368484i32);
pub const mtsErrDllLoadFailed: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368483i32);
pub const mtsErrBadRegistryLibID: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368482i32);
pub const mtsErrPackDirNotFound: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368481i32);
pub const mtsErrTreatAs: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368480i32);
pub const mtsErrBadForward: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368479i32);
pub const mtsErrBadIID: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368478i32);
pub const mtsErrRegistrarFailed: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368477i32);
pub const mtsErrCompFileDoesNotExist: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368476i32);
pub const mtsErrCompFileLoadDLLFail: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368475i32);
pub const mtsErrCompFileGetClassObj: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368474i32);
pub const mtsErrCompFileClassNotAvail: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368473i32);
pub const mtsErrCompFileBadTLB: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368472i32);
pub const mtsErrCompFileNotInstallable: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368471i32);
pub const mtsErrNotChangeable: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368470i32);
pub const mtsErrNotDeletable: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368469i32);
pub const mtsErrSession: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368468i32);
pub const mtsErrCompFileNoRegistrar: __MIDL___MIDL_itf_mtxadmin_0107_0003 = __MIDL___MIDL_itf_mtxadmin_0107_0003(-2146368460i32);
impl ::core::convert::From<i32> for __MIDL___MIDL_itf_mtxadmin_0107_0003 {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for __MIDL___MIDL_itf_mtxadmin_0107_0003 {
type Abi = Self;
}
|
use std::io::prelude::*;
use std::fs::OpenOptions;
use chrono::prelude::*;
use std::sync::{Mutex, Arc};
pub fn crear_log() -> std::sync::Arc<std::sync::Mutex<std::fs::File>> {
let file = Arc::new(Mutex::new(
match OpenOptions::new()
.read(true)
.write(true)
.append(true)
.create(true)
.open("log.txt") {
Ok(f) => f,
Err(err) => { panic!("No se pude crear log: {}", err); }
}
));
return file;
}
pub fn log(file : &std::sync::Arc<std::sync::Mutex<std::fs::File>> , message : String) {
let local = Local::now().format("%d/%m/%Y %H:%M:%S");
let output = format!("{} - {}", local, message);
// Bloque protegido
{
let mut f = file.lock().unwrap();
match f.write(output.as_bytes()){
Ok(_) => {},
Err(err) => println!("Error al loggear: {}", err)
};
}
} |
use game_metrics::{scope, instrument, Metrics};
use std::time::Duration;
#[instrument]
fn long() {
std::thread::sleep(Duration::from_millis(500));
}
#[instrument]
fn short() {
std::thread::sleep(Duration::from_millis(50));
}
fn long_scoped() {
scope!("long_scoped");
std::thread::sleep(Duration::from_millis(500));
}
fn short_scoped() {
scope!("short_scoped");
std::thread::sleep(Duration::from_millis(50));
}
fn main() {
let metrics = Metrics::new(1);
let t1 = std::thread::spawn(|| {
(0..10).for_each(|_| long_scoped());
(0..10).for_each(|_| long());
(0..10).for_each(|_| short_scoped());
(0..10).for_each(|_| short());
});
let t2 = std::thread::spawn(|| {
(0..10).for_each(|_| long_scoped());
(0..10).for_each(|_| long());
(0..10).for_each(|_| short_scoped());
(0..10).for_each(|_| short());
});
t1.join().unwrap();
t2.join().unwrap();
metrics.for_each_histogram(|span_name, h| {
println!("{} -> {:.2}ms", span_name, h.mean() / 1_000_000.0);
});
}
|
#![allow(dead_code)]
use arrow::record_batch::RecordBatch;
use data_types::{sequence_number_set::SequenceNumberSet, SequenceNumber, TimestampMinMax};
use mutable_batch::MutableBatch;
mod buffering;
mod persisting;
mod snapshot;
pub(in crate::buffer_tree::partition::buffer) use buffering::*;
pub(crate) use persisting::*;
use crate::query::projection::OwnedProjection;
use super::traits::{Queryable, Writeable};
/// A result type for fallible transitions.
///
/// The type system ensures the state machine is always returned to the caller,
/// regardless of the transition outcome.
#[derive(Debug)]
pub(crate) enum Transition<A, B> {
/// The transition succeeded, and the new state is contained within.
Ok(BufferState<A>),
/// The state machine failed to transition due to an invariant not being
/// upheld, and the original state is contained within.
Unchanged(BufferState<B>),
}
impl<A, B> Transition<A, B> {
/// A helper function to construct [`Self::Ok`] variants.
pub(super) fn ok(v: A, sequence_numbers: SequenceNumberSet) -> Self {
Self::Ok(BufferState {
state: v,
sequence_numbers,
})
}
/// A helper function to construct [`Self::Unchanged`] variants.
pub(super) fn unchanged(v: BufferState<B>) -> Self {
Self::Unchanged(v)
}
}
/// A finite state machine for buffering writes, and converting them into a
/// queryable data format on-demand.
///
/// This FSM is used to provide explicit states for each stage of the data
/// lifecycle within a partition buffer:
///
/// ```text
/// ┌──────────────┐
/// │ Buffering │
/// └───────┬──────┘
/// │
/// ▼
/// ┌ ─ ─ ─ ─ ─ ─ ─ ┌ ─ ─ ─ ─ ─ ─ ─
/// Snapshot ├─────▶ Persisting │
/// └ ─ ─ ─ ─ ─ ─ ─ └ ─ ─ ─ ─ ─ ─ ─
/// ```
///
/// Boxes with dashed lines indicate immutable, queryable states that contain
/// data in an efficient data format for query execution ([`RecordBatch`]).
///
/// Boxes with solid lines indicate a mutable state to which further writes can
/// be applied.
///
/// A [`BufferState`] tracks the bounding [`SequenceNumber`] values it has
/// observed, and enforces monotonic writes (w.r.t their [`SequenceNumber`]).
#[derive(Debug)]
pub(crate) struct BufferState<T> {
state: T,
/// The set of [`SequenceNumber`] successfully applied to this buffer.
sequence_numbers: SequenceNumberSet,
}
impl BufferState<Buffering> {
/// Initialise a new buffer state machine.
pub(crate) fn new() -> Self {
Self {
state: Buffering::default(),
sequence_numbers: SequenceNumberSet::default(),
}
}
}
impl<T> BufferState<T> {
/// Return the set of sequence numbers wrote to this [`BufferState`].
pub(crate) fn sequence_number_set(&self) -> &SequenceNumberSet {
&self.sequence_numbers
}
}
/// A [`BufferState`] in a mutable state can accept writes and record their
/// [`SequenceNumber`].
impl<T> BufferState<T>
where
T: Writeable,
{
/// The provided [`SequenceNumber`] MUST be for the given [`MutableBatch`].
pub(crate) fn write(
&mut self,
batch: MutableBatch,
n: SequenceNumber,
) -> Result<(), mutable_batch::Error> {
self.state.write(batch)?;
// Add the sequence number to the observed set after the fallible write.
self.sequence_numbers.add(n);
Ok(())
}
}
/// A [`BufferState`] in a queryable state delegates the read to the current
/// state machine state.
impl<T> Queryable for BufferState<T>
where
T: Queryable,
{
/// Returns the current buffer data.
///
/// This is always a cheap method call.
fn get_query_data(&self, projection: &OwnedProjection) -> Vec<RecordBatch> {
self.state.get_query_data(projection)
}
fn rows(&self) -> usize {
self.state.rows()
}
fn timestamp_stats(&self) -> Option<TimestampMinMax> {
self.state.timestamp_stats()
}
fn schema(&self) -> Option<schema::Schema> {
self.state.schema()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use arrow_util::assert_batches_eq;
use assert_matches::assert_matches;
use mutable_batch_lp::test_helpers::lp_to_mutable_batch;
use schema::Projection;
use snapshot::*;
use super::*;
#[test]
// comparing dyn Array always has same vtable, so is accurate to use Arc::ptr_eq
#[allow(clippy::vtable_address_comparisons)]
fn test_buffer_lifecycle() {
// Initialise a buffer in the base state.
let mut buffer: BufferState<Buffering> = BufferState::new();
// Write some data to a buffer.
buffer
.write(
lp_to_mutable_batch(
r#"bananas,tag=platanos great=true,how_much=42 668563242000000042"#,
)
.1,
SequenceNumber::new(0),
)
.expect("write to empty buffer should succeed");
// Ensure the sequence number was recorded
{
let set = buffer.sequence_number_set();
assert!(set.contains(SequenceNumber::new(0)));
assert_eq!(set.len(), 1);
}
// Extract the queryable data from the buffer and validate it.
//
// Keep the data to validate they are ref-counted copies after further
// writes below. Note this construct allows the caller to decide when/if
// to allocate.
let w1_data = buffer.get_query_data(&OwnedProjection::default());
let expected = vec![
"+-------+----------+----------+--------------------------------+",
"| great | how_much | tag | time |",
"+-------+----------+----------+--------------------------------+",
"| true | 42.0 | platanos | 1991-03-10T00:00:42.000000042Z |",
"+-------+----------+----------+--------------------------------+",
];
assert_batches_eq!(&expected, &[w1_data[0].clone()]);
// Apply another write.
buffer
.write(
lp_to_mutable_batch(
r#"bananas,tag=platanos great=true,how_much=1000 668563242000000043"#,
)
.1,
SequenceNumber::new(1),
)
.expect("write to empty buffer should succeed");
// Snapshot the buffer into an immutable, queryable data format.
let buffer: BufferState<Snapshot> = match buffer.snapshot() {
Transition::Ok(v) => v,
Transition::Unchanged(_) => panic!("did not transition to snapshot state"),
};
// Verify the writes are still queryable.
let w2_data = buffer.get_query_data(&OwnedProjection::default());
let expected = vec![
"+-------+----------+----------+--------------------------------+",
"| great | how_much | tag | time |",
"+-------+----------+----------+--------------------------------+",
"| true | 42.0 | platanos | 1991-03-10T00:00:42.000000042Z |",
"| true | 1000.0 | platanos | 1991-03-10T00:00:42.000000043Z |",
"+-------+----------+----------+--------------------------------+",
];
assert_eq!(w2_data.len(), 1);
assert_batches_eq!(&expected, &[w2_data[0].clone()]);
// Ensure the same data is returned for a second read.
{
let second_read = buffer.get_query_data(&OwnedProjection::default());
assert_eq!(w2_data, second_read);
// And that no data was actually copied.
let same_arcs = w2_data
.iter()
.zip(second_read.iter())
.all(|(a, b)| Arc::ptr_eq(a.column(0), b.column(0)));
assert!(same_arcs);
}
// Finally transition into the terminal persisting state.
let buffer: BufferState<Persisting> = buffer.into_persisting();
// Extract the final buffered result
let final_data = buffer.get_query_data(&OwnedProjection::default());
// And once again verify no data was changed, copied or re-ordered.
assert_eq!(w2_data, final_data);
let same_arcs = w2_data
.into_iter()
.zip(final_data.into_iter())
.all(|(a, b)| Arc::ptr_eq(a.column(0), b.column(0)));
assert!(same_arcs);
// Assert the sequence numbers were recorded.
let set = buffer.into_sequence_number_set();
assert!(set.contains(SequenceNumber::new(0)));
assert!(set.contains(SequenceNumber::new(1)));
assert_eq!(set.len(), 2);
}
/// Assert projection is correct across all the queryable FSM states.
#[test]
// comparing dyn Array always has same vtable, so is accurate to use Arc::ptr_eq
#[allow(clippy::vtable_address_comparisons)]
fn test_buffer_projection() {
let projection = OwnedProjection::from(vec![
"tag".to_string(),
"great".to_string(),
"missing".to_string(),
"time".to_string(),
]);
// Initialise a buffer in the base state.
let mut buffer: BufferState<Buffering> = BufferState::new();
// Write some data to a buffer.
buffer
.write(
lp_to_mutable_batch(
r#"bananas,tag=platanos great=true,how_much=42 668563242000000042"#,
)
.1,
SequenceNumber::new(0),
)
.expect("write to empty buffer should succeed");
// Extract the queryable data from the buffer and validate it.
//
// Keep the data to validate they are ref-counted copies after further
// writes below. Note this construct allows the caller to decide when/if
// to allocate.
let w1_data = buffer.get_query_data(&projection);
let expected = vec![
"+----------+-------+--------------------------------+",
"| tag | great | time |",
"+----------+-------+--------------------------------+",
"| platanos | true | 1991-03-10T00:00:42.000000042Z |",
"+----------+-------+--------------------------------+",
];
assert_batches_eq!(&expected, &[w1_data[0].clone()]);
// Apply another write.
buffer
.write(
lp_to_mutable_batch(
r#"bananas,tag=platanos great=true,how_much=1000 668563242000000043"#,
)
.1,
SequenceNumber::new(1),
)
.expect("write to empty buffer should succeed");
// Snapshot the buffer into an immutable, queryable data format.
let buffer: BufferState<Snapshot> = match buffer.snapshot() {
Transition::Ok(v) => v,
Transition::Unchanged(_) => panic!("did not transition to snapshot state"),
};
// Verify the writes are still queryable.
let w2_data = buffer.get_query_data(&projection);
let expected = vec![
"+----------+-------+--------------------------------+",
"| tag | great | time |",
"+----------+-------+--------------------------------+",
"| platanos | true | 1991-03-10T00:00:42.000000042Z |",
"| platanos | true | 1991-03-10T00:00:42.000000043Z |",
"+----------+-------+--------------------------------+",
];
assert_eq!(w2_data.len(), 1);
assert_batches_eq!(&expected, &[w2_data[0].clone()]);
// Ensure the same data is returned for a second read.
{
let second_read = buffer.get_query_data(&projection);
assert_eq!(w2_data, second_read);
// And that no data was actually copied.
let same_arcs = w2_data
.iter()
.zip(second_read.iter())
.all(|(a, b)| Arc::ptr_eq(a.column(0), b.column(0)));
assert!(same_arcs);
}
// Finally transition into the terminal persisting state.
let buffer: BufferState<Persisting> = buffer.into_persisting();
// Extract the final buffered result
let final_data = buffer.get_query_data(&projection);
// And once again verify no data was changed, copied or re-ordered.
assert_eq!(w2_data, final_data);
let same_arcs = w2_data
.into_iter()
.zip(final_data.into_iter())
.all(|(a, b)| Arc::ptr_eq(a.column(0), b.column(0)));
assert!(same_arcs);
// Assert the sequence numbers were recorded.
let set = buffer.into_sequence_number_set();
assert!(set.contains(SequenceNumber::new(0)));
assert!(set.contains(SequenceNumber::new(1)));
assert_eq!(set.len(), 2);
}
#[test]
fn test_snapshot_buffer_different_but_compatible_schemas() {
let mut buffer = BufferState::new();
// Missing tag `t1`
let (_, mut mb1) = lp_to_mutable_batch(r#"foo iv=1i,uv=774u,fv=1.0,bv=true,sv="hi" 1"#);
buffer.state.write(mb1.clone()).unwrap();
// Missing field `iv`
let (_, mb2) = lp_to_mutable_batch(r#"foo,t1=aoeu uv=1u,fv=12.0,bv=false,sv="bye" 10000"#);
buffer.state.write(mb2.clone()).unwrap();
let buffer: BufferState<Snapshot> = match buffer.snapshot() {
Transition::Ok(v) => v,
Transition::Unchanged(_) => panic!("failed to transition"),
};
assert_eq!(buffer.get_query_data(&OwnedProjection::default()).len(), 1);
let snapshot = buffer.get_query_data(&OwnedProjection::default())[0].clone();
// Generate the combined buffer from the original inputs to compare
// against.
mb1.extend_from(&mb2).unwrap();
let want = mb1.to_arrow(Projection::All).unwrap();
assert_eq!(snapshot, want);
}
#[test]
fn test_fallible_write_sequence_number_observation() {
let mut buffer: BufferState<Buffering> = BufferState::new();
// A successful write has the sequence number recorded.
let (_, mb) = lp_to_mutable_batch(r#"bananas great=42 1"#);
buffer.write(mb, SequenceNumber::new(24)).unwrap();
// Validate the sequence number was recorded.
{
let set = buffer.sequence_number_set();
assert!(set.contains(SequenceNumber::new(24)));
assert_eq!(set.len(), 1);
}
// A failed write (in this case because of a schema conflict) must not
// have the sequence number recorded.
let (_, mb) = lp_to_mutable_batch(r#"bananas great="yep" 1"#);
let _ = buffer.write(mb, SequenceNumber::new(12)).unwrap_err();
let set = buffer.sequence_number_set();
assert!(set.contains(SequenceNumber::new(24)));
assert!(!set.contains(SequenceNumber::new(12)));
assert_eq!(set.len(), 1);
}
/// Assert the summary statistics are correctly computed across various FSM
/// states.
#[test]
fn test_summary_statistics() {
let mut buffer: BufferState<Buffering> = BufferState::new();
// Write some data to a buffer.
buffer
.write(
lp_to_mutable_batch(
r#"bananas,tag=platanos great=true,how_much=42 668563242000000042"#,
)
.1,
SequenceNumber::new(0),
)
.expect("write to empty buffer should succeed");
assert_eq!(buffer.rows(), 1);
assert_eq!(
buffer.timestamp_stats(),
Some(TimestampMinMax {
min: 668563242000000042,
max: 668563242000000042
})
);
// Write another row to change the timestamp (it goes backwards!)
buffer
.write(
lp_to_mutable_batch(r#"bananas,tag=platanos great=true,how_much=42 42"#).1,
SequenceNumber::new(0),
)
.unwrap();
assert_eq!(buffer.rows(), 2);
assert_eq!(
buffer.timestamp_stats(),
Some(TimestampMinMax {
min: 42,
max: 668563242000000042
})
);
// Transition to a snapshot.
let buffer = assert_matches!(buffer.snapshot(), Transition::Ok(v) => v);
assert_eq!(buffer.rows(), 2);
assert_eq!(
buffer.timestamp_stats(),
Some(TimestampMinMax {
min: 42,
max: 668563242000000042
})
);
// Transition to persisting
let buffer = buffer.into_persisting();
assert_eq!(buffer.rows(), 2);
assert_eq!(
buffer.timestamp_stats(),
Some(TimestampMinMax {
min: 42,
max: 668563242000000042
})
);
}
}
|
use wasm_bindgen::JsCast;
use web_sys::WebGlRenderingContext as GL;
use web_sys::*;
use js_sys::WebAssembly;
use super::super::common_funcs as cf;
pub struct Color2D {
program: WebGlProgram,
vertex_buffer_length: usize,
gl_buffer: WebGlBuffer,
u_color: WebGlUniformLocation,
u_transform: WebGlUniformLocation
}
impl Color2D {
pub fn new(gl: &WebGlRenderingContext) -> Color2D {
let program = cf::link_program(
&gl,
super::super::shaders::vertex::color_2d::SHADER,
super::super::shaders::fragment::color_2d::SHADER
).unwrap();
let vertices: [f32; 12] = [
0., 1.,
0., 0.,
1., 1.,
1., 1.,
0., 0.,
1., 0.
];
let vertices_ptr_index = vertices.as_ptr() as u32 / 4;
let wasm_buffer = wasm_bindgen::memory()
.dyn_into::<WebAssembly::Memory>()
.unwrap()
.buffer();
let js_vertex_array = js_sys::Float32Array::new(&wasm_buffer).subarray(
vertices_ptr_index,
vertices_ptr_index + vertices.len() as u32
);
let gl_buffer = gl.create_buffer().ok_or("Failed to create buffer").unwrap();
gl.bind_buffer(GL::ARRAY_BUFFER, Some(&gl_buffer));
gl.buffer_data_with_array_buffer_view(GL::ARRAY_BUFFER, &js_vertex_array, GL::STATIC_DRAW);
Color2D {
u_color: gl.get_uniform_location(&program, "uColor").unwrap(),
u_transform: gl.get_uniform_location(&program, "uTransform").unwrap(),
gl_buffer,
vertex_buffer_length: vertices.len(),
program,
}
}
pub fn draw(
&self,
gl: &WebGlRenderingContext,
bottom: f32,
top: f32,
left: f32,
right: f32,
canvas_width: f32,
canvas_height: f32
) {
gl.use_program(Some(&self.program));
gl.bind_buffer(GL::ARRAY_BUFFER, Some(&self.gl_buffer));
gl.vertex_attrib_pointer_with_i32(0, 2, GL::FLOAT, false, 0, 0);
gl.enable_vertex_attrib_array(0);
gl.uniform4f(
Some(&self.u_color),
0.,
0.5,
0.25,
1.
);
let translation_matrix = cf::translation_matrix(
2. * left / canvas_width - 1.,
2. * bottom / canvas_height - 1.,
0.
);
let scale_matrix = cf::scale_matrix(
2. * (right - left) / canvas_width,
2. * (top - bottom) / canvas_height,
0.,
);
let transform_matrix = cf::multiply_matrix4(scale_matrix, translation_matrix);
gl.uniform_matrix4fv_with_f32_array(Some(&self.u_transform), false, &transform_matrix);
gl.draw_arrays(GL::TRIANGLES, 0, (self.vertex_buffer_length / 2) as i32);
}
} |
use std::path::{PathBuf, Path};
use std::fs::{Metadata, read_link};
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use users::{get_user_by_uid, get_group_by_gid};
use size::{Size, Base, Style};
use crate::core::MaxInfo;
use std::time::UNIX_EPOCH;
use time::Timespec;
use std::panic::resume_unwind;
quick_error!(
#[derive(Debug)]
pub enum MetaError {
UnableReadName(path: String) {
from(path)
}
Encoding(path: String) {
from(path)
}
UnableReadMate(path: String) {
from(path)
}
}
);
pub struct Meta {
pub path: PathBuf,
pub name: String,
pub permission: String,
pub group: String,
pub user: String,
pub meta: Metadata,
pub symlink: Option<String>,
pub filesize: String,
pub size_uint: String,
pub time: String,
}
impl Meta {
pub fn from_path(path: &Path) -> Result<Self, MetaError> {
let name = match path.file_name() {
Some(name) => match name.to_str() {
Some(name) => name.to_string(),
None => return Err(MetaError::Encoding(format!("Os str convert str fail. Path: {}", path.display().to_string())))
},
None => return Err(MetaError::UnableReadName(format!("Get file name error. Path: {}", path.display().to_string())))
};
let (meta, symlink) = match read_link(path) {
Ok(res) => {
let meta = path.symlink_metadata().expect(format!("Fail to read symlink {}", path.to_str().expect("path to str fail")).as_str());
let symlink = res.to_str().expect("Fail to convert pathbuf to str");
(meta, Some(symlink.to_string()))
},
_ => {
let meta = match path.metadata() {
Ok(meta) => meta,
_ => return Err(MetaError::UnableReadMate(format!("Get file metadata error. Path: {}", path.display().to_string())))
};
(meta, None)
}
};
let user = get_user_by_uid(meta.uid())
.expect("Get user by uid error")
.name()
.to_str()
.expect("User name os str convert to str fail")
.to_string();
let group = get_group_by_gid(meta.gid())
.expect("Get group by uid error")
.name()
.to_str()
.expect("Group name os str convert to str fail")
.to_string();
let filesize = Size::Bytes(meta.len()).to_string(Base::Base10, Style::Abbreviated);
let filesize_parts: Vec<_> = filesize.split(" ").collect();
let modified = meta.modified().expect("Get modified time fail");
let dur = modified.duration_since(UNIX_EPOCH).expect("Get The modified duration fail");
let modified_time = time::at(Timespec::new(
dur.as_secs() as i64,
dur.subsec_nanos() as i32,));
let modified = modified_time
.strftime("%m月 %d %H:%M")
.expect("format time error");
Ok(Meta{
path: path.to_path_buf(),
name,
user,
group,
permission: String::new(),
meta,
symlink,
filesize: filesize_parts[0].to_string(),
size_uint: filesize_parts[1].to_string(),
time: modified.to_string(),
})
}
fn format_group(&mut self, maxinfo: &MaxInfo) {
if self.group.len() < maxinfo.group {
for _ in 0..(maxinfo.group - self.group.len()) {
self.group.push(' ');
}
}
}
fn format_user(&mut self, maxinfo: &MaxInfo) {
if self.user.len() < maxinfo.user {
for _ in 0..(maxinfo.user - self.user.len()) {
self.user.push(' ');
}
}
}
fn format_filesize(&mut self, maxinfo: &MaxInfo) {
if self.filesize.len() < maxinfo.filesize {
for _ in 0..(maxinfo.filesize - self.filesize.len()) {
self.filesize.push(' ');
}
}
}
fn format_uint(&mut self, maxinfo: &MaxInfo) {
if self.size_uint.len() < maxinfo.sizeuint {
for _ in 0..(maxinfo.sizeuint - self.size_uint.len()) {
self.size_uint.push(' ');
}
}
}
fn format_symlink(&mut self) {
match self.symlink {
Some(ref link) => {
self.name.push_str(" => ");
self.name.push_str(link.as_str());
},
None => {}
}
}
fn format_permission(&mut self) {
let unix_permission = "rwxrwxrwx".to_string();
let mut permission = String::new();
if self.path.is_dir() {
permission.push('d');
} else {
match self.symlink {
Some(_) => permission.push('l'),
None => permission.push('-')
}
}
let mode = self.meta.permissions().mode();
for (key, value) in unix_permission.chars().enumerate() {
if mode & 0b100000000>>key == 0 {
permission.push('-')
} else {
permission.push(value);
}
}
self.permission = permission;
}
pub fn format_meta(&mut self, dirinfo: &MaxInfo) {
self.format_permission();
self.format_symlink();
self.format_group(dirinfo);
self.format_user(dirinfo);
self.format_filesize(dirinfo);
self.format_uint(dirinfo);
}
}
|
use embedded_graphics::{
draw_target::DrawTarget,
mono_font::{MonoFont, MonoTextStyle, MonoTextStyleBuilder},
pixelcolor::{PixelColor, Rgb888},
prelude::{Dimensions, Point, Size},
primitives::Rectangle,
text::renderer::{CharacterStyle, TextRenderer},
Drawable,
};
use embedded_gui::{
geometry::{measurement::MeasureSpec, MeasuredSize},
widgets::text_block::{TextBlock, TextBlockProperties},
WidgetRenderer,
};
use embedded_text::{
plugin::ansi::Ansi,
style::{HeightMode, TextBoxStyleBuilder, VerticalOverdraw},
TextBox as EgTextBox,
};
pub use embedded_text::alignment::{HorizontalAlignment, VerticalAlignment};
use crate::{EgCanvas, ToRectangle};
pub struct TextBlockStyle<T>
where
T: TextRenderer + CharacterStyle<Color = <T as TextRenderer>::Color>,
{
renderer: T,
horizontal: HorizontalAlignment,
vertical: VerticalAlignment,
}
impl<C, T> TextBlockStyle<T>
where
C: PixelColor,
T: TextRenderer<Color = C> + CharacterStyle<Color = C>,
{
/// Customize the text color
pub fn text_color(&mut self, text_color: C) {
self.renderer.set_text_color(Some(text_color));
}
}
impl<'a, C> TextBlockStyle<MonoTextStyle<'a, C>>
where
C: PixelColor,
{
/// Customize the font
pub fn font<'a2>(self, font: &'a2 MonoFont<'a2>) -> TextBlockStyle<MonoTextStyle<'a2, C>> {
TextBlockStyle {
renderer: MonoTextStyleBuilder::from(&self.renderer)
.font(font)
.build(),
horizontal: self.horizontal,
vertical: self.vertical,
}
}
}
impl<F, C> TextBlockProperties for TextBlockStyle<F>
where
F: TextRenderer<Color = C> + CharacterStyle<Color = C>,
C: PixelColor + From<Rgb888>,
{
fn measure_text(&self, text: &str, spec: MeasureSpec) -> MeasuredSize {
let max_width = spec.width.largest().unwrap_or(u32::MAX);
let max_height = spec.height.largest().unwrap_or(u32::MAX);
let bounding_box = EgTextBox::with_textbox_style(
text,
Rectangle::new(Point::zero(), Size::new(max_width, max_height)),
self.renderer.clone(),
TextBoxStyleBuilder::new()
.height_mode(HeightMode::Exact(VerticalOverdraw::Hidden))
.build(),
)
.bounding_box();
MeasuredSize {
width: bounding_box.size.width,
height: bounding_box.size.height,
}
}
}
pub trait TextBlockStyling<S, T>: Sized
where
T: CharacterStyle<Color = Self::Color>,
T: TextRenderer<Color = Self::Color>,
{
type Color;
fn text_color(mut self, color: Self::Color) -> Self {
self.set_text_color(color);
self
}
fn set_text_color(&mut self, color: Self::Color);
fn text_renderer<T2>(self, renderer: T2) -> TextBlock<S, TextBlockStyle<T2>>
where
T2: TextRenderer + CharacterStyle<Color = <T2 as TextRenderer>::Color>,
<T2 as TextRenderer>::Color: From<Rgb888>;
fn style<P>(self, props: P) -> TextBlock<S, P>
where
P: TextBlockProperties;
fn horizontal_alignment(self, alignment: HorizontalAlignment) -> Self;
fn vertical_alignment(self, alignment: VerticalAlignment) -> Self;
}
impl<'a, C, S> TextBlockStyling<S, MonoTextStyle<'a, C>>
for TextBlock<S, TextBlockStyle<MonoTextStyle<'a, C>>>
where
S: AsRef<str>,
C: PixelColor + From<Rgb888>,
{
type Color = C;
fn set_text_color(&mut self, color: Self::Color) {
self.label_properties.text_color(color);
}
fn text_renderer<T>(self, renderer: T) -> TextBlock<S, TextBlockStyle<T>>
where
T: TextRenderer + CharacterStyle<Color = <T as TextRenderer>::Color>,
<T as TextRenderer>::Color: From<Rgb888>,
{
let horizontal = self.label_properties.horizontal;
let vertical = self.label_properties.vertical;
self.style(TextBlockStyle {
renderer,
horizontal,
vertical,
})
}
fn style<P>(self, props: P) -> TextBlock<S, P>
where
P: TextBlockProperties,
{
TextBlock {
parent_index: self.parent_index,
text: self.text,
bounds: self.bounds,
label_properties: props,
on_state_changed: |_, _| (),
}
}
fn horizontal_alignment(self, alignment: HorizontalAlignment) -> Self {
let renderer = self.label_properties.renderer;
let horizontal = alignment;
let vertical = self.label_properties.vertical;
self.style(TextBlockStyle {
renderer,
horizontal,
vertical,
})
}
fn vertical_alignment(self, alignment: VerticalAlignment) -> Self {
let renderer = self.label_properties.renderer;
let horizontal = self.label_properties.horizontal;
let vertical = alignment;
self.style(TextBlockStyle {
renderer,
horizontal,
vertical,
})
}
}
/// Font settings specific to `MonoFont`'s renderer.
pub trait MonoFontTextBlockStyling<C, S>: Sized
where
S: AsRef<str>,
C: PixelColor,
{
fn font<'a>(self, font: &'a MonoFont<'a>)
-> TextBlock<S, TextBlockStyle<MonoTextStyle<'a, C>>>;
}
impl<'a, C, S> MonoFontTextBlockStyling<C, S> for TextBlock<S, TextBlockStyle<MonoTextStyle<'a, C>>>
where
S: AsRef<str>,
C: PixelColor + From<Rgb888>,
{
fn font<'a2>(
self,
font: &'a2 MonoFont<'a2>,
) -> TextBlock<S, TextBlockStyle<MonoTextStyle<'a2, C>>> {
let renderer = MonoTextStyleBuilder::from(&self.label_properties.renderer)
.font(font)
.build();
let horizontal = self.label_properties.horizontal;
let vertical = self.label_properties.vertical;
self.style(TextBlockStyle {
renderer,
horizontal,
vertical,
})
}
}
impl<S, F, C, DT> WidgetRenderer<EgCanvas<DT>> for TextBlock<S, TextBlockStyle<F>>
where
S: AsRef<str>,
F: TextRenderer<Color = C> + CharacterStyle<Color = C>,
C: PixelColor + From<Rgb888>,
DT: DrawTarget<Color = C>,
{
fn draw(&mut self, canvas: &mut EgCanvas<DT>) -> Result<(), DT::Error> {
EgTextBox::with_textbox_style(
self.text.as_ref(),
self.bounds.to_rectangle(),
self.label_properties.renderer.clone(),
TextBoxStyleBuilder::new()
.height_mode(HeightMode::Exact(VerticalOverdraw::Hidden))
.alignment(self.label_properties.horizontal)
.vertical_alignment(self.label_properties.vertical)
.build(),
)
.add_plugin(Ansi::new())
.draw(&mut canvas.target)
.map(|_| ())
}
}
macro_rules! textbox_for_charset {
($charset:ident, $font:ident) => {
pub mod $charset {
use embedded_graphics::{
mono_font::{$charset, MonoTextStyle},
pixelcolor::PixelColor,
};
use embedded_gui::{geometry::BoundingBox, widgets::text_block::TextBlock};
use embedded_text::alignment::{HorizontalAlignment, VerticalAlignment};
use crate::{themes::Theme, widgets::text_block::TextBlockStyle};
pub trait TextBlockConstructor<'a, S, C>
where
S: AsRef<str>,
C: PixelColor,
{
fn new(text: S) -> TextBlock<S, TextBlockStyle<MonoTextStyle<'a, C>>>;
}
impl<'a, C, S> TextBlockConstructor<'a, S, C>
for TextBlock<S, TextBlockStyle<MonoTextStyle<'a, C>>>
where
S: AsRef<str>,
C: PixelColor + Theme,
{
fn new(text: S) -> Self {
TextBlock {
parent_index: 0,
text,
label_properties: TextBlockStyle {
renderer: MonoTextStyle::new(
&$charset::$font,
<C as Theme>::TEXT_COLOR,
),
horizontal: HorizontalAlignment::Left,
vertical: VerticalAlignment::Top,
},
bounds: BoundingBox::default(),
on_state_changed: |_, _| (),
}
}
}
}
};
($charset:ident) => {
textbox_for_charset!($charset, FONT_6X10);
};
}
textbox_for_charset!(ascii);
textbox_for_charset!(iso_8859_1);
textbox_for_charset!(iso_8859_10);
textbox_for_charset!(iso_8859_13);
textbox_for_charset!(iso_8859_14);
textbox_for_charset!(iso_8859_15);
textbox_for_charset!(iso_8859_16);
textbox_for_charset!(iso_8859_2);
textbox_for_charset!(iso_8859_3);
textbox_for_charset!(iso_8859_4);
textbox_for_charset!(iso_8859_5);
textbox_for_charset!(iso_8859_7);
textbox_for_charset!(iso_8859_9);
textbox_for_charset!(jis_x0201, FONT_6X13);
|
// Definitions of all the different data structures needed for rendering
// This defines vectors and vector arithmetic, (more to come)
use std::ops::{Add, Sub, Mul};
#[derive(Debug, Clone)]
pub struct Vector {
pub x: f64,
pub y: f64,
pub z: f64,
pub w: f64,
}
#[derive(Debug, Clone)]
pub struct Matrix {
pub vals: [[f64; 4]; 4],
}
impl Vector {
pub fn new() -> Vector {
Vector {
x: 0f64,
y: 0f64,
z: 0f64,
w: 1f64,
}
}
pub fn from(x: f64, y: f64, z: f64, w: f64) -> Vector {
Vector {
x: x,
y: y,
z: z,
w: w,
}
}
pub fn magnitude(self) -> f64 {
(self.x.powf(2.0) + self.y.powf(2.0) + self.z.powf(2.0)).powf(0.5)
}
// Keep direction of vector but set magnitude to 1
pub fn normalise(&mut self) {
let m = self.clone().magnitude();
self.x /= m;
self.y /= m;
self.z /= m;
}
pub fn normalised(self) -> Vector {
let mut v = self.clone();
v.normalise();
v
}
pub fn dot_product(v1: &Vector, v2: &Vector) -> f64 {
return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;
}
pub fn cross_product(v1: &Vector, v2: &Vector) -> Vector {
return Vector::from(v1.y*v2.z-v1.z*v2.y, v1.z*v2.x-v1.x*v2.z, v1.x*v2.y-v1.y*v2.x, 0.0);
}
}
impl Mul<f64> for Vector {
type Output = Vector;
fn mul(self, rhs: f64) -> Vector {
Vector::from(self.x * rhs, self.y * rhs, self.z * rhs, self.w)
}
}
impl Add<Vector> for Vector {
type Output = Vector;
fn add(self, rhs: Vector) -> Vector {
Vector::from(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z, self.w)
}
}
impl Sub<Vector> for Vector {
type Output = Vector;
fn sub(self, rhs: Vector) -> Vector {
Vector::from(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z, self.w)
}
}
impl Matrix {
pub fn new() -> Matrix {
Matrix {
vals: [[0f64; 4]; 4],
}
}
pub fn translation(v: Vector) -> Matrix {
Matrix {
vals: [[1.0, 0.0, 0.0, v.x],
[0.0, 1.0, 0.0, v.y],
[0.0, 0.0, 1.0, v.z],
[0.0, 0.0, 0.0, 1.0]]
}
}
pub fn rotation(angle: f64, axis: Vector) -> Matrix {
let uvec = axis.normalised();
let ux = uvec.x;
let uy = uvec.y;
let uz = uvec.z;
Matrix {
vals: [
[angle.cos()+ux.powf(2.0)*(1.0-angle.cos()), ux*uy*(1.0-angle.cos())-uz*angle.sin(), ux*uz*(1.0-angle.cos())+uy*angle.sin(), 0.0],
[uy*ux*(1.0-angle.cos())+uz*angle.sin(), angle.cos()+uy.powf(2.0)*(1.0-angle.cos()), uy*uz*(1.0-angle.cos())-ux*angle.sin(), 0.0],
[uz*ux*(1.0-angle.cos())-uy*angle.sin(), uz*uy*(1.0-angle.cos())+ux*angle.sin(), angle.cos()+uz.powf(2.0)*(1.0-angle.cos()), 0.0],
[0.0, 0.0, 0.0, 0.0]
]
}
}
pub fn perspective(angle: f64, ratio: f64, near: f64, far: f64) -> Matrix {
// (THA stands for tan-half-angle - thought the variable name was unwieldy
let tha = (angle/2f64).tan();
Matrix {
vals: [[1.0/(ratio * tha), 0.0, 0.0, 0.0],
[0.0, 1.0/tha, 0.0, 0.0],
[0.0, 0.0, -(far + near)/(far - near), -(2.0*far*near)/(far-near)],
[0.0, 0.0, -1.0, 0.0]]
}
}
}
impl Mul<Vector> for Matrix {
type Output = Vector;
fn mul(self, rhs: Vector) -> Vector {
Vector {
x: self.vals[0][0]*rhs.x + self.vals[0][1]*rhs.y + self.vals[0][2]*rhs.z + self.vals[0][3]*rhs.w,
y: self.vals[1][0]*rhs.x + self.vals[1][1]*rhs.y + self.vals[1][2]*rhs.z + self.vals[1][3]*rhs.w,
z: self.vals[2][0]*rhs.x + self.vals[2][1]*rhs.y + self.vals[2][2]*rhs.z + self.vals[2][3]*rhs.w,
w: self.vals[3][0]*rhs.x + self.vals[3][1]*rhs.y + self.vals[3][2]*rhs.z + self.vals[3][3]*rhs.w,
}
}
}
impl Mul<Matrix> for Matrix {
type Output = Matrix;
fn mul(self, rhs: Matrix) -> Matrix {
let mut vals = [[0f64; 4]; 4];
// Watch as I condense matrix multiplication into the worst thing ever:
// A triple nested for loop. Fun for the whole family! That is if you have a family of
// masochists, though frankly I think 'masochist' and 'programmer' mean the same thing.
for i in 0..4 {
for j in 0..4 {
for k in 0..4 {
vals[i][j] += self.vals[i][k]*rhs.vals[k][j];
}
}
}
// Bruh
Matrix {
vals: vals,
}
}
}
|
//map.rs
//
//
use rand::random as rand;
use quicksilver::{
geom::Vector,
graphics::Color,
};
//derive for comp, vecs...
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Tile {
pub pos: Vector,
pub id: i32, // tile type code
pub ch: char, //for display during development
pub chance_val: i32, //
pub fare: i32, // cost to cross tile
pub seen: bool, // tile seen by player
pub color: Color, //replace with sprite
pub reqs: Vec<String>, // required items to enter/traverse tile
//...
}
impl Tile {
pub fn new(pos: Vector, id: i32) -> Tile {
Tile {
pos,
id,
ch: 'x',
chance_val: 0,
fare: 99,
seen: false,
color: Color::BLACK,
reqs: Vec::<String>::with_capacity(0),
}
}
pub fn get_display_ch(&self) -> &char {
if self.seen {
return &self.ch;
}
&'x'
}
pub fn get_display_color(&self) -> Color {
if self.seen {
return self.color;
}
Color::BLACK
}
pub fn mod_tile(
&mut self,
tile_type: char,
chance_val: i32,
fare: i32,
color: Color,
reqs: Vec<String>,
) {
self.ch = tile_type;
self.chance_val = chance_val;
self.fare = fare;
self.color = color;
self.reqs = reqs;
}
pub fn auto_mod_tile(&mut self, tile_type: char) {
self.ch = tile_type;
match tile_type {
'x' => {
self.chance_val = rand::<u8>() as i32 % 10; //keep range < 256
self.fare = rand::<u8>() as i32 % 10;
self.color = Color::from_hex("#006400"); //dark green
self.reqs.push("Blue towel".to_string());
}
'l' => {
self.color = Color::GREEN;
self.reqs.push("Green towel".to_string());
}
'm' => {
self.fare = 10;
self.color = Color::from_hex("#A52A2A"); //brown ish
self.reqs.push("Rope".to_string())
}
'w' => {
self.color = Color::BLUE;
self.reqs.push("Boat".to_string());
}
'o' => {
self.color = Color::ORANGE;
self.reqs.push("Orange towel".to_string());
}
'g' => {
self.fare = 0;
self.color = Color::from_hex("#FFD700"); //gold ish
}
_ => {}
};
}
pub fn set_seen(&mut self, seen: bool) {
self.seen = seen;
}
}
pub struct Map {
pub map: Vec<Tile>,
pub size: Vector,
pub win: bool,
}
// make default/shrouded display char/color xxx
impl Map {
pub fn new(x: i32, y: i32) -> Map {
Map {
size: Vector::new(x, y),
map: Vec::with_capacity((x * y) as usize),
win: false,
}
}
pub fn gen(x: i32, y: i32) -> Map {
let mut m = Map::new(x, y);
for i in 0..x {
for j in 0..y {
let pos = Vector::new(i, j);
let id = i + j * x;
let mut t = Tile::new(pos, id);
let r = rand::<u8>() % 10;
if i == 0 || i == x - 1 {
t.auto_mod_tile('l');
} else if j == 0 || j == y - 1 {
t.auto_mod_tile('o');
} else if r % 11 == 2 {
t.auto_mod_tile('w');
} else if r % 11 == 3 {
t.auto_mod_tile('m')
} else if id == 80 {
t.auto_mod_tile('g')
} else {
t.auto_mod_tile('x');
}
m.map.push(t);
}
}
m
}
pub fn get_tile(&self, pos: Vector) -> &Tile {
if self.is_on_board(pos) {
//if valid vector position, return tile from map's vec of tiles
return &self.map[(pos.y + pos.x * self.size.x) as usize] //must be usizable
} //else return tile 0 as default
return &self.map[0]
}
pub fn get_mut_tile(&mut self, pos: Vector) -> Option<&mut Tile> {
if self.is_on_board(pos) {
Some(&mut self.map[(pos.y + pos.x * self.size.x) as usize])
}
else {//return none
None }
}
pub fn pos_to_tile_id(pos: Vector, width: f32) -> usize {
(pos.y + pos.x * width) as usize
}
pub fn is_on_board(&self, o_pos: Vector) -> bool {
// make into vector trait ???
(o_pos.x >= 0.0 && o_pos.x <= self.size.x - 1.0)
&& (o_pos.y >= 0.0 && o_pos.y <= self.size.y - 1.0)
}
pub fn is_on_board_x(&self, other: f32) -> bool {
//<T: Into<f32>>
(other >= 0.0 && other <= self.size.x - 1.0)
}
pub fn is_on_board_y(&self, other: f32) -> bool {
(other >= 0.0 && other <= self.size.y - 1.0)
}
//tiles to be unshrouded
pub fn unshroud_dis_x(&mut self, pos: Vector, dis: i32) {
for x in 0..=dis * 2 {
//offset range nonneg
for y in 0..=dis * 2 {
let offset = Vector::new(x as i32 - dis, y as i32 - dis); // xxx
match self.get_mut_tile(pos + offset) {
Some(t) => t.set_seen(true),
None => (),
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_on_board() {
let m = Map::new(10, 10);
let p1 = m.is_on_board(Vector::new(0.0, 0.0));
let p2 = m.is_on_board(Vector::new(9, 9));
let p3 = m.is_on_board(Vector::new(5.0, 5.0));
let pf1 = m.is_on_board(Vector::new(-1.0, -1.0));
let pf2 = m.is_on_board(Vector::new(9.0, 9.1));
let pf3 = m.is_on_board(Vector::new(5.0, 15.0));
assert_eq!(p1 && p2 && p3, true);
assert_eq!(pf1 && pf2 && pf3, false);;
}
#[test]
fn test_is_on_board_x_y() {
let m = Map::new(10, 10);
let p1 = m.is_on_board_x(0.0);
let p2 = m.is_on_board_x(9.0);
let p3 = m.is_on_board_x(5.0);
let pf1 = m.is_on_board_x(-1.0);
let pf2 = m.is_on_board_x(10.0);
let pf3 = m.is_on_board_x(100.1);
assert_eq!(p1 && p2 && p3, true);
assert_eq!(pf1 && pf2 && pf3, false);
let p1 = m.is_on_board_y(0.0);
let p2 = m.is_on_board_y(9.0);
let p3 = m.is_on_board_y(5.0);
let pf1 = m.is_on_board_y(-1.0);
let pf2 = m.is_on_board_y(10.0);
let pf3 = m.is_on_board_y(100.1);
assert_eq!(p1 && p2 && p3, true);
assert_eq!(pf1 && pf2 && pf3, false);
}
#[test]
fn test_shroud() {
let mut m = Map::gen(10, 10);
//four corners
let (p1, p2, p3, p4) = (
Vector::new(0, 0),
Vector::new(9, 0),
Vector::new(0, 9),
Vector::new(9, 9),
);
//3 away
let (p1a, p2a, p3a, p4a) = (
Vector::new(3, 0),
Vector::new(9, 3),
Vector::new(3, 9),
Vector::new(6, 6),
);
assert_eq!(
m.get_tile(p1).seen
&& m.get_tile(p2).seen
&& m.get_tile(p3).seen
&& m.get_tile(p4).seen,
false
);
assert_eq!(
m.get_tile(p1a).seen
&& m.get_tile(p2a).seen
&& m.get_tile(p3a).seen
&& m.get_tile(p4a).seen,
false
);
//unshroud four corners
m.unshroud_dis_x(p1, 2);
m.unshroud_dis_x(p2, 2);
m.unshroud_dis_x(p3, 2);
m.unshroud_dis_x(p4, 2);
assert_eq!(
m.get_tile(p1).seen
&& m.get_tile(p2).seen
&& m.get_tile(p3).seen
&& m.get_tile(p4).seen,
true
); //points are seen
assert_eq!(
m.get_tile(p1a).seen
&& m.get_tile(p2a).seen
&& m.get_tile(p3a).seen
&& m.get_tile(p4a).seen,
false
); //outside of range are not
}
//test map gen
//
}
|
#![allow(dead_code)]
extern crate image;
use image::GenericImageView;
fn get_path(path: &str) -> String {
format!(
"/home/xypnox/Projects/learn/rustSick/experiments/pxsort_v1/src/{}",
path,
)
}
fn main() {
// Use the open function to load an image from a Path.
// `open` returns a `DynamicImage` on success.
let img = image::open(get_path("images/1.png")).unwrap();
// The dimensions method returns the images width and height.
println!("dimensions {:?}", img.dimensions());
// The color method returns the image's `ColorType`.
println!("{:?}", img.color());
// Use RBGA for everything so YOLO
// let mut buf = img.to_rgba();
// let buf2 = buf.clone();
// let mut sorted_pixels: Vec<_> = buf2.pixels().collect();
// sorted_pixels.sort_by_key(|p| );
// for (i, pixel) in buf.pixels_mut().enumerate() {
// *pixel = *sorted_pixels[i];
// }
img.save(get_path("images/output/1.png"))
.unwrap_or_else(|_| {
println!("Could not save image!");
});
}
|
use super::{
sppm::{Counter, KDTree, Pixel, Point},
Camera,
};
use crate::{
geo::Material,
geo::{Geo, HitResult},
linalg::{Ray, Vct},
utils::{clamp, Image, Rng},
Deserialize, Flt, Serialize, EPS, PI,
};
use pbr::ProgressBar;
use rand::prelude::*;
use rayon::prelude::*;
use std::sync::Mutex;
use std::time;
use std::time::Duration;
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct PT {
pub sample: usize,
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct SPPM {
pub view_point_sample: usize,
pub photon_sample: usize,
pub radius: Flt,
pub radius_decay: Flt,
pub rounds: usize,
pub light_pos: Vct,
pub light_r: Flt,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Renderer {
PT(PT),
SPPM(SPPM),
}
pub struct World {
pub objs: Vec<Box<dyn Geo>>,
pub camera: Camera,
pub max_depth: usize,
pub thread_num: usize,
pub stack_size: usize,
pub n1: Flt,
pub n2: Flt,
pub r0: Flt,
pub renderer: Renderer,
}
impl World {
pub fn new(
camera: Camera,
max_depth: usize,
thread_num: usize,
stack_size: usize,
na: Flt,
ng: Flt,
renderer: Renderer,
) -> Self {
Self {
objs: Vec::new(),
camera,
max_depth,
thread_num,
stack_size,
n1: na / ng,
n2: ng / na,
r0: ((na - ng) * (na - ng)) / ((na + ng) * (na + ng)),
renderer,
}
}
pub fn render(&self, p: &mut Image) {
match self.renderer {
Renderer::PT(cfg) => self.path_tracing(p, cfg),
Renderer::SPPM(cfg) => self.stochastic_progressive_photon_mapping(p, cfg),
};
}
fn gen(rng: &mut Rng) -> Flt {
let r = 2.0 * rng.gen();
if r < 1.0 {
r.sqrt() - 1.0
} else {
1.0 - (2.0 - r).sqrt()
}
}
pub fn add(&mut self, obj: Box<dyn Geo>) -> &mut Self {
self.objs.push(obj);
self
}
fn find<'a>(&'a self, r: &Ray) -> Option<HitResult> {
let mut t: Flt = 1e30;
let mut obj = None;
let mut gg = None;
self.objs.iter().for_each(|o| {
if let Some(d) = o.hit_t(r) {
if d.0 < t {
t = d.0;
gg = d.1;
obj = Some(o);
}
}
});
if let Some(o) = obj {
return Some(o.hit(r, (t, gg)));
}
None
}
fn pt(&self, r: &Ray, mut depth: usize, rng: &mut Rng) -> Vct {
if let Some(HitResult { pos, norm, ref texture }) = self.find(r) {
depth += 1;
if depth > self.max_depth {
return texture.emission;
}
let mut color = texture.color;
if depth > 5 {
let p = color.x.max(color.y.max(color.z));
if rng.gen() < p {
color /= p;
} else {
return texture.emission;
}
}
let mut ff = || {
let nd = norm.dot(r.direct);
if texture.material == Material::Diffuse {
let w = if nd < 0.0 { norm } else { -norm };
let (r1, r2) = (PI * 2.0 * rng.gen(), rng.gen());
let r2s = r2.sqrt();
let u = (if w.x.abs() <= 0.1 {
Vct::new(1.0, 0.0, 0.0)
} else {
Vct::new(0.0, 1.0, 0.0)
} % w)
.norm();
let v = w % u;
let d = (u * r1.cos() + v * r1.sin()) * r2s + w * (1.0 - r2).sqrt();
return self.pt(&Ray::new(pos, d.norm()), depth, rng);
}
let refl = Ray::new(pos, r.direct - norm * (2.0 * nd));
if texture.material == Material::Specular {
return self.pt(&refl, depth, rng);
}
let w = if nd < 0.0 { norm } else { -norm };
let (it, ddw) = (norm.dot(w) > 0.0, r.direct.dot(w));
let (n, sign) = if it { (self.n1, 1.0) } else { (self.n2, -1.0) };
let cos2t = 1.0 - n * n * (1.0 - ddw * ddw);
if cos2t < 0.0 {
return self.pt(&refl, depth, rng);
}
let td = (r.direct * n - norm * ((ddw * n + cos2t.sqrt()) * sign)).norm();
let refr = Ray::new(pos, td);
let c = if it { 1.0 + ddw } else { 1.0 - td.dot(norm) };
let cc = c * c;
let re = self.r0 + (1.0 - self.r0) * cc * cc * c;
let tr = 1.0 - re;
if depth > 2 {
let p = 0.25 + 0.5 * re;
if rng.gen() < p {
self.pt(&refl, depth, rng) * (re / p)
} else {
self.pt(&refr, depth, rng) * (tr / (1.0 - p))
}
} else {
self.pt(&refl, depth, rng) * re + self.pt(&refr, depth, rng) * tr
}
};
return texture.emission + color * ff();
}
Vct::zero()
}
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn path_tracing(&self, p: &mut Image, cfg: PT) {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(self.thread_num)
.stack_size(self.stack_size)
.build()
.unwrap();
pool.install(|| {
let (w, h) = (p.w, p.h);
let (fw, fh) = (w as Flt, h as Flt);
let cx = Vct::new(fw * self.camera.view_angle_scale / fh, 0.0, 0.0);
let cy = (cx % self.camera.direct).norm() * self.camera.view_angle_scale;
let sample = cfg.sample / 4;
let inv = 1.0 / sample as Flt;
let camera_direct = self.camera.direct.norm();
let max_dim = camera_direct.x.abs().max(camera_direct.y.abs().max(camera_direct.z.abs()));
let choose = if max_dim == camera_direct.x.abs() { 0 } else if max_dim == camera_direct.y.abs() { 1 } else { 2 };
let mut pb = ProgressBar::new((w * h) as u64);
pb.set_max_refresh_rate(Some(Duration::from_secs(1)));
let mut data: Vec<(usize, usize)> = Vec::new();
(0..w).for_each(|x| (0..h).for_each(|y| data.push((x, y))));
data.shuffle(&mut rand::thread_rng());
let pb = Mutex::new(pb);
let p = Mutex::new(p);
println!("w: {}, h: {}, sample: {}, actual sample: {}", w, h, cfg.sample, sample * 4);
println!("Start rendering with {} threads.", pool.current_num_threads());
let s_time = time::Instant::now();
data.into_par_iter().for_each(|(x, y)| {
let mut sum = Vct::zero();
let (fx, fy) = (x as Flt, y as Flt);
let mut rng = Rng::new((y * w + x) as u32);
for sx in 0..2 {
for sy in 0..2 {
let mut c = Vct::zero();
for _ in 0..sample {
let (fsx, fsy) = (sx as Flt, sy as Flt);
let ccx = cx * (((fsx + 0.5 + Self::gen(&mut rng)) / 2.0 + fx) / fw - 0.5);
let ccy = cy * (((fsy + 0.5 + Self::gen(&mut rng)) / 2.0 + fy) / fh - 0.5);
let rand_b = rng.gen() - 0.5;
let rand_a = rng.gen() - 0.5;
let d = camera_direct;
let r = if choose == 0 {
let (y, z) = (rand_a * d.y, rand_b * d.z);
Vct::new(-(y + z) / d.x, rand_a, rand_b)
} else if choose == 1 {
let (x, z) = (rand_a * d.x, rand_b * d.z);
Vct::new(rand_a, -(x + z) / d.y, rand_b)
} else {
let (x, y) = (rand_a * d.x, rand_b * d.y);
Vct::new(rand_a, rand_b, -(x + y) / d.z)
}.norm() * self.camera.aperture * rng.gen();
let d = ccx + ccy + d;
let o = self.camera.origin + r + d * self.camera.plane_distance;
let d = (d.norm() * self.camera.focal_distance - r).norm();
c += self.pt(&Ray::new(o, d), 0, &mut rng) * inv;
}
sum += Vct::new(clamp(c.x), clamp(c.y), clamp(c.z)) * 0.25;
}
}
p.lock().unwrap().set(x, h - y - 1, sum);
pb.lock().unwrap().inc();
});
pb.lock().unwrap().finish_println("...done\n");
let mils = (time::Instant::now() - s_time).as_millis();
let days = mils / 1000 / 60 / 60 / 24;
let hours = mils / 1000 / 60 / 60 - days * 24;
let mins = mils / 1000 / 60 - days * 24 * 60 - hours * 60;
let secs = mils / 1000 - days * 24 * 60 * 60 - hours * 60 * 60 - mins * 60;
println!("Total cost {}d {}h {}m {}s.", days, hours, mins, secs);
});
}
fn sppm_1(
&self,
r: &Ray,
mut depth: usize,
rng: &mut Rng,
points: &mut Vec<Point>,
prod: Vct,
index: usize,
prob: Flt,
) {
if prod.x.max(prod.y.max(prod.z)) < EPS {
return;
}
if prob < EPS {
return;
}
depth += 1;
if depth > self.max_depth {
return;
}
if let Some(HitResult { pos, norm, ref texture }) = self.find(r) {
let mut color = texture.color;
if depth > 5 {
let p = color.x.max(color.y.max(color.z));
if rng.gen() < p {
color /= p;
} else {
return;
}
}
let prod = prod * color;
if texture.material == Material::Diffuse {
points.push(Point::new(pos, norm, prod, index));
return;
}
let nd = norm.dot(r.direct);
let refl = Ray::new(pos, r.direct - norm * (2.0 * nd));
if texture.material == Material::Specular {
self.sppm_1(&refl, depth, rng, points, prod, index, prob);
return;
}
let w = if nd < 0.0 { norm } else { -norm };
let (it, ddw) = (norm.dot(w) > 0.0, r.direct.dot(w));
let (n, sign) = if it { (self.n1, 1.0) } else { (self.n2, -1.0) };
let cos2t = 1.0 - n * n * (1.0 - ddw * ddw);
if cos2t < 0.0 {
self.sppm_1(&refl, depth, rng, points, prod, index, prob);
return;
}
let td = (r.direct * n - norm * ((ddw * n + cos2t.sqrt()) * sign)).norm();
let refr = Ray::new(pos, td);
let c = if it { 1.0 + ddw } else { 1.0 - td.dot(norm) };
let cc = c * c;
let re = self.r0 + (1.0 - self.r0) * cc * cc * c;
let tr = 1.0 - re;
if depth > 2 {
let p = 0.25 + 0.5 * re;
if rng.gen() < p {
self.sppm_1(&refl, depth, rng, points, prod, index, prob * (re / p));
} else {
self.sppm_1(&refr, depth, rng, points, prod, index, prob * (tr / (1.0 - p)));
}
} else {
self.sppm_1(&refl, depth, rng, points, prod, index, prob * re);
self.sppm_1(&refr, depth, rng, points, prod, index, prob * tr);
}
}
}
fn sppm_2(
&self,
r: &Ray,
mut depth: usize,
rng: &mut Rng,
tree: &KDTree,
pixels: &mut Vec<Pixel>,
flux: Vct,
) {
if flux.x.max(flux.y.max(flux.z)) < EPS {
return;
}
depth += 1;
if depth > self.max_depth {
return;
}
if let Some(HitResult { pos, norm, ref texture }) = self.find(r) {
let mut color = texture.color;
if depth > 5 {
let p = color.x.max(color.y.max(color.z));
if rng.gen() < p {
color /= p;
} else {
return;
}
}
let nd = norm.dot(r.direct);
if texture.material == Material::Diffuse {
tree.update(&pos, &norm, &flux, pixels);
let w = if nd < 0.0 { norm } else { -norm };
let (r1, r2) = (PI * 2.0 * rng.gen(), rng.gen());
let r2s = r2.sqrt();
let u = (if w.x.abs() <= 0.1 {
Vct::new(1.0, 0.0, 0.0)
} else {
Vct::new(0.0, 1.0, 0.0)
} % w)
.norm();
let v = w % u;
let d = (u * r1.cos() + v * r1.sin()) * r2s + w * (1.0 - r2).sqrt();
self.sppm_2(&Ray::new(pos, d.norm()), depth, rng, tree, pixels, flux * color);
return;
}
let flux = flux * color;
let refl = Ray::new(pos, r.direct - norm * (2.0 * nd));
if texture.material == Material::Specular {
self.sppm_2(&refl, depth, rng, tree, pixels, flux);
return;
}
let w = if nd < 0.0 { norm } else { -norm };
let (it, ddw) = (norm.dot(w) > 0.0, r.direct.dot(w));
let (n, sign) = if it { (self.n1, 1.0) } else { (self.n2, -1.0) };
let cos2t = 1.0 - n * n * (1.0 - ddw * ddw);
if cos2t < 0.0 {
self.sppm_2(&refl, depth, rng, tree, pixels, flux);
return;
}
let td = (r.direct * n - norm * ((ddw * n + cos2t.sqrt()) * sign)).norm();
let refr = Ray::new(pos, td);
let c = if it { 1.0 + ddw } else { 1.0 - td.dot(norm) };
let cc = c * c;
let re = self.r0 + (1.0 - self.r0) * cc * cc * c;
if depth > 2 {
let p = 0.25 + 0.5 * re;
if rng.gen() < p {
self.sppm_2(&refl, depth, rng, tree, pixels, flux);
} else {
self.sppm_2(&refr, depth, rng, tree, pixels, flux);
}
} else {
self.sppm_2(&refl, depth, rng, tree, pixels, flux);
self.sppm_2(&refr, depth, rng, tree, pixels, flux);
}
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn stochastic_progressive_photon_mapping(&self, p: &mut Image, cfg: SPPM) {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(self.thread_num)
.stack_size(self.stack_size)
.build()
.unwrap();
pool.install(|| {
let (w, h) = (p.w, p.h);
let (fw, fh) = (w as Flt, h as Flt);
let cx = Vct::new(fw * self.camera.view_angle_scale / fh, 0.0, 0.0);
let cy = (cx % self.camera.direct).norm() * self.camera.view_angle_scale;
let thread_num = pool.current_num_threads();
let sample = cfg.view_point_sample / 4;
let camera_direct = self.camera.direct.norm();
let max_dim = camera_direct.x.abs().max(camera_direct.y.abs().max(camera_direct.z.abs()));
let choose = if max_dim == camera_direct.x.abs() { 0 } else if max_dim == camera_direct.y.abs() { 1 } else { 2 };
let mut radius = cfg.radius;
let radius_decay = cfg.radius_decay;
let rounds = cfg.rounds;
let photon_sample = cfg.photon_sample / thread_num;
println!("w: {}, h: {}, view point sample: {}, actual sample: {}", w, h, cfg.view_point_sample, sample * 4);
println!("photon samples: {}, total rounds: {}, init radius: {}, radius decay: {}", photon_sample * thread_num, rounds, radius, radius_decay);
println!("Start rendering with {} threads.", pool.current_num_threads());
let s_time = time::Instant::now();
let mut final_pixel = vec![Vct::zero(); w * h];
for iter in 0..rounds {
println!("Round: {}, radius: {}", iter + 1, radius);
let mut data: Vec<(usize, usize)> = Vec::new();
(0..w).for_each(|x| (0..h).for_each(|y| data.push((x, y))));
data.shuffle(&mut rand::thread_rng());
let total_points = Mutex::new(vec![]);
println!("Running sppm1");
data.into_par_iter().for_each(|(x, y)| {
let (fx, fy) = (x as Flt, y as Flt);
let index = y * w + x;
let mut rng = Rng::new((index + iter * w * h) as u32);
let mut points = vec![];
for sx in 0..2 {
for sy in 0..2 {
for _ in 0..sample {
let (fsx, fsy) = (sx as Flt, sy as Flt);
let ccx = cx * (((fsx + 0.5 + Self::gen(&mut rng)) / 2.0 + fx) / fw - 0.5);
let ccy = cy * (((fsy + 0.5 + Self::gen(&mut rng)) / 2.0 + fy) / fh - 0.5);
let rand_b = rng.gen() - 0.5;
let rand_a = rng.gen() - 0.5;
let d = camera_direct;
let r = if choose == 0 {
let (y, z) = (rand_a * d.y, rand_b * d.z);
Vct::new(-(y + z) / d.x, rand_a, rand_b)
} else if choose == 1 {
let (x, z) = (rand_a * d.x, rand_b * d.z);
Vct::new(rand_a, -(x + z) / d.y, rand_b)
} else {
let (x, y) = (rand_a * d.x, rand_b * d.y);
Vct::new(rand_a, rand_b, -(x + y) / d.z)
}.norm() * self.camera.aperture * rng.gen();
let d = ccx + ccy + d;
let o = self.camera.origin + r + d * self.camera.plane_distance;
let d = (d.norm() * self.camera.focal_distance - r).norm();
self.sppm_1(&Ray::new(o, d), 0, &mut rng, &mut points, Vct::one() * 0.35 / (iter + 1) as Flt, index, 1.0);
}
}
}
total_points.lock().unwrap().append(&mut points);
});
println!("...done");
let mut total_points = total_points.lock().unwrap();
println!("Total view points: {}", total_points.len());
println!("Building tree");
let tree = KDTree::new(&mut total_points, radius);
println!("...done");
let mut pb = ProgressBar::new((photon_sample * thread_num) as u64);
pb.set_max_refresh_rate(Some(Duration::from_secs(1)));
let pb = Mutex::new(pb);
let total_pixel = Mutex::new(vec![Counter::default(); w * h]);
println!("Running sppm2");
(0..thread_num).into_par_iter().for_each(|index| {
let mut pixels = vec![Pixel::default(); w * h];
let mut rng = Rng::new((iter * thread_num + index) as u32);
for i in 1..=photon_sample {
let ang = rng.gen() * PI * 2.0;
let r = rng.gen() * cfg.light_r;
let o = Vct::new(cfg.light_pos.x + r * ang.cos(), cfg.light_pos.y, cfg.light_pos.z + r * ang.sin());
let t1 = rng.gen() * PI * 2.0;
let t2 = rng.gen() * PI * 2.0;
let mut d = Vct::new(t1.sin() * t2.cos(), t1.sin() * t2.sin(), t1.cos()).norm();
if d.y < 0.0 {
d.y = -d.y;
}
self.sppm_2(&Ray::new(o, d), 0, &mut rng, &tree, &mut pixels, Vct::one());
if i % 100 == 0 {
pb.lock().unwrap().add(100);
}
}
let mut total = total_pixel.lock().unwrap();
for i in 0..pixels.len() {
total[i].add(pixels[i].flux, pixels[i].n);
}
pb.lock().unwrap().add(photon_sample as u64 % 100);
});
pb.lock().unwrap().finish_println("...done\n");
let total = total_pixel.lock().unwrap();
for i in 0..total.len() {
final_pixel[i] += total[i].get();
}
radius *= radius_decay;
for x in 0..w {
for y in 0..h {
p.set(x, h - y - 1, final_pixel[y * w + x]);
}
}
p.save_png(&format!("./result/test/test_{}.png", iter));
}
for x in 0..w {
for y in 0..h {
p.set(x, h - y - 1, final_pixel[y * w + x]);
}
}
let mils = (time::Instant::now() - s_time).as_millis();
let days = mils / 1000 / 60 / 60 / 24;
let hours = mils / 1000 / 60 / 60 - days * 24;
let mins = mils / 1000 / 60 - days * 24 * 60 - hours * 60;
let secs = mils / 1000 - days * 24 * 60 * 60 - hours * 60 * 60 - mins * 60;
println!("Total cost {}d {}h {}m {}s.", days, hours, mins, secs);
});
}
}
|
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
use std::fs;
fn main() {
run();
}
#[allow(clippy::cast_lossless)]
#[allow(clippy::cast_possible_truncation)]
fn run() {
let start = std::time::Instant::now();
// code goes here
let mut names: Vec<String> = fs::read_to_string("./names.txt")
.expect("could not read file")
.replace("\"", "")
.replace(",", " ")
.split_ascii_whitespace()
.map(std::string::ToString::to_string)
.collect();
names.sort();
let res: usize = names
.iter()
.enumerate()
.map(|(i, name)| {
name
.chars()
.map(|c| ((c as u8) - b'A' + 1) as usize)
.sum::<usize>()
* (i + 1)
})
.sum();
let span = start.elapsed().as_nanos();
println!("{} {}", res, span);
}
|
mod args;
use args::{Address, OneRegister, RegisterAndValue, TwoRegisters};
#[derive(Debug)]
pub enum Opcode {
// 0x0
ClearScreen,
Return,
Call(Address),
// 0x01
Jump(Address),
// 0x02
CallSubroutine(Address),
// 0x03
SkipIfEqual(RegisterAndValue),
// 0x04
SkipIfNotEqual(RegisterAndValue),
// 0x05
SkipIfEqualRegister(TwoRegisters),
// 0x06
SetValue(RegisterAndValue),
// 0x07
AddValue(RegisterAndValue),
// 0x08
AssignRegister(TwoRegisters),
BitwiseOr(TwoRegisters),
BitwiseAnd(TwoRegisters),
BitwiseXor(TwoRegisters),
AddRegister(TwoRegisters),
SubtractRegister(TwoRegisters),
RightShiftByOne(TwoRegisters),
ReverseSubtractRegister(TwoRegisters),
LeftShiftByOne(TwoRegisters),
// 0x09
SkipIfNotEqualRegister(TwoRegisters),
// 0xA
SetMemoryToValue(Address),
// 0xB
JumpWithOffset(Address),
// 0xC
RandAnd(RegisterAndValue),
// 0xD
Draw(TwoRegisters),
// 0xE
SkipIfKeyPressed(OneRegister),
SkipIfKeyNotPressed(OneRegister),
// 0xF
SetFromDelayTimer(OneRegister),
GetKey(OneRegister),
SetDelayTimer(OneRegister),
SetSoundTimer(OneRegister),
AddRegisterToMemory(OneRegister),
SetChar(OneRegister),
SetMemoryToBcd(OneRegister),
RegDump(OneRegister),
RegLoad(OneRegister),
Unknown,
}
impl From<[u8; 2]> for Opcode {
fn from(opcode: [u8; 2]) -> Opcode {
let [hi, lo] = opcode;
match hi >> 4u8 {
0x0 => match lo {
0xE0 => Opcode::ClearScreen,
0xEE => Opcode::Return,
_ => Opcode::Call(Address::from(opcode)),
},
0x1 => Opcode::Jump(Address::from(opcode)),
0x2 => Opcode::CallSubroutine(Address::from(opcode)),
0x3 => Opcode::SkipIfEqual(RegisterAndValue::from(opcode)),
0x4 => Opcode::SkipIfNotEqual(RegisterAndValue::from(opcode)),
0x5 => Opcode::SkipIfEqualRegister(TwoRegisters::from(opcode)),
0x6 => Opcode::SetValue(RegisterAndValue::from(opcode)),
0x7 => Opcode::AddValue(RegisterAndValue::from(opcode)),
0x8 => match lo & 0x0F {
0x1 => Opcode::BitwiseOr(TwoRegisters::from(opcode)),
0x0 => Opcode::AssignRegister(TwoRegisters::from(opcode)),
0x2 => Opcode::BitwiseAnd(TwoRegisters::from(opcode)),
0x3 => Opcode::BitwiseXor(TwoRegisters::from(opcode)),
0x4 => Opcode::AddRegister(TwoRegisters::from(opcode)),
0x5 => Opcode::SubtractRegister(TwoRegisters::from(opcode)),
0x6 => Opcode::RightShiftByOne(TwoRegisters::from(opcode)),
0x7 => Opcode::ReverseSubtractRegister(TwoRegisters::from(opcode)),
0xE => Opcode::LeftShiftByOne(TwoRegisters::from(opcode)),
_ => Opcode::Unknown,
},
0x9 => Opcode::SkipIfNotEqualRegister(TwoRegisters::from(opcode)),
0xA => Opcode::SetMemoryToValue(Address::from(opcode)),
0xB => Opcode::JumpWithOffset(Address::from(opcode)),
0xC => Opcode::RandAnd(RegisterAndValue::from(opcode)),
0xD => Opcode::Draw(TwoRegisters::from(opcode)),
0xE => match lo {
0x9E => Opcode::SkipIfKeyPressed(OneRegister::from(opcode)),
0xA1 => Opcode::SkipIfKeyNotPressed(OneRegister::from(opcode)),
_ => Opcode::Unknown,
},
0xF => match lo {
0x07 => Opcode::SetFromDelayTimer(OneRegister::from(opcode)),
0x0A => Opcode::GetKey(OneRegister::from(opcode)),
0x15 => Opcode::SetDelayTimer(OneRegister::from(opcode)),
0x18 => Opcode::SetSoundTimer(OneRegister::from(opcode)),
0x1E => Opcode::AddRegisterToMemory(OneRegister::from(opcode)),
0x29 => Opcode::SetChar(OneRegister::from(opcode)),
0x33 => Opcode::SetMemoryToBcd(OneRegister::from(opcode)),
0x55 => Opcode::RegDump(OneRegister::from(opcode)),
0x65 => Opcode::RegLoad(OneRegister::from(opcode)),
_ => Opcode::Unknown,
},
_ => Opcode::Unknown,
}
}
} |
//
// line2.rs
// Copyright (C) 2019 Malcolm Ramsay <malramsay64@gmail.com>
// Distributed under terms of the MIT license.
//
use std::fmt;
#[cfg(test)]
use approx::AbsDiffEq;
use nalgebra::Point2;
use serde::{Deserialize, Serialize};
use crate::traits::Intersect;
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub struct Line2 {
pub start: Point2<f64>,
pub end: Point2<f64>,
}
impl Intersect for Line2 {
/// Determine whether two line segments intersect
///
/// This calculates whether two lines intersect at a point contained within each line segment
/// see [this](https://en.wikipedia.org/wiki/Intersection_%28Euclidean_geometry%29#Two_line_segments)
/// Wikipedia article for more information on the algorithm used for this calculation.
///
fn intersects(&self, other: &Self) -> bool {
// Also see below links for other implementations of this algorithm
// - https://github.com/georust/geo/blob/96c7846d703a74f59ba68e68929415cbce4a68d9/geo/src/algorithm/intersects.rs#L142
// - https://github.com/brandonxiang/geojson-python-utils/blob/33b4c00c6cf27921fb296052d0c0341bd6ca1af2/geojson_utils.py
// - http://www.kevlindev.com/gui/math/intersection/Intersection.js
//
let u_b = other.dy() * self.dx() - other.dx() * self.dy();
// Where u_b == 0 the two lines are parallel. In this case we don't need any further checks
// since we are only concerned with lines that cross, parallel is fine.
if u_b == 0. {
return false;
}
let ua_t = other.dx() * (self.start.y - other.start.y)
- other.dy() * (self.start.x - other.start.x);
let ub_t =
self.dx() * (self.start.y - other.start.y) - self.dy() * (self.start.x - other.start.x);
let ua = ua_t / u_b;
let ub = ub_t / u_b;
// Should the points ua, ub both lie on the interval [0, 1] the lines intersect.
if (0. ..=1.).contains(&ua) && (0. ..=1.).contains(&ub) {
return true;
}
false
}
fn area(&self) -> f64 {
// TODO Implement some area calculation being the area to the origin or to the y axis.
0.
}
}
#[cfg(test)]
impl AbsDiffEq for Line2 {
type Epsilon = f64;
fn default_epsilon() -> Self::Epsilon {
std::f64::EPSILON
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
self.start.abs_diff_eq(&other.start, epsilon) && self.end.abs_diff_eq(&other.end, epsilon)
}
}
impl fmt::Display for Line2 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Line2 {{ ({:.5}, {:.5}), ({:.5}, {:.5}) }}",
self.start.x, self.start.y, self.end.x, self.end.y
)
}
}
impl Line2 {
pub fn new(start: (f64, f64), end: (f64, f64)) -> Self {
Self {
start: Point2::new(start.0, start.1),
end: Point2::new(end.0, end.1),
}
}
/// The difference in the x values over the line.
pub fn dx(&self) -> f64 {
self.end.x - self.start.x
}
/// The difference in the y values over the line.
pub fn dy(&self) -> f64 {
self.end.y - self.start.y
}
}
#[cfg(test)]
mod test {
use itertools::iproduct;
use super::*;
use crate::Transform2;
#[test]
fn new() {
let line = Line2::new((1., 0.), (0., 1.));
assert_eq!(line.start, Point2::new(1., 0.));
assert_eq!(line.end, Point2::new(0., 1.));
}
#[test]
fn intersects_radial() -> Result<(), String> {
// Testing lines to and from the same point don't intersect
// Using values of -1, 0, 1 for the x and y axes
let values: Vec<f64> = vec![-1., 0., 1.];
let points: Vec<(f64, f64)> = values
.iter()
.zip(values.iter())
.map(|(a, b)| (*a, *b))
.collect();
let mut result = Ok(());
for (start1, start2) in iproduct!(points.iter(), points.iter()) {
let l1 = Line2::new(*start1, (0., 0.));
let l2 = Line2::new(*start2, (0., 0.));
if l1.intersects(&l2) {
println!("{:?} {:?}", start1, start2);
result = Err(String::from(""));
}
}
result
}
#[test]
fn isometry_matrix_mul() {
let ident: Transform2 = Transform2::identity();
let line = Line2::new((1., 1.), (0., 0.));
assert_eq!(line * ident, line);
let trans: Transform2 = Transform2::new(0., (1., 1.));
assert_eq!(line * trans, Line2::new((2., 2.), (1., 1.)));
}
//
// +-------------------|-------------------+
// | | |
// | + 1 |
// | | |
// | | |
// | | |
// | p3 | p1 p2 |
// |---------+---------+---------+---------|
// | -1 | 1 |
// | | |
// | | |
// | p5 | |
// | + p4 + -1 |
// | | |
// | | |
// +-------------------|-------------------+
//
#[test]
fn intersects() {
let line1 = Line2::new((-1., 0.), (0., -1.));
let line2 = Line2::new((-1., -1.), (0., 0.));
assert!(line1.intersects(&line2));
assert!(line2.intersects(&line1));
let line3 = Line2::new((-2., -1.), (1., 0.));
assert!(line2.intersects(&line3));
assert!(line3.intersects(&line2));
assert!(line1.intersects(&line3));
assert!(line3.intersects(&line1));
}
}
|
use num_bigint::{BigUint, RandBigInt};
use rand::Rng;
uint::construct_uint! {
struct U256(4);
}
pub fn factorization(n: u128) -> Vec<u128> {
if is_prime(&n.into()) {
return vec![n];
}
let mut ret = vec![];
let mut n = n;
while !is_prime(&n.into()) {
let factor = pollard_rho(n);
assert!(n > factor);
assert!(n % factor == 0);
ret.append(&mut factorization(factor));
n /= factor;
}
if n > 1 {
ret.push(n);
}
ret.sort();
ret
}
pub fn is_prime(n: &BigUint) -> bool {
if n == &0u32.into() || n == &1u32.into() {
false
} else if n == &2u32.into() || n == &3u32.into() {
true
} else {
miller_rabin_test(n, 100) == MillerRabinResult::ProbablyPrime
}
}
#[derive(PartialEq, Eq, Debug)]
enum MillerRabinResult {
Composite,
ProbablyPrime,
}
fn miller_rabin_test(n: &BigUint, k: usize) -> MillerRabinResult {
let t: BigUint = n - 1_u32;
let r = t.trailing_zeros().unwrap();
let d = t.clone() >> r;
let one = BigUint::from(1u32);
let two = BigUint::from(2u32);
let mut rng = rand::thread_rng();
'outer: for _ in 0..k {
let a: BigUint = rng.gen_biguint_range(&two, &t);
let mut x = a.modpow(&d, &n);
if x == one || x == t {
continue;
}
for _ in 1..r {
x = x.modpow(&two, &n);
if x == t {
continue 'outer;
}
}
return MillerRabinResult::Composite;
}
MillerRabinResult::ProbablyPrime
}
pub fn gen_prime(bits: usize, rng: &mut impl Rng) -> BigUint {
loop {
let n = rng.gen_biguint(bits as _);
if is_prime(&n) {
break n;
}
}
}
pub fn pollard_rho(n: u128) -> u128 {
loop {
if let Some(ret) = pollard_rho_once(n, rand::thread_rng().gen_range(2, n)) {
return ret;
}
}
}
fn pollard_rho_once(n: u128, mut x: u128) -> Option<u128> {
for cycle in 1.. {
let y = x;
for _ in 0..1 << cycle {
x = mul_mod(x, x, n);
x = (x + 1) % n;
let d = if x >= y { x - y } else { y - x };
let factor = gcd(d, n);
if factor > 1 {
return if factor != n { Some(factor) } else { None };
}
}
}
unreachable!()
}
fn gcd(a: u128, b: u128) -> u128 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
fn mul_mod(a: u128, b: u128, m: u128) -> u128 {
(U256::from(a) * U256::from(b) % U256::from(m)).as_u128()
}
#[cfg(test)]
mod tests {
use crate::*;
use rand::Rng;
use MillerRabinResult::*;
#[test]
fn miller_rabin() {
assert_eq!(miller_rabin_test(&4u32.into(), 100), Composite);
assert_eq!(miller_rabin_test(&5u32.into(), 100), ProbablyPrime);
assert_eq!(miller_rabin_test(&6u32.into(), 100), Composite);
assert_eq!(miller_rabin_test(&7u32.into(), 100), ProbablyPrime);
assert_eq!(miller_rabin_test(&8u32.into(), 100), Composite);
assert_eq!(miller_rabin_test(&9u32.into(), 100), Composite);
assert_eq!(miller_rabin_test(&10u32.into(), 100), Composite);
let primes = [
241393502644931236824083437316691947053_u128,
203851774287909279562700874830405601907,
288998372467163468683539125188698897449,
189822170223895762265064303540250435637,
328089814025503192461392250603431433007,
296924869529206030921754222802047897761,
239796305212141579879826223504530404303,
183793893507075905518837979761809022117,
];
for &p in primes.iter() {
assert_eq!(miller_rabin_test(&p.into(), 100), ProbablyPrime);
}
let composites = [
123818405246410390178707765938870261443_u128,
202383583825519051662160491314347582777,
167210971201646539721622042892407080737,
117531937261998017622502744988913176479,
212783729721844122818518594528126775039,
305792237550134519087322660700463788397,
93694064147469858944238195598447143569,
132633955283692567229336700018758707763,
];
for &c in composites.iter() {
assert_eq!(miller_rabin_test(&c.into(), 100), Composite);
}
}
#[test]
fn factorization_test() {
assert_eq!(factorization(2), [2]);
assert_eq!(factorization(3), [3]);
assert_eq!(factorization(4), [2, 2]);
assert_eq!(factorization(5), [5]);
assert_eq!(factorization(6), [2, 3]);
assert_eq!(factorization(7), [7]);
assert_eq!(factorization(8), [2, 2, 2]);
assert_eq!(factorization(9), [3, 3]);
assert_eq!(factorization(10), [2, 5]);
let test = |x| {
let fs = factorization(x);
assert!(fs.iter().all(|&f| is_prime(&f.into())));
assert_eq!(fs.iter().product::<u128>(), x);
};
for x in 2..1000 {
test(x);
}
for _ in 0..100 {
let x = rand::thread_rng().gen_range(2, u64::MAX as u128);
test(x);
}
}
}
|
use crate::algebra::linear::scalar::Scalar;
use fructose::operators::{ClosedAdd, ClosedDiv, ClosedMul, ClosedSub};
use std::fmt::{Debug, Display, Formatter};
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
use std::str::FromStr;
#[derive(Debug, Clone)]
pub struct DVector<T> {
pub data: Vec<T>,
pub len: usize,
}
impl<T> DVector<T> {
pub fn new(data: Vec<T>) -> Self {
let len = data.len();
Self { data, len }
}
}
impl<T: Default + Copy> DVector<T> {
pub fn default_with_size(size: usize) -> Self {
let data = vec![T::default(); size];
DVector { data, len: size }
}
}
impl<T: Scalar + ClosedAdd + ClosedMul> DVector<T> {
pub fn dot(&self, other: Self) -> T {
let mut sum = T::default();
for i in 0..self.len {
sum += self.data[i];
}
sum
}
}
impl<T: Default + Copy> Default for DVector<T> {
fn default() -> Self {
Self {
data: Default::default(),
len: 0,
}
}
}
impl<T: Scalar + ClosedAdd> Add for DVector<T> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
assert_eq!(self.len, rhs.len);
let mut vec = self.clone();
for i in 0..self.len {
vec.data[i] += rhs.data[i];
}
vec
}
}
impl<T: Scalar + ClosedAdd> AddAssign for DVector<T> {
fn add_assign(&mut self, rhs: Self) {
assert_eq!(self.len, rhs.len);
for i in 0..self.len {
self.data[i] += rhs.data[i];
}
}
}
impl<T: Scalar + ClosedSub> Sub for DVector<T> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
assert_eq!(self.len, rhs.len);
let mut vec = self.clone();
for i in 0..self.len {
vec.data[i] -= rhs.data[i];
}
vec
}
}
impl<T: Scalar + ClosedSub> SubAssign for DVector<T> {
fn sub_assign(&mut self, rhs: Self) {
assert_eq!(self.len, rhs.len);
for i in 0..self.len {
self.data[i] -= rhs.data[i];
}
}
}
impl<T: Default + Copy> From<DMatrix<T>> for DVector<T> {
fn from(rhs: DMatrix<T>) -> Self {
assert_eq!(rhs.size.1, 1);
DVector {
data: rhs.data[0].clone(),
len: rhs.size.0,
}
}
}
#[derive(Debug, Clone)]
pub struct DMatrix<T> {
pub data: Vec<Vec<T>>,
pub size: (usize, usize),
}
impl<T> DMatrix<T> {
pub fn new(data: Vec<Vec<T>>) -> Self {
let mut size = (0, 0);
size.1 = data.len();
if data.len() != 0 {
size.0 = data.get(0).unwrap().len()
}
Self { data, size }
}
}
impl<T: ToString> DMatrix<T> {
pub fn to_string_vec(&self) -> DMatrix<String> {
let data_str: Vec<Vec<String>> = self
.data
.iter()
.map(|col| col.iter().map(|val| val.to_string()).collect())
.collect();
DMatrix {
data: data_str,
size: self.size,
}
}
}
impl<T: Default> Default for DMatrix<T> {
fn default() -> Self {
Self {
data: Default::default(),
size: Default::default(),
}
}
}
impl<T: Default + Copy> DMatrix<T> {
pub fn default_with_size(size: (usize, usize)) -> Self {
let mut data = vec![vec![T::default(); size.0]; size.1];
Self { data, size }
}
}
impl<T: Scalar + ClosedAdd> Add for DMatrix<T> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
assert_eq!(self.size, rhs.size);
let mut mat = self.clone();
for m in 0..self.size.0 {
for n in 0..self.size.1 {
mat.data[n][m] += rhs.data[n][m];
}
}
mat
}
}
impl<T: Scalar + ClosedAdd> AddAssign for DMatrix<T> {
fn add_assign(&mut self, rhs: Self) {
assert_eq!(self.size, rhs.size);
for m in 0..self.size.0 {
for n in 0..self.size.1 {
self.data[n][m] += rhs.data[n][m];
}
}
}
}
impl<T: Scalar + ClosedSub> Sub for DMatrix<T> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
assert_eq!(self.size, rhs.size);
let mut mat = self.clone();
for m in 0..self.size.0 {
for n in 0..self.size.1 {
mat.data[n][m] -= rhs.data[n][m];
}
}
mat
}
}
impl<T: Scalar + ClosedSub> SubAssign for DMatrix<T> {
fn sub_assign(&mut self, rhs: Self) {
assert_eq!(self.size, rhs.size);
for m in 0..self.size.0 {
for n in 0..self.size.1 {
self.data[n][m] -= rhs.data[n][m];
}
}
}
}
impl<T: Scalar + ClosedAdd + ClosedMul> Mul for DMatrix<T> {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
assert_eq!(self.size.0, rhs.size.1);
let mut mat = Self::default_with_size((rhs.size.1, self.size.0));
for m in 0..self.size.0 {
for p in 0..rhs.size.1 {
for n in 0..self.size.1 {
mat.data[p][m] += self.data[n][m] * rhs.data[p][n];
}
}
}
mat
}
}
impl<T: Scalar + ClosedMul> MulAssign for DMatrix<T> {
fn mul_assign(&mut self, rhs: Self) {
assert_eq!(self.size.0, rhs.size.1);
for m in 0..self.size.0 {
for p in 0..rhs.size.1 {
for n in 0..self.size.1 {
self.data[p][m] *= rhs.data[p][n];
}
}
}
}
}
impl<T: Default + Copy, const M: usize, const N: usize> From<[[T; M]; N]> for DMatrix<T> {
fn from(rhs: [[T; M]; N]) -> Self {
let mut mat = Self::default_with_size((M, N));
for m in 0..M {
for n in 0..N {
mat.data[n][m] = rhs[n][m];
}
}
mat
}
}
impl<T: Default + Copy> From<DVector<T>> for DMatrix<T> {
fn from(rhs: DVector<T>) -> Self {
let len = rhs.len;
DMatrix {
data: vec![rhs.data],
size: (len, 0),
}
}
}
impl<T: Scalar + ClosedAdd + ClosedMul> Mul<DVector<T>> for DMatrix<T> {
type Output = DVector<T>;
fn mul(self, rhs: DVector<T>) -> Self::Output {
DVector::from(self * DMatrix::from(rhs))
}
}
impl<T: Scalar + ClosedMul> Mul<T> for DMatrix<T> {
type Output = Self;
fn mul(self, rhs: T) -> Self::Output {
let mut mat = self.clone();
for m in 0..self.size.0 {
for n in 0..self.size.1 {
mat.data[m][n] *= rhs
}
}
self
}
}
impl<T: Scalar + ClosedMul> MulAssign<T> for DMatrix<T> {
fn mul_assign(&mut self, rhs: T) {
for m in 0..self.size.0 {
for n in 0..self.size.1 {
self.data[m][n] *= rhs
}
}
}
}
impl<T: Scalar + ClosedDiv> Div<T> for DMatrix<T> {
type Output = Self;
fn div(self, rhs: T) -> Self::Output {
let mut mat = self.clone();
for m in 0..self.size.0 {
for n in 0..self.size.1 {
mat.data[m][n] /= rhs
}
}
self
}
}
impl<T: Scalar + ClosedDiv> DivAssign<T> for DMatrix<T> {
fn div_assign(&mut self, rhs: T) {
for m in 0..self.size.0 {
for n in 0..self.size.1 {
self.data[m][n] /= rhs
}
}
}
}
impl<T: Display + Copy> Display for DMatrix<T> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut string = String::new();
let biggest = format!("{}", self.data.get(1).unwrap().get(1).unwrap()).len();
for m in 0..self.size.0 {
string.push_str("|");
for n in 0..self.size.1 {
if n == self.size.1 - 1 {
&string.push_str(&format!("{}", self.data.get(n).unwrap().get(m).unwrap()));
break;
}
let current = format!("{}", self.data.get(n).unwrap().get(m).unwrap()).len();
string.push_str(&format!("{} ", self.data.get(n).unwrap().get(m).unwrap()));
for _ in current..biggest + 1 {
string.push(' ');
}
}
&string.push_str("|\n");
}
write!(f, "{}", string)
}
}
impl<T: FromStr + Default> From<&str> for DVector<T> {
fn from(rhs: &str) -> Self {
let data = rhs
.split(" ")
.map(|val| val.parse::<T>().unwrap_or_else(|t| <T>::default()))
.collect::<Vec<T>>();
let len = data.len();
Self { data, len }
}
}
impl<T: FromStr + Default> From<String> for DVector<T> {
fn from(rhs: String) -> Self {
let data = rhs
.split(" ")
.map(|val| val.parse::<T>().unwrap_or_else(|t| <T>::default()))
.collect::<Vec<T>>();
let len = data.len();
Self { data, len }
}
}
impl<T: FromStr + Default> From<String> for DMatrix<T> {
fn from(rhs: String) -> Self {
let cols_str = rhs.split(";").collect::<Vec<&str>>();
let cols_t = cols_str
.iter()
.map(|str| {
str.split(" ")
.map(|val| val.parse::<T>().unwrap_or_else(|t| <T>::default()))
.collect::<Vec<T>>()
})
.collect::<Vec<Vec<T>>>();
let size = (cols_t[0].len(), cols_t.len());
Self { data: cols_t, size }
}
}
impl<T: FromStr + Default> From<&str> for DMatrix<T> {
fn from(rhs: &str) -> Self {
let cols_t = rhs
.split(";")
.into_iter()
.map(|str| {
str.split(" ")
.map(|val| val.parse::<T>().unwrap_or_else(|t| <T>::default()))
.collect::<Vec<T>>()
})
.collect::<Vec<Vec<T>>>();
let size = (cols_t[0].len(), cols_t.len());
Self { data: cols_t, size }
}
}
#[cfg(test)]
mod dynamic_mat_tests {
use crate::algebra::linear::dynamic::DMatrix;
use crate::algebra::linear::dynamic::DVector;
#[test]
fn add() {
let mat1 = DMatrix::new(vec![vec![0.1, 3.0], vec![2.1, 4.0]]);
let mat2 = DMatrix::new(vec![vec![0.4, 1.0], vec![5.0, -6.0]]);
let mat3 = mat1 + mat2;
}
#[test]
fn add_assign() {
let mut mat1 = DMatrix::new(vec![vec![0.1, 3.0], vec![2.1, 4.0]]);
let mat2 = DMatrix::new(vec![vec![0.4, 1.0], vec![5.0, -6.0]]);
mat1 += mat2;
}
#[test]
fn mul() {
let mat1 = DMatrix::new(vec![vec![1.0, 4.0], vec![2.0, 5.0], vec![3.0, 6.0]]);
let mat2 = DMatrix::new(vec![vec![7.0, 9.0, 11.0], vec![8.0, 10.0, 12.0]]);
let mat3 = mat1 * mat2;
}
#[test]
fn from_arr() {
let mat2 = DMatrix::from([[7.0, 9.0, 11.0], [8.0, 10.0, 12.0]]);
}
#[test]
fn from_str() {
let mat1 = DMatrix::<f64>::from("4 3 2;2 2 -1");
let mat2 = DMatrix::<f64>::from("-2.5 3 2;-2 2.5 3");
let mat = mat1 + mat2;
let vec1 = DVector::<f64>::from("4 3 2");
let vec2 = DVector::<f64>::from("-2.5 3 2");
let vec = vec1 + vec2;
}
}
|
import std::str;
import std::ivec;
import std::option;
import option::some;
import option::none;
import std::map::hashmap;
import lib::llvm::llvm;
import lib::llvm::llvm::ValueRef;
import lib::llvm::llvm::TypeRef;
import lib::llvm::llvm::BasicBlockRef;
import trans::new_sub_block_ctxt;
import trans::new_scope_block_ctxt;
import trans::load_if_immediate;
import ty::pat_ty;
import syntax::ast;
import syntax::ast::def_id;
import syntax::codemap::span;
import util::common::lit_eq;
import trans_common::*;
// An option identifying a branch (either a literal or a tag variant)
tag opt {
lit(@ast::lit);
var(/* variant id */uint, /* variant dids */{tg: def_id, var: def_id});
}
fn opt_eq(a: &opt, b: &opt) -> bool {
alt a {
lit(la) {
ret alt b { lit(lb) { lit_eq(la, lb) } var(_, _) { false } };
}
var(ida, _) {
ret alt b { lit(_) { false } var(idb, _) { ida == idb } };
}
}
}
fn trans_opt(bcx: &@block_ctxt, o: &opt) -> result {
alt o {
lit(l) { ret trans::trans_lit(bcx, *l); }
var(id, _) { ret rslt(bcx, C_int(id as int)); }
}
}
fn variant_opt(ccx: &@crate_ctxt, pat_id: ast::node_id) -> opt {
let vdef = ast::variant_def_ids(ccx.tcx.def_map.get(pat_id));
let variants = ty::tag_variants(ccx.tcx, vdef.tg);
let i = 0u;
for v: ty::variant_info in variants {
if vdef.var == v.id { ret var(i, vdef); }
i += 1u;
}
fail;
}
type bind_map = {ident: ast::ident, val: ValueRef}[];
type match_branch =
@{pats: (@ast::pat)[], body: BasicBlockRef, mutable bound: bind_map};
type match = match_branch[];
fn matches_always(p: &@ast::pat) -> bool {
ret alt p.node {
ast::pat_wild. { true }
ast::pat_bind(_) { true }
ast::pat_rec(_, _) { true }
_ { false }
};
}
fn bind_for_pat(p: &@ast::pat, br: &match_branch, val: ValueRef) {
alt p.node {
ast::pat_bind(name) { br.bound += ~[{ident: name, val: val}]; }
_ { }
}
}
type enter_pat = fn(&@ast::pat) -> option::t[(@ast::pat)[]] ;
fn enter_match(m: &match, col: uint, val: ValueRef, e: &enter_pat) -> match {
let result = ~[];
for br: match_branch in m {
alt e(br.pats.(col)) {
some(sub) {
let pats =
ivec::slice(br.pats, 0u, col) + sub +
ivec::slice(br.pats, col + 1u, ivec::len(br.pats));
let new_br = @{pats: pats with *br};
result += ~[new_br];
bind_for_pat(br.pats.(col), new_br, val);
}
none. { }
}
}
ret result;
}
fn enter_default(m: &match, col: uint, val: ValueRef) -> match {
fn e(p: &@ast::pat) -> option::t[(@ast::pat)[]] {
ret if matches_always(p) { some(~[]) } else { none };
}
ret enter_match(m, col, val, e);
}
fn enter_opt(ccx: &@crate_ctxt, m: &match, opt: &opt, col: uint,
tag_size: uint, val: ValueRef) -> match {
let dummy = @{id: 0, node: ast::pat_wild, span: {lo: 0u, hi: 0u}};
fn e(ccx: &@crate_ctxt, dummy: &@ast::pat, opt: &opt, size: uint,
p: &@ast::pat) -> option::t[(@ast::pat)[]] {
alt p.node {
ast::pat_tag(ctor, subpats) {
ret if opt_eq(variant_opt(ccx, p.id), opt) {
some(subpats)
} else { none };
}
ast::pat_lit(l) {
ret if opt_eq(lit(l), opt) { some(~[]) } else { none };
}
_ { ret some(ivec::init_elt(dummy, size)); }
}
}
ret enter_match(m, col, val, bind e(ccx, dummy, opt, tag_size, _));
}
fn enter_rec(m: &match, col: uint, fields: &ast::ident[], val: ValueRef) ->
match {
let dummy = @{id: 0, node: ast::pat_wild, span: {lo: 0u, hi: 0u}};
fn e(dummy: &@ast::pat, fields: &ast::ident[], p: &@ast::pat) ->
option::t[(@ast::pat)[]] {
alt p.node {
ast::pat_rec(fpats, _) {
let pats = ~[];
for fname: ast::ident in fields {
let pat = dummy;
for fpat: ast::field_pat in fpats {
if str::eq(fpat.ident, fname) { pat = fpat.pat; break; }
}
pats += ~[pat];
}
ret some(pats);
}
_ { ret some(ivec::init_elt(dummy, ivec::len(fields))); }
}
}
ret enter_match(m, col, val, bind e(dummy, fields, _));
}
fn enter_box(m: &match, col: uint, val: ValueRef) -> match {
let dummy = @{id: 0, node: ast::pat_wild, span: {lo: 0u, hi: 0u}};
fn e(dummy: &@ast::pat, p: &@ast::pat) -> option::t[(@ast::pat)[]] {
alt p.node {
ast::pat_box(sub) { ret some(~[sub]); }
_ { ret some(~[dummy]); }
}
}
ret enter_match(m, col, val, bind e(dummy, _));
}
fn get_options(ccx: &@crate_ctxt, m: &match, col: uint) -> opt[] {
fn add_to_set(set: &mutable opt[], val: &opt) {
for l: opt in set { if opt_eq(l, val) { ret; } }
set += ~[val];
}
let found = ~[];
for br: match_branch in m {
alt br.pats.(col).node {
ast::pat_lit(l) { add_to_set(found, lit(l)); }
ast::pat_tag(_, _) {
add_to_set(found, variant_opt(ccx, br.pats.(col).id));
}
_ { }
}
}
ret found;
}
fn extract_variant_args(bcx: @block_ctxt, pat_id: ast::node_id,
vdefs: &{tg: def_id, var: def_id}, val: ValueRef)
-> {vals: ValueRef[], bcx: @block_ctxt} {
let ccx = bcx.fcx.lcx.ccx;
let ty_param_substs = ty::node_id_to_type_params(ccx.tcx, pat_id);
let blobptr = val;
let variants = ty::tag_variants(ccx.tcx, vdefs.tg);
let args = ~[];
let size =
ivec::len(ty::tag_variant_with_id(ccx.tcx, vdefs.tg, vdefs.var).args);
if size > 0u && ivec::len(variants) != 1u {
let tagptr =
bcx.build.PointerCast(val,
trans_common::T_opaque_tag_ptr(ccx.tn));
blobptr = bcx.build.GEP(tagptr, ~[C_int(0), C_int(1)]);
}
let i = 0u;
while i < size {
let r =
trans::GEP_tag(bcx, blobptr, vdefs.tg, vdefs.var, ty_param_substs,
i as int);
bcx = r.bcx;
args += ~[r.val];
i += 1u;
}
ret {vals: args, bcx: bcx};
}
fn collect_record_fields(m: &match, col: uint) -> ast::ident[] {
let fields = ~[];
for br: match_branch in m {
alt br.pats.(col).node {
ast::pat_rec(fs, _) {
for f: ast::field_pat in fs {
if !ivec::any(bind str::eq(f.ident, _), fields) {
fields += ~[f.ident];
}
}
}
_ { }
}
}
ret fields;
}
fn any_box_pat(m: &match, col: uint) -> bool {
for br: match_branch in m {
alt br.pats.(col).node { ast::pat_box(_) { ret true; } _ { } }
}
ret false;
}
type exit_node = {bound: bind_map, from: BasicBlockRef, to: BasicBlockRef};
type mk_fail = fn() -> BasicBlockRef;
fn pick_col(m: &match) -> uint {
let scores = ivec::init_elt_mut(0u, ivec::len(m.(0).pats));
for br: match_branch in m {
let i = 0u;
for p: @ast::pat in br.pats {
alt p.node {
ast::pat_lit(_) | ast::pat_tag(_, _) { scores.(i) += 1u; }
_ {}
}
i += 1u;
}
}
let max_score = 0u;
let best_col = 0u;
let i = 0u;
for score: uint in scores {
// Irrefutable columns always go first, they'd only be duplicated in
// the branches.
if score == 0u { ret i; }
// If no irrefutable ones are found, we pick the one with the biggest
// branching factor.
if score > max_score {
max_score = score;
best_col = i;
}
i += 1u;
}
ret best_col;
}
fn compile_submatch(bcx: @block_ctxt, m: &match, vals: ValueRef[],
f: &mk_fail, exits: &mutable exit_node[]) {
if ivec::len(m) == 0u { bcx.build.Br(f()); ret; }
if ivec::len(m.(0).pats) == 0u {
exits += ~[{bound: m.(0).bound, from: bcx.llbb, to: m.(0).body}];
bcx.build.Br(m.(0).body);
ret;
}
let col = pick_col(m);
let val = vals.(col);
let vals_left = ivec::slice(vals, 0u, col) +
ivec::slice(vals, col + 1u, ivec::len(vals));
let ccx = bcx.fcx.lcx.ccx;
let pat_id = 0;
for br: match_branch in m {
// Find a real id (we're adding placeholder wildcard patterns, but
// each column is guaranteed to have at least one real pattern)
if pat_id == 0 { pat_id = br.pats.(col).id; }
}
let rec_fields = collect_record_fields(m, col);
// Separate path for extracting and binding record fields
if ivec::len(rec_fields) > 0u {
let rec_ty = ty::node_id_to_monotype(ccx.tcx, pat_id);
let fields =
alt ty::struct(ccx.tcx, rec_ty) { ty::ty_rec(fields) { fields } };
let rec_vals = ~[];
for field_name: ast::ident in rec_fields {
let ix: uint =
ty::field_idx(ccx.sess, {lo: 0u, hi: 0u}, field_name, fields);
let r = trans::GEP_tup_like(bcx, rec_ty, val, ~[0, ix as int]);
rec_vals += ~[r.val];
bcx = r.bcx;
}
compile_submatch(bcx, enter_rec(m, col, rec_fields, val),
rec_vals + vals_left, f, exits);
ret;
}
// Unbox in case of a box field
if any_box_pat(m, col) {
let box = bcx.build.Load(val);
let unboxed =
bcx.build.InBoundsGEP(box,
~[C_int(0),
C_int(back::abi::box_rc_field_body)]);
compile_submatch(bcx, enter_box(m, col, val), ~[unboxed] + vals_left,
f, exits);
ret;
}
// Decide what kind of branch we need
let opts = get_options(ccx, m, col);
tag branch_kind { no_branch; single; switch; compare; }
let kind = no_branch;
let test_val = val;
if ivec::len(opts) > 0u {
alt opts.(0) {
var(_, vdef) {
if ivec::len(ty::tag_variants(ccx.tcx, vdef.tg)) == 1u {
kind = single;
} else {
let tagptr = bcx.build.PointerCast
(val, trans_common::T_opaque_tag_ptr(ccx.tn));
let discrimptr = bcx.build.GEP(tagptr, ~[C_int(0), C_int(0)]);
test_val = bcx.build.Load(discrimptr);
kind = switch;
}
}
lit(l) {
test_val = bcx.build.Load(val);
kind = alt l.node { ast::lit_str(_, _) { compare } _ { switch } };
}
}
}
let else_cx =
alt kind {
no_branch. | single. { bcx }
_ { new_sub_block_ctxt(bcx, "match_else") }
};
let sw =
if kind == switch {
bcx.build.Switch(test_val, else_cx.llbb, ivec::len(opts))
} else { C_int(0) }; // Placeholder for when not using a switch
// Compile subtrees for each option
for opt: opt in opts {
let opt_cx = new_sub_block_ctxt(bcx, "match_case");
alt kind {
single. { bcx.build.Br(opt_cx.llbb); }
switch. {
let r = trans_opt(bcx, opt);
bcx = r.bcx;
llvm::LLVMAddCase(sw, r.val, opt_cx.llbb);
}
compare. {
let r = trans_opt(bcx, opt);
bcx = r.bcx;
let t = ty::node_id_to_type(ccx.tcx, pat_id);
let eq = trans::trans_compare(bcx, ast::eq, test_val, t,
r.val, t);
bcx = new_sub_block_ctxt(bcx, "next");
eq.bcx.build.CondBr(eq.val, opt_cx.llbb, bcx.llbb);
}
_ { }
}
let size = 0u;
let unpacked = ~[];
alt opt {
var(_, vdef) {
let args = extract_variant_args(opt_cx, pat_id, vdef, val);
size = ivec::len(args.vals);
unpacked = args.vals;
opt_cx = args.bcx;
}
lit(_) { }
}
compile_submatch(opt_cx, enter_opt(ccx, m, opt, col, size, val),
unpacked + vals_left, f, exits);
}
// Compile the fall-through case
if kind == compare { bcx.build.Br(else_cx.llbb); }
if kind != single {
compile_submatch(else_cx, enter_default(m, col, val), vals_left, f,
exits);
}
}
// Returns false for unreachable blocks
fn make_phi_bindings(bcx: &@block_ctxt, map: &exit_node[],
ids: &ast::pat_id_map) -> bool {
fn assoc(key: str, list: &bind_map) -> option::t[ValueRef] {
for elt: {ident: ast::ident, val: ValueRef} in list {
if str::eq(elt.ident, key) { ret some(elt.val); }
}
ret none;
}
let our_block = bcx.llbb as uint;
let success = true;
for each item: @{key: ast::ident, val: ast::node_id} in ids.items() {
let llbbs = ~[];
let vals = ~[];
for ex: exit_node in map {
if ex.to as uint == our_block {
alt assoc(item.key, ex.bound) {
some(val) { llbbs += ~[ex.from]; vals += ~[val]; }
none. { }
}
}
}
if ivec::len(vals) > 0u {
let phi = bcx.build.Phi(val_ty(vals.(0)), vals, llbbs);
bcx.fcx.lllocals.insert(item.val, phi);
} else { success = false; }
}
ret success;
}
fn trans_alt(cx: &@block_ctxt, expr: &@ast::expr, arms: &ast::arm[],
id: ast::node_id, output: &trans::out_method) -> result {
let bodies = ~[];
let match: match = ~[];
let er = trans::trans_expr(cx, expr);
if (ty::type_is_bot(bcx_tcx(cx), ty::expr_ty(bcx_tcx(cx), expr))) {
// No need to generate code for alt,
// since the disc diverges.
if (!cx.build.is_terminated()) {
ret rslt(cx, cx.build.Unreachable());
}
else {
ret rslt(cx, C_nil());
}
}
for a: ast::arm in arms {
let body = new_scope_block_ctxt(cx, "case_body");
bodies += ~[body];
for p: @ast::pat in a.pats {
match += ~[@{pats: ~[p], body: body.llbb, mutable bound: ~[]}];
}
}
// Cached fail-on-fallthrough block
let fail_cx = @mutable none;
fn mk_fail(cx: &@block_ctxt, sp: &span,
done: @mutable option::t[BasicBlockRef]) -> BasicBlockRef {
alt *done { some(bb) { ret bb; } _ { } }
let fail_cx = new_sub_block_ctxt(cx, "case_fallthrough");
trans::trans_fail(fail_cx, some(sp), "non-exhaustive match failure");
*done = some(fail_cx.llbb);
ret fail_cx.llbb;
}
let exit_map = ~[];
let t = trans::node_id_type(cx.fcx.lcx.ccx, expr.id);
let v = trans::spill_if_immediate(er.bcx, er.val, t);
compile_submatch(er.bcx, match, ~[v],
bind mk_fail(cx, expr.span, fail_cx), exit_map);
let i = 0u;
let arm_results = ~[];
for a: ast::arm in arms {
let body_cx = bodies.(i);
if make_phi_bindings(body_cx, exit_map, ast::pat_id_map(a.pats.(0))) {
let block_res = trans::trans_block(body_cx, a.block, output);
arm_results += ~[block_res];
} else { // Unreachable
arm_results += ~[rslt(body_cx, C_nil())];
}
i += 1u;
}
ret rslt(trans::join_branches(cx, arm_results), C_nil());
}
// Not alt-related, but similar to the pattern-munging code above
fn bind_irrefutable_pat(bcx: @block_ctxt, pat: &@ast::pat, val: ValueRef,
table: hashmap[ast::node_id, ValueRef], copy: bool)
-> @block_ctxt {
let ccx = bcx.fcx.lcx.ccx;
alt pat.node {
ast::pat_bind(_) {
if copy {
let ty = ty::node_id_to_monotype(ccx.tcx, pat.id);
let llty = trans::type_of(ccx, pat.span, ty);
let alloc = trans::alloca(bcx, llty);
bcx = trans::memmove_ty(bcx, alloc, val, ty).bcx;
let loaded = trans::load_if_immediate(bcx, alloc, ty);
bcx = trans::copy_ty(bcx, loaded, ty).bcx;
table.insert(pat.id, alloc);
trans_common::add_clean(bcx, alloc, ty);
} else {
table.insert(pat.id, val);
}
}
ast::pat_tag(_, sub) {
if ivec::len(sub) == 0u { ret bcx; }
let vdefs = ast::variant_def_ids(ccx.tcx.def_map.get(pat.id));
let args = extract_variant_args(bcx, pat.id, vdefs, val);
let i = 0;
for argval: ValueRef in args.vals {
bcx = bind_irrefutable_pat(bcx, sub.(i), argval, table, copy);
i += 1;
}
}
ast::pat_rec(fields, _) {
let rec_ty = ty::node_id_to_monotype(ccx.tcx, pat.id);
let rec_fields =
alt ty::struct(ccx.tcx, rec_ty) { ty::ty_rec(fields) { fields } };
for f: ast::field_pat in fields {
let ix: uint =
ty::field_idx(ccx.sess, pat.span, f.ident, rec_fields);
let r = trans::GEP_tup_like(bcx, rec_ty, val, ~[0, ix as int]);
bcx = bind_irrefutable_pat(r.bcx, f.pat, r.val, table, copy);
}
}
ast::pat_box(inner) {
let box = bcx.build.Load(val);
let unboxed = bcx.build.InBoundsGEP
(box, ~[C_int(0), C_int(back::abi::box_rc_field_body)]);
bcx = bind_irrefutable_pat(bcx, inner, unboxed, table, true);
}
ast::pat_wild. | ast::pat_lit(_) {}
}
ret bcx;
}
// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
|
#[path = "float_to_binary_2/with_float.rs"]
pub mod with_float;
// `without_float_errors_badarg` in unit tests
|
use crate::dynamics::{acceleration::Acceleration, velocity::Velocity};
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Circle {
x: f64,
y: f64,
radius: f64,
angle: f64,
velocity: Velocity,
acceleration: Acceleration,
}
impl Circle {
pub fn new(
x: f64,
y: f64,
radius: f64,
angle: Option<f64>,
velocity: Velocity,
acceleration: Acceleration,
) -> Circle {
let angle_or_default: f64 = match angle {
None => 0.0,
Some(angle) => angle,
};
Circle {
x,
y,
radius,
angle: angle_or_default,
velocity,
acceleration,
}
}
pub fn get_position(&self) -> (f64, f64) {
(self.x, self.y)
}
pub fn get_radius(&self) -> f64 {
self.radius
}
pub fn get_area(&self) -> f64 {
let base = self.radius;
std::f64::consts::PI * base.powi(2)
}
pub fn get_angle(&self) -> f64 {
self.angle
}
pub fn get_velocity(&self) -> Velocity {
self.velocity
}
pub fn get_acceleration(&self) -> Acceleration {
self.acceleration
}
}
#[cfg(test)]
mod tests {
use super::{Acceleration, Velocity};
#[test]
fn it_circle() {
use crate::shapes::circle::Circle;
let velocity = Velocity::new(5.0, 5.0, 0.0);
let acceleration = Acceleration::new(0.0, 0.0, 0.0);
let my_circle = Circle::new(10.0, 20.0, 5.9, None, velocity, acceleration);
let radius: f64 = 5.9;
assert_eq!(my_circle.get_position(), (10.0, 20.0));
assert_eq!(my_circle.get_radius(), 5.9);
assert_eq!(my_circle.get_area(), std::f64::consts::PI * radius.powi(2));
assert_eq!(my_circle.get_angle(), 0.0);
}
}
|
use super::helpers::{reverse_add_assign, reverse_add_c_long, reverse_add_c_long_assign};
use crate::integer::Integer;
use core::ops::Add;
// Add The addition operator +.
// ['Integer', 'Integer', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref']]
impl Add<Integer> for Integer {
type Output = Integer;
fn add(mut self, rhs: Integer) -> Self::Output {
Integer::add_assign(&mut self, &rhs);
self
}
}
// ['Integer', '&Integer', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// []]
impl Add<&Integer> for Integer {
type Output = Integer;
fn add(mut self, rhs: &Integer) -> Self::Output {
Integer::add_assign(&mut self, rhs);
self
}
}
// ['&Integer', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', [],
// ['ref_mut']]
impl Add<Integer> for &Integer {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['&Integer', '&Integer', 'Integer', 'Integer::add', 'no', [], []]
impl Add<&Integer> for &Integer {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
Integer::add(self, rhs)
}
}
// ['Integer', 'i8', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
impl Add<i8> for Integer {
type Output = Integer;
fn add(mut self, rhs: i8) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&i8', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
impl Add<&i8> for Integer {
type Output = Integer;
fn add(mut self, rhs: &i8) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'i8', 'Integer', 'Integer::add_c_long', 'no', [], []]
impl Add<i8> for &Integer {
type Output = Integer;
fn add(self, rhs: i8) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&i8', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
impl Add<&i8> for &Integer {
type Output = Integer;
fn add(self, rhs: &i8) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['i8', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
impl Add<Integer> for i8 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['i8', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
impl Add<&Integer> for i8 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&i8', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
impl Add<Integer> for &i8 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&i8', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
impl Add<&Integer> for &i8 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'u8', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
impl Add<u8> for Integer {
type Output = Integer;
fn add(mut self, rhs: u8) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&u8', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
impl Add<&u8> for Integer {
type Output = Integer;
fn add(mut self, rhs: &u8) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'u8', 'Integer', 'Integer::add_c_long', 'no', [], []]
impl Add<u8> for &Integer {
type Output = Integer;
fn add(self, rhs: u8) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&u8', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
impl Add<&u8> for &Integer {
type Output = Integer;
fn add(self, rhs: &u8) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['u8', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
impl Add<Integer> for u8 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['u8', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
impl Add<&Integer> for u8 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&u8', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
impl Add<Integer> for &u8 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&u8', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
impl Add<&Integer> for &u8 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'i16', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
impl Add<i16> for Integer {
type Output = Integer;
fn add(mut self, rhs: i16) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&i16', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
impl Add<&i16> for Integer {
type Output = Integer;
fn add(mut self, rhs: &i16) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'i16', 'Integer', 'Integer::add_c_long', 'no', [], []]
impl Add<i16> for &Integer {
type Output = Integer;
fn add(self, rhs: i16) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&i16', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
impl Add<&i16> for &Integer {
type Output = Integer;
fn add(self, rhs: &i16) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['i16', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
impl Add<Integer> for i16 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['i16', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
impl Add<&Integer> for i16 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&i16', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
impl Add<Integer> for &i16 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&i16', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
impl Add<&Integer> for &i16 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'u16', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
impl Add<u16> for Integer {
type Output = Integer;
fn add(mut self, rhs: u16) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&u16', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
impl Add<&u16> for Integer {
type Output = Integer;
fn add(mut self, rhs: &u16) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'u16', 'Integer', 'Integer::add_c_long', 'no', [], []]
impl Add<u16> for &Integer {
type Output = Integer;
fn add(self, rhs: u16) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&u16', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
impl Add<&u16> for &Integer {
type Output = Integer;
fn add(self, rhs: &u16) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['u16', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
impl Add<Integer> for u16 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['u16', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
impl Add<&Integer> for u16 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&u16', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
impl Add<Integer> for &u16 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&u16', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
impl Add<&Integer> for &u16 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'i32', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
impl Add<i32> for Integer {
type Output = Integer;
fn add(mut self, rhs: i32) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&i32', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
impl Add<&i32> for Integer {
type Output = Integer;
fn add(mut self, rhs: &i32) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'i32', 'Integer', 'Integer::add_c_long', 'no', [], []]
impl Add<i32> for &Integer {
type Output = Integer;
fn add(self, rhs: i32) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&i32', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
impl Add<&i32> for &Integer {
type Output = Integer;
fn add(self, rhs: &i32) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['i32', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
impl Add<Integer> for i32 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['i32', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
impl Add<&Integer> for i32 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&i32', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
impl Add<Integer> for &i32 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&i32', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
impl Add<&Integer> for &i32 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'u32', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<u32> for Integer {
type Output = Integer;
fn add(mut self, rhs: u32) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&u32', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&u32> for Integer {
type Output = Integer;
fn add(mut self, rhs: &u32) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'u32', 'Integer', 'Integer::add_c_long', 'no', [], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<u32> for &Integer {
type Output = Integer;
fn add(self, rhs: u32) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&u32', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&u32> for &Integer {
type Output = Integer;
fn add(self, rhs: &u32) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['u32', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<Integer> for u32 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['u32', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&Integer> for u32 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&u32', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<Integer> for &u32 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&u32', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&Integer> for &u32 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'i64', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<i64> for Integer {
type Output = Integer;
fn add(mut self, rhs: i64) -> Self::Output {
Integer::add_c_long_assign(&mut self, rhs);
self
}
}
// ['Integer', '&i64', 'Integer', 'Integer::add_c_long_assign', 'lhs',
// ['ref_mut'], ['deref']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&i64> for Integer {
type Output = Integer;
fn add(mut self, rhs: &i64) -> Self::Output {
Integer::add_c_long_assign(&mut self, *rhs);
self
}
}
// ['&Integer', 'i64', 'Integer', 'Integer::add_c_long', 'no', [], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<i64> for &Integer {
type Output = Integer;
fn add(self, rhs: i64) -> Self::Output {
Integer::add_c_long(self, rhs)
}
}
// ['&Integer', '&i64', 'Integer', 'Integer::add_c_long', 'no', [], ['deref']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&i64> for &Integer {
type Output = Integer;
fn add(self, rhs: &i64) -> Self::Output {
Integer::add_c_long(self, *rhs)
}
}
// ['i64', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', [],
// ['ref_mut']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<Integer> for i64 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(self, &mut rhs);
rhs
}
}
// ['i64', '&Integer', 'Integer', 'reverse_add_c_long', 'no', [], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&Integer> for i64 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(self, rhs)
}
}
// ['&i64', 'Integer', 'Integer', 'reverse_add_c_long_assign', 'rhs', ['deref'],
// ['ref_mut']]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<Integer> for &i64 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_c_long_assign(*self, &mut rhs);
rhs
}
}
// ['&i64', '&Integer', 'Integer', 'reverse_add_c_long', 'no', ['deref'], []]
#[cfg(all(target_pointer_width = "64", not(windows)))]
impl Add<&Integer> for &i64 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
reverse_add_c_long(*self, rhs)
}
}
// ['Integer', 'u32', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}]]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<u32> for Integer {
type Output = Integer;
fn add(mut self, rhs: u32) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(rhs));
self
}
}
// ['Integer', '&u32', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}, 'deref']]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&u32> for Integer {
type Output = Integer;
fn add(mut self, rhs: &u32) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(*rhs));
self
}
}
// ['&Integer', 'u32', 'Integer', 'let mut rhs =
// Integer::from(rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<u32> for &Integer {
type Output = Integer;
fn add(self, rhs: u32) -> Self::Output {
let mut rhs = Integer::from(rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['&Integer', '&u32', 'Integer', 'let mut rhs =
// Integer::from(*rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&u32> for &Integer {
type Output = Integer;
fn add(self, rhs: &u32) -> Self::Output {
let mut rhs = Integer::from(*rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['u32', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}], ['ref_mut']]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<Integer> for u32 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(self), &mut rhs);
rhs
}
}
// ['u32', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&Integer> for u32 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['&u32', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}, 'deref'], ['ref_mut']]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<Integer> for &u32 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(*self), &mut rhs);
rhs
}
}
// ['&u32', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(*self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&Integer> for &u32 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(*self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['Integer', 'i64', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}]]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<i64> for Integer {
type Output = Integer;
fn add(mut self, rhs: i64) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(rhs));
self
}
}
// ['Integer', '&i64', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}, 'deref']]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&i64> for Integer {
type Output = Integer;
fn add(mut self, rhs: &i64) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(*rhs));
self
}
}
// ['&Integer', 'i64', 'Integer', 'let mut rhs =
// Integer::from(rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<i64> for &Integer {
type Output = Integer;
fn add(self, rhs: i64) -> Self::Output {
let mut rhs = Integer::from(rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['&Integer', '&i64', 'Integer', 'let mut rhs =
// Integer::from(*rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&i64> for &Integer {
type Output = Integer;
fn add(self, rhs: &i64) -> Self::Output {
let mut rhs = Integer::from(*rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['i64', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}], ['ref_mut']]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<Integer> for i64 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(self), &mut rhs);
rhs
}
}
// ['i64', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&Integer> for i64 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['&i64', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}, 'deref'], ['ref_mut']]
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<Integer> for &i64 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(*self), &mut rhs);
rhs
}
}
// ['&i64', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(*self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
#[cfg(not(all(target_pointer_width = "64", not(windows))))]
impl Add<&Integer> for &i64 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(*self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['Integer', 'u64', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}]]
impl Add<u64> for Integer {
type Output = Integer;
fn add(mut self, rhs: u64) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(rhs));
self
}
}
// ['Integer', '&u64', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}, 'deref']]
impl Add<&u64> for Integer {
type Output = Integer;
fn add(mut self, rhs: &u64) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(*rhs));
self
}
}
// ['&Integer', 'u64', 'Integer', 'let mut rhs =
// Integer::from(rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
impl Add<u64> for &Integer {
type Output = Integer;
fn add(self, rhs: u64) -> Self::Output {
let mut rhs = Integer::from(rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['&Integer', '&u64', 'Integer', 'let mut rhs =
// Integer::from(*rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
impl Add<&u64> for &Integer {
type Output = Integer;
fn add(self, rhs: &u64) -> Self::Output {
let mut rhs = Integer::from(*rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['u64', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}], ['ref_mut']]
impl Add<Integer> for u64 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(self), &mut rhs);
rhs
}
}
// ['u64', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
impl Add<&Integer> for u64 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['&u64', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}, 'deref'], ['ref_mut']]
impl Add<Integer> for &u64 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(*self), &mut rhs);
rhs
}
}
// ['&u64', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(*self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
impl Add<&Integer> for &u64 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(*self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['Integer', 'i128', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}]]
impl Add<i128> for Integer {
type Output = Integer;
fn add(mut self, rhs: i128) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(rhs));
self
}
}
// ['Integer', '&i128', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}, 'deref']]
impl Add<&i128> for Integer {
type Output = Integer;
fn add(mut self, rhs: &i128) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(*rhs));
self
}
}
// ['&Integer', 'i128', 'Integer', 'let mut rhs =
// Integer::from(rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
impl Add<i128> for &Integer {
type Output = Integer;
fn add(self, rhs: i128) -> Self::Output {
let mut rhs = Integer::from(rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['&Integer', '&i128', 'Integer', 'let mut rhs =
// Integer::from(*rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
impl Add<&i128> for &Integer {
type Output = Integer;
fn add(self, rhs: &i128) -> Self::Output {
let mut rhs = Integer::from(*rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['i128', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}], ['ref_mut']]
impl Add<Integer> for i128 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(self), &mut rhs);
rhs
}
}
// ['i128', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
impl Add<&Integer> for i128 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['&i128', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}, 'deref'], ['ref_mut']]
impl Add<Integer> for &i128 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(*self), &mut rhs);
rhs
}
}
// ['&i128', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(*self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
impl Add<&Integer> for &i128 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(*self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['Integer', 'u128', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}]]
impl Add<u128> for Integer {
type Output = Integer;
fn add(mut self, rhs: u128) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(rhs));
self
}
}
// ['Integer', '&u128', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'],
// ['ref', {'convert': 'Integer'}, 'deref']]
impl Add<&u128> for Integer {
type Output = Integer;
fn add(mut self, rhs: &u128) -> Self::Output {
Integer::add_assign(&mut self, &Integer::from(*rhs));
self
}
}
// ['&Integer', 'u128', 'Integer', 'let mut rhs =
// Integer::from(rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
impl Add<u128> for &Integer {
type Output = Integer;
fn add(self, rhs: u128) -> Self::Output {
let mut rhs = Integer::from(rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['&Integer', '&u128', 'Integer', 'let mut rhs =
// Integer::from(*rhs);\nreverse_add_assign(self, &mut rhs);\nrhs']
impl Add<&u128> for &Integer {
type Output = Integer;
fn add(self, rhs: &u128) -> Self::Output {
let mut rhs = Integer::from(*rhs);
reverse_add_assign(self, &mut rhs);
rhs
}
}
// ['u128', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}], ['ref_mut']]
impl Add<Integer> for u128 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(self), &mut rhs);
rhs
}
}
// ['u128', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
impl Add<&Integer> for u128 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
// ['&u128', 'Integer', 'Integer', 'reverse_add_assign', 'rhs', ['ref',
// {'convert': 'Integer'}, 'deref'], ['ref_mut']]
impl Add<Integer> for &u128 {
type Output = Integer;
fn add(self, mut rhs: Integer) -> Self::Output {
reverse_add_assign(&Integer::from(*self), &mut rhs);
rhs
}
}
// ['&u128', '&Integer', 'Integer', 'let mut lhs =
// Integer::from(*self);\nInteger::add_assign(&mut lhs, rhs);\nlhs']
impl Add<&Integer> for &u128 {
type Output = Integer;
fn add(self, rhs: &Integer) -> Self::Output {
let mut lhs = Integer::from(*self);
Integer::add_assign(&mut lhs, rhs);
lhs
}
}
|
use crate::Result;
use std::{fs::File, io::Read, path::Path};
pub fn create_pipeline(
vert_file: &Path,
frag_file: &Path,
vertex_buffer_descriptor: wgpu::VertexBufferDescriptor,
format: wgpu::TextureFormat,
device: &wgpu::Device,
) -> Result<wgpu::RenderPipeline> {
let mut vs_src = String::new();
File::open(vert_file)?.read_to_string(&mut vs_src)?;
let mut fs_src = String::new();
File::open(frag_file)?.read_to_string(&mut fs_src)?;
let vs_spriv = glsl_to_spirv::compile(&vs_src, glsl_to_spirv::ShaderType::Vertex)?;
let fs_spriv = glsl_to_spirv::compile(&fs_src, glsl_to_spirv::ShaderType::Fragment)?;
let vs_data = wgpu::read_spirv(vs_spriv)?;
let fs_data = wgpu::read_spirv(fs_spriv)?;
let vs_module = device.create_shader_module(&vs_data);
let fs_module = device.create_shader_module(&fs_data);
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &layout,
vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module,
entry_point: "main",
},
fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
module: &fs_module,
entry_point: "main",
}),
rasterization_state: Some(wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Ccw,
cull_mode: wgpu::CullMode::Back,
depth_bias: 0,
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}),
color_states: &[wgpu::ColorStateDescriptor {
format: format,
color_blend: wgpu::BlendDescriptor::REPLACE,
alpha_blend: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWrite::ALL,
}],
vertex_state: wgpu::VertexStateDescriptor {
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[vertex_buffer_descriptor],
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
depth_stencil_state: None,
sample_count: 1,
sample_mask: !0,
alpha_to_coverage_enabled: false,
});
Ok(render_pipeline)
}
|
pub fn solve(input: Vec<&str>) {
part1();
part2();
}
fn part1() {
println!("Not implemented");
}
fn part2() {
println!("Not implemented");
}
|
mod test_utils;
use test_utils::ServerTestingExt;
use tide::{Request, StatusCode};
async fn add_one(req: Request<()>) -> Result<String, tide::Error> {
match req.param::<i64>("num") {
Ok(num) => Ok((num + 1).to_string()),
Err(err) => Err(tide::Error::new(StatusCode::BadRequest, err)),
}
}
async fn add_two(req: Request<()>) -> Result<String, tide::Error> {
let one = req
.param::<i64>("one")
.map_err(|err| tide::Error::new(StatusCode::BadRequest, err))?;
let two = req
.param::<i64>("two")
.map_err(|err| tide::Error::new(StatusCode::BadRequest, err))?;
Ok((one + two).to_string())
}
async fn echo_path(req: Request<()>) -> Result<String, tide::Error> {
match req.param::<String>("path") {
Ok(path) => Ok(path),
Err(err) => Err(tide::Error::new(StatusCode::BadRequest, err)),
}
}
#[async_std::test]
async fn wildcard() {
let mut app = tide::Server::new();
app.at("/add_one/:num").get(add_one);
assert_eq!(app.get_body("/add_one/3").await, "4");
assert_eq!(app.get_body("/add_one/-7").await, "-6");
}
#[async_std::test]
async fn invalid_segment_error() {
let mut app = tide::new();
app.at("/add_one/:num").get(add_one);
assert_eq!(app.get("/add_one/a").await.status(), StatusCode::BadRequest);
}
#[async_std::test]
async fn not_found_error() {
let mut app = tide::new();
app.at("/add_one/:num").get(add_one);
assert_eq!(app.get("/add_one/").await.status(), StatusCode::NotFound);
}
#[async_std::test]
async fn wild_path() {
let mut app = tide::new();
app.at("/echo/*path").get(echo_path);
assert_eq!(app.get_body("/echo/some_path").await, "some_path");
assert_eq!(
app.get_body("/echo/multi/segment/path").await,
"multi/segment/path"
);
assert_eq!(app.get("/echo/").await.status(), StatusCode::NotFound);
}
#[async_std::test]
async fn multi_wildcard() {
let mut app = tide::new();
app.at("/add_two/:one/:two/").get(add_two);
assert_eq!(app.get_body("/add_two/1/2/").await, "3");
assert_eq!(app.get_body("/add_two/-1/2/").await, "1");
assert_eq!(app.get("/add_two/1").await.status(), StatusCode::NotFound);
}
#[async_std::test]
async fn wild_last_segment() {
let mut app = tide::new();
app.at("/echo/:path/*").get(echo_path);
assert_eq!(app.get_body("/echo/one/two").await, "one");
assert_eq!(app.get_body("/echo/one/two/three/four").await, "one");
}
#[async_std::test]
async fn invalid_wildcard() {
let mut app = tide::new();
app.at("/echo/*path/:one/").get(echo_path);
assert_eq!(
app.get("/echo/one/two").await.status(),
StatusCode::NotFound
);
}
#[async_std::test]
async fn nameless_wildcard() {
let mut app = tide::Server::new();
app.at("/echo/:").get(|_| async { Ok("") });
assert_eq!(
app.get("/echo/one/two").await.status(),
StatusCode::NotFound
);
assert_eq!(app.get("/echo/one").await.status(), StatusCode::Ok);
}
#[async_std::test]
async fn nameless_internal_wildcard() {
let mut app = tide::new();
app.at("/echo/:/:path").get(echo_path);
assert_eq!(app.get("/echo/one").await.status(), StatusCode::NotFound);
assert_eq!(app.get_body("/echo/one/two").await, "two");
}
#[async_std::test]
async fn nameless_internal_wildcard2() {
let mut app = tide::new();
app.at("/echo/:/:path").get(|req: Request<()>| async move {
assert_eq!(req.param::<String>("path")?, "two");
Ok("")
});
app.get("/echo/one/two").await;
}
#[async_std::test]
async fn ambiguous_router_wildcard_vs_star() {
let mut app = tide::new();
app.at("/:one/:two").get(|_| async { Ok("one/two") });
app.at("/posts/*").get(|_| async { Ok("posts/*") });
assert_eq!(app.get_body("/posts/10").await, "posts/*");
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {bitfield::bitfield, bitflags::bitflags, failure::Fail};
/// The error types for packet parsing.
#[derive(Fail, Debug, PartialEq)]
pub enum Error {
/// The value that was sent was out of range.
#[fail(display = "Value was out of range.")]
OutOfRange,
/// The value that was provided is invalid.
#[fail(display = "Invalid value.")]
InvalidValue,
#[doc(hidden)]
#[fail(display = "__Nonexhaustive error should never be created.")]
__Nonexhaustive,
}
bitflags! {
/// Sampling Frequency field for SBC (Octet 0; b4-7).
/// 44100Hz and 48000Hz are mandatory for A2DP sink.
/// A2DP source must support at least one of 44100Hz and 48000Hz.
/// A2DP Sec. 4.3.2.1
pub struct SbcSamplingFrequency:u8 {
const FREQ16000HZ = 0b1000;
const FREQ32000HZ = 0b0100;
const FREQ44100HZ = 0b0010;
const FREQ48000HZ = 0b0001;
const MANDATORY_SNK = Self::FREQ44100HZ.bits | Self::FREQ48000HZ.bits;
}
}
bitflags! {
/// Channel Mode field for SBC (Octet 0; b0-3).
/// Support for all modes is mandatory in A2DP sink.
/// Mono and at least one of Dual Channel, Stereo, and Joint Stereo must be
/// supported by A2DP source.
/// A2DP Sec. 4.3.2.2
pub struct SbcChannelMode:u8 {
const MONO = 0b1000;
const DUAL_CHANNEL = 0b0100;
const STEREO = 0b0010;
const JOINT_STEREO = 0b0001;
const MANDATORY_SNK = Self::MONO.bits
| Self::DUAL_CHANNEL.bits
| Self::STEREO.bits
| Self::JOINT_STEREO.bits;
}
}
bitflags! {
/// The Block Length field for SBC (Octet 1; b4-7).
/// Support for all block lengths is mandatory in both A2DP Sink and Source.
/// A2DP Sec. 4.3.2.3
pub struct SbcBlockCount:u8 {
const FOUR = 0b1000;
const EIGHT = 0b0100;
const TWELVE = 0b0010;
const SIXTEEN = 0b0001;
const MANDATORY_SNK = Self::FOUR.bits
| Self::EIGHT.bits
| Self::TWELVE.bits
| Self::SIXTEEN.bits;
const MANDATORY_SRC = Self::FOUR.bits
| Self::EIGHT.bits
| Self::TWELVE.bits
| Self::SIXTEEN.bits;
}
}
bitflags! {
/// The Number of Subbands field for SBC (Octet 1; b2-3).
/// Support for both 4 and 8 subbands is mandatory in A2DP Sink.
/// Support for only 8 subbands is mandatory in A2DP Source.
/// 4 subbands is optional.
/// A2DP Sec. 4.3.2.4
pub struct SbcSubBands:u8 {
const FOUR = 0b0010;
const EIGHT = 0b0001;
const MANDATORY_SNK = Self::FOUR.bits | Self::EIGHT.bits;
const MANDATORY_SRC = Self::EIGHT.bits;
}
}
bitflags! {
/// Allocation Method field for SBC (Octet 1; b0-1).
/// Support for both SNR and Loudness is mandatory in A2DP Sink.
/// Support for at least Loudness is mandatory in A2DP Source. SNR is optional.
/// A2DP Sec. 4.3.2.5
pub struct SbcAllocation:u8 {
const SNR = 0b0010;
const LOUDNESS = 0b0001;
const MANDATORY_SNK = Self::SNR.bits | Self::LOUDNESS.bits;
const MANDATORY_SRC = Self::LOUDNESS.bits;
}
}
bitfield! {
/// SBC Codec Specific Information Elements (A2DP Sec. 4.3.2).
/// Packet structure:
/// Octet0: Sampling Frequency (b4-7), Channel Mode (b0-3)
/// Octet1: Block Length (b4-7), Subbands (b2-3), Allocation Method (b0-1)
/// Octet2: Minimum Bitpool Value [2,250]
/// Octet3: Maximum Bitpool Value [2,250]
/// Some fields are mandatory choose 1, and therefore do not have a mandatory parameter method.
pub struct SbcCodecInfo(u32);
impl Debug;
u8;
maxbitpoolval, set_maxbpv: 7, 0;
minbitpoolval, set_minbpv: 15, 8;
allocation_method, set_allocation_method: 17,16;
subbands, set_sub_bands: 19, 18;
block_count, set_block_count: 23, 20;
channel_mode, set_channel_mode: 27, 24;
sampling_frequency, set_sampling_frequency: 31, 28;
}
impl SbcCodecInfo {
// Bitpool values can range from [2,250].
pub const BITPOOL_MIN: u8 = 2;
pub const BITPOOL_MAX: u8 = 250;
pub fn new(
sampling_frequency: SbcSamplingFrequency,
channel_mode: SbcChannelMode,
block_count: SbcBlockCount,
sub_bands: SbcSubBands,
allocation: SbcAllocation,
min_bpv: u8,
max_bpv: u8,
) -> Result<Self, Error> {
if min_bpv > max_bpv {
return Err(Error::InvalidValue);
}
if min_bpv < Self::BITPOOL_MIN
|| min_bpv > Self::BITPOOL_MAX
|| max_bpv < Self::BITPOOL_MIN
|| max_bpv > Self::BITPOOL_MAX
{
return Err(Error::OutOfRange);
}
let mut res = SbcCodecInfo(0);
res.set_maxbpv(max_bpv);
res.set_minbpv(min_bpv);
res.set_allocation_method(allocation.bits());
res.set_sub_bands(sub_bands.bits());
res.set_block_count(block_count.bits());
res.set_channel_mode(channel_mode.bits());
res.set_sampling_frequency(sampling_frequency.bits());
Ok(res)
}
pub fn to_bytes(&self) -> Vec<u8> {
self.0.to_be_bytes().to_vec()
}
}
bitflags! {
/// Object Type field for MPEG-2,4 AAC (Octet 0; b0-7).
/// Support for MPEG-2 AAC LC is mandatory in both A2DP Sink and Source.
/// Bits 0 to 4 are RFA.
/// A2DP Sec. 4.5.2.1
pub struct AACObjectType:u8 {
const MPEG2_AAC_LC = 0b10000000;
const MPEG4_AAC_LC = 0b01000000;
const MPEG4_AAC_LTP = 0b00100000;
const MPEG4_AAC_SCALABLE = 0b00010000;
const MANDATORY_SNK = Self::MPEG2_AAC_LC.bits;
const MANDATORY_SRC = Self::MPEG2_AAC_LC.bits;
}
}
bitflags! {
/// Sampling Frequency field for MPEG-2,4 AAC (Octet 1; b0-7, Octet 2; b4-7)
/// Support for 44.1KHz & 48.0KHz is mandatory in A2DP Sink.
/// Support for either 44.1KHz or 48.0KHz is mandatory in A2DP Source.
/// A2DP Sec. 4.5.2.2
pub struct AACSamplingFrequency:u16 {
const FREQ8000HZ = 0b100000000000;
const FREQ11025HZ = 0b010000000000;
const FREQ12000HZ = 0b001000000000;
const FREQ16000HZ = 0b000100000000;
const FREQ22050HZ = 0b000010000000;
const FREQ24000HZ = 0b000001000000;
const FREQ32000HZ = 0b000000100000;
const FREQ44100HZ = 0b000000010000;
const FREQ48000HZ = 0b000000001000;
const FREQ64000HZ = 0b000000000100;
const FREQ88200HZ = 0b000000000010;
const FREQ96000HZ = 0b000000000001;
const MANDATORY_SNK = Self::FREQ44100HZ.bits | Self::FREQ48000HZ.bits;
}
}
bitflags! {
/// Channels field for MPEG-2,4 AAC (Octet 2; b2-3).
/// Support for both 1 and 2 channels is mandatory in A2DP Sink.
/// Support for either 1 or 2 channels is mandatory in A2DP Source.
/// A2DP Sec 4.5.2.3
pub struct AACChannels:u8 {
const ONE = 0b10;
const TWO = 0b01;
const MANDATORY_SNK = Self::ONE.bits | Self::TWO.bits;
}
}
bitflags! {
/// Support of Variable Bit Rate (VBR) field for MPEG-2,4 AAC (Octet 3; b7).
/// Support for VBR is mandatory in A2DP Sink.
/// A2DP Sec 4.5.2.5
pub struct AACVariableBitRate: u8 {
const VBR_SUPPORTED = 0b1;
const MANDATORY_SNK = Self::VBR_SUPPORTED.bits;
}
}
bitfield! {
/// MPEG-2 AAC Codec Specific Information Elements (A2DP Sec 4.5.2)
/// Structure:
/// Octet0: Object Type (b 40-47)
/// Octet1: Sampling Frequency (b 32-39)
/// Octet2: Sampling Frequency (b 28-31), Channels (b 26-27), RFA (b 24-25)
/// Octet3: VBR (b 23), Bit Rate (b 16-22)
/// Octet4: Bit Rate (b 8-15)
/// Octet5: Bit Rate (b 0-7)
/// Some fields are mandatory choose 1, and therefore do not have a mandatory parameter method.
pub struct AACMediaCodecInfo(u64);
impl Debug;
u8;
u32, bitrate, set_bitrate: 22, 0;
vbr, set_vbr: 23, 23;
// Bits 24-25 RFA.
channels, set_channels: 27,26;
u16, sampling_frequency, set_sampling_frequency: 39, 28;
object_type, set_object_type: 47, 40;
// Bits 48-63 Unused.
}
impl AACMediaCodecInfo {
pub fn new(
object_type: AACObjectType,
sampling_frequency: AACSamplingFrequency,
channels: AACChannels,
vbr: AACVariableBitRate,
bitrate: u32,
) -> Result<Self, Error> {
// Bitrate is expressed as a 23bit UiMsbf, stored in a u32.
if bitrate > 0x7fffff {
return Err(Error::OutOfRange);
}
let mut res = AACMediaCodecInfo(0);
res.set_bitrate(bitrate);
res.set_vbr(vbr.bits());
res.set_channels(channels.bits());
res.set_sampling_frequency(sampling_frequency.bits());
res.set_object_type(object_type.bits());
Ok(res)
}
/// `AACMediaCodecInfo` is represented as an u64, with upper 16 bits unused.
/// Return a vector of the lower 6 bytes.
pub fn to_bytes(&self) -> Vec<u8> {
let codec_info = self.0.to_be_bytes();
let mut res = [0u8; 6];
res.copy_from_slice(&codec_info[2..8]);
res.to_vec()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
/// Unit test for the SBC media codec info generation.
fn test_sbc_media_codec_info() {
// Mandatory A2DP Sink support case.
let sbc_media_codec_info: SbcCodecInfo = SbcCodecInfo::new(
SbcSamplingFrequency::MANDATORY_SNK,
SbcChannelMode::MANDATORY_SNK,
SbcBlockCount::MANDATORY_SNK,
SbcSubBands::MANDATORY_SNK,
SbcAllocation::MANDATORY_SNK,
2,
250,
)
.expect("Couldn't create sbc media codec info.");
let res = sbc_media_codec_info.to_bytes();
assert_eq!(vec![0x3F, 0xFF, 2, 250], res);
// Mandatory A2DP source support case. Some fields are choose 1 fields.
let sbc_media_codec_info: SbcCodecInfo = SbcCodecInfo::new(
SbcSamplingFrequency::FREQ44100HZ,
SbcChannelMode::MONO | SbcChannelMode::DUAL_CHANNEL,
SbcBlockCount::MANDATORY_SRC,
SbcSubBands::MANDATORY_SRC,
SbcAllocation::MANDATORY_SRC,
2,
250,
)
.expect("Couldn't create sbc media codec info.");
let res = sbc_media_codec_info.to_bytes();
assert_eq!(vec![0x2C, 0xF5, 2, 250], res);
// No supported codec information
let sbc_codec_info: SbcCodecInfo = SbcCodecInfo::new(
SbcSamplingFrequency::empty(),
SbcChannelMode::empty(),
SbcBlockCount::empty(),
SbcSubBands::empty(),
SbcAllocation::empty(),
2,
250,
)
.expect("Couldn't create sbc media codec info.");
let res = sbc_codec_info.to_bytes();
assert_eq!(vec![0x00, 0x00, 2, 250], res);
// All codec field values are supported
let sbc_codec_info: SbcCodecInfo = SbcCodecInfo::new(
SbcSamplingFrequency::all(),
SbcChannelMode::all(),
SbcBlockCount::all(),
SbcSubBands::all(),
SbcAllocation::all(),
SbcCodecInfo::BITPOOL_MIN, // Smallest bitpool value.
SbcCodecInfo::BITPOOL_MAX, // Largest bitpool value.
)
.expect("Couldn't create sbc media codec info.");
let res = sbc_codec_info.to_bytes();
assert_eq!(vec![0xFF, 0xFF, 2, 250], res);
// Out of range bitpool value
let sbc_codec_info = SbcCodecInfo::new(
SbcSamplingFrequency::all(),
SbcChannelMode::all(),
SbcBlockCount::all(),
SbcSubBands::all(),
SbcAllocation::all(),
20,
252, // Too large.
);
assert!(sbc_codec_info.is_err());
// Out of range bitpool value
let sbc_codec_info = SbcCodecInfo::new(
SbcSamplingFrequency::all(),
SbcChannelMode::all(),
SbcBlockCount::all(),
SbcSubBands::all(),
SbcAllocation::all(),
0, // Too small
240,
);
assert!(sbc_codec_info.is_err());
// Invalid bitpool value
let sbc_codec_info = SbcCodecInfo::new(
SbcSamplingFrequency::all(),
SbcChannelMode::all(),
SbcBlockCount::all(),
SbcSubBands::all(),
SbcAllocation::all(),
100,
50,
);
assert!(sbc_codec_info.is_err());
}
#[test]
fn test_aac_media_codec_info() {
// Empty case.
let aac_media_codec_info: AACMediaCodecInfo = AACMediaCodecInfo::new(
AACObjectType::empty(),
AACSamplingFrequency::empty(),
AACChannels::empty(),
AACVariableBitRate::empty(),
0,
)
.expect("Error creating aac media codec info.");
let res = aac_media_codec_info.to_bytes();
assert_eq!(vec![0, 0, 0, 0, 0, 0], res);
// All codec info supported case.
let aac_media_codec_info: AACMediaCodecInfo = AACMediaCodecInfo::new(
AACObjectType::all(),
AACSamplingFrequency::all(),
AACChannels::all(),
AACVariableBitRate::all(),
8388607, // Largest 23-bit bit rate.
)
.expect("Error creating aac media codec info.");
let res = aac_media_codec_info.to_bytes();
assert_eq!(vec![0xF0, 0xFF, 0xFC, 0xFF, 0xFF, 0xFF], res);
// Only VBR specified.
let aac_media_codec_info: AACMediaCodecInfo = AACMediaCodecInfo::new(
AACObjectType::empty(),
AACSamplingFrequency::empty(),
AACChannels::empty(),
AACVariableBitRate::VBR_SUPPORTED,
0,
)
.expect("Error creating aac media codec info.");
let res = aac_media_codec_info.to_bytes();
assert_eq!(vec![0x00, 0x00, 0x00, 0x80, 0x00, 0x00], res);
// A2DP Sink mandatory fields supported.
let aac_media_codec_info: AACMediaCodecInfo = AACMediaCodecInfo::new(
AACObjectType::MANDATORY_SNK,
AACSamplingFrequency::MANDATORY_SNK,
AACChannels::MANDATORY_SNK,
AACVariableBitRate::MANDATORY_SNK,
0xAAFF, // Arbitrary bit rate.
)
.expect("Error creating aac media codec info.");
let res = aac_media_codec_info.to_bytes();
assert_eq!(vec![0x80, 0x01, 0x8C, 0x80, 0xAA, 0xFF], res);
// A2DP Source mandatory fields supported.
let aac_media_codec_info: AACMediaCodecInfo = AACMediaCodecInfo::new(
AACObjectType::MANDATORY_SRC,
AACSamplingFrequency::FREQ44100HZ,
AACChannels::ONE,
AACVariableBitRate::empty(), // VBR is optional in SRC.
0xAAFF, // Arbitrary
)
.expect("Error creating aac media codec info.");
let res = aac_media_codec_info.to_bytes();
assert_eq!(vec![0x80, 0x01, 0x08, 0x00, 0xAA, 0xFF], res);
// Out of range bit rate.
let aac_media_codec_info = AACMediaCodecInfo::new(
AACObjectType::MANDATORY_SRC,
AACSamplingFrequency::FREQ44100HZ,
AACChannels::ONE,
AACVariableBitRate::empty(),
0xFFFFFF, // Too large
);
assert!(aac_media_codec_info.is_err());
}
}
|
use {
crate::{
descriptor,
escape::{Escape, KeepAlive, Terminal},
},
gfx_hal::Backend,
std::ops::{Deref, DerefMut},
};
/// Descriptor set object wrapper.
#[derive(Debug)]
pub struct DescriptorSet<B: Backend> {
escape: Escape<(descriptor::DescriptorSet<B>, KeepAlive)>,
}
impl<B> DescriptorSet<B>
where
B: Backend,
{
/// Wrap a descriptor set.
///
/// # Safety
///
/// `terminal` will receive descriptor set upon drop, it must free descriptor set properly.
///
pub unsafe fn new(
set: descriptor::DescriptorSet<B>,
layout: &DescriptorSetLayout<B>,
terminal: &Terminal<(descriptor::DescriptorSet<B>, KeepAlive)>,
) -> Self {
DescriptorSet {
escape: terminal.escape((set, layout.keep_alive())),
}
}
/// This will return `None` and would be equivalent to dropping
/// if there are `KeepAlive` created from this `DescriptorSet.
pub fn unescape(self) -> Option<(descriptor::DescriptorSet<B>, KeepAlive)> {
Escape::unescape(self.escape)
}
/// Creates [`KeepAlive`] handler to extend descriptor set lifetime.
///
/// [`KeepAlive`]: struct.KeepAlive.html
pub fn keep_alive(&self) -> KeepAlive {
Escape::keep_alive(&self.escape)
}
/// Get raw descriptor set handle.
///
/// # Safety
///
/// Raw descriptor set handler should not be used to violate this object valid usage.
pub fn raw(&self) -> &B::DescriptorSet {
self.escape.0.raw()
}
}
#[derive(Debug)]
pub struct DescriptorSetLayout<B: Backend> {
escape: Escape<descriptor::DescriptorSetLayout<B>>,
}
impl<B> DescriptorSetLayout<B>
where
B: Backend,
{
/// Wrap a descriptor set layout.
///
/// # Safety
///
/// `terminal` will receive descriptor set layout upon drop, it must free descriptor set layout properly.
///
pub unsafe fn new(
layout: descriptor::DescriptorSetLayout<B>,
terminal: &Terminal<descriptor::DescriptorSetLayout<B>>,
) -> Self {
DescriptorSetLayout {
escape: terminal.escape(layout),
}
}
/// This will return `None` and would be equivalent to dropping
/// if there are `KeepAlive` created from this `DescriptorSetLayout.
pub fn unescape(self) -> Option<descriptor::DescriptorSetLayout<B>> {
Escape::unescape(self.escape)
}
/// Creates [`KeepAlive`] handler to extend descriptor set layout lifetime.
///
/// [`KeepAlive`]: struct.KeepAlive.html
pub fn keep_alive(&self) -> KeepAlive {
Escape::keep_alive(&self.escape)
}
/// Get raw descriptor set layout handle.
///
/// # Safety
///
/// Raw descriptor set layout handler should not be used to violate this object valid usage.
pub fn raw(&self) -> &B::DescriptorSetLayout {
self.escape.raw()
}
}
impl<B: Backend> Deref for DescriptorSetLayout<B> {
type Target = descriptor::DescriptorSetLayout<B>;
fn deref(&self) -> &descriptor::DescriptorSetLayout<B> {
&*self.escape
}
}
impl<B: Backend> DerefMut for DescriptorSetLayout<B> {
fn deref_mut(&mut self) -> &mut descriptor::DescriptorSetLayout<B> {
&mut *self.escape
}
}
|
//! Instruction types
#![allow(dead_code)]
use crate::state::ImpermenantLossStopLossConfig;
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
/// Instructions supported by the program
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, BorshSchema, PartialEq)]
pub enum Instruction {
Initialize {
config: ImpermenantLossStopLossConfig,
},
Configure {
config: ImpermenantLossStopLossConfig,
},
OwnerAddLiquidity {
amount_a: u64,
amount_b: u64,
},
OwnerRemoveLiquidity {
amount_a: u64,
amount_b: u64,
},
AnyoneRemoveLiquidity {
amount_a: u64,
amount_b: u64,
}
}
|
use std::path::Path;
pub mod compiler;
pub mod constants;
pub mod deploy;
pub use deploy::{deploy_contract, make_web3, make_web3_ganache};
pub fn get_artifact(contract_name: &str) -> deploy::ContractArtifact {
deploy::get_artifact(Path::new(constants::BUILD_PATH), contract_name)
}
|
use yew::prelude::*;
pub struct EmailApp {}
pub enum Msg {}
impl Component for EmailApp {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
EmailApp {}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<div class="p-2" style="font-size: 14px;">
<p>{ " Email Applications using this connection." }</p>
<div class="mb-3">
<table class="table">
<tbody>
<tr>
<td>
<p class="fw-bold">{"TelAuth Management API (Test Application)"}</p>
<p>{"Machine to Machine"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="authManageSwitch"/>
</div>
</td>
</tr>
<tr>
<td>
<p class="fw-bold">{"API Explorer Application"}</p>
<p>{"Machine to Machine"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="apiExplorerSwitch"/>
</div>
</td>
</tr>
<tr>
<td>
<p class="fw-bold">{"Placeholder (Test Application)"}</p>
<p>{"Machine to Machine"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="placeholderTestSwitch"/>
</div>
</td>
</tr>
<tr>
<td>
<p class="fw-bold">{"Default App"}</p>
<p>{"Generic"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="defaultAppSwitch"/>
</div>
</td>
</tr>
<tr>
<td>
<p class="fw-bold">{"Native App"}</p>
<p>{"Generic"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="nativeAppSwitch"/>
</div>
</td>
</tr>
<tr>
<td>
<p class="fw-bold">{"RWA"}</p>
<p>{"Regular Web Application"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="regWebAppSwitch"/>
</div>
</td>
</tr>
<tr>
<td>
<p class="fw-bold">{"SPWA"}</p>
<p>{"Generic"}</p>
</td>
<td>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="singPageAppSwitch"/>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">{"Save"}</button>
</div>
</div>
}
}
}
|
#![feature(core_intrinsics)]
#![feature(const_fn)]
use crate::geometry::Vector2;
use crate::geometry::Vector3;
use crate::types::Float;
use crate::types::Int;
use std::f32;
use std::f64;
pub mod bounds;
pub mod bssrdf;
pub mod efloat;
pub mod geometry;
pub mod interaction;
pub mod intersect;
pub mod light;
pub mod lights;
pub mod materials;
pub mod math;
pub mod medium;
pub mod primitive;
pub mod quaternion;
pub mod ray;
pub mod reflection;
pub mod sampler;
pub mod sampling;
pub mod scene;
pub mod shape;
pub mod sphere;
pub mod spectrum;
pub mod texture;
pub mod transform;
pub mod types;
pub type Point2<T> = Vector2<T>;
pub type Normal2<T> = Vector2<T>;
pub type Vector2i = Vector2<Int>;
pub type Vector2f = Vector2<Float>;
pub type Point2i = Vector2i;
pub type Point2f = Vector2f;
pub type Normal2i = Vector2i;
pub type Normal2f = Vector2f;
pub type Point3<T> = Vector3<T>;
pub type Normal3<T> = Vector3<T>;
pub type Vector3i = Vector3<Int>;
pub type Vector3f = Vector3<Float>;
pub type Point3i = Vector3i;
pub type Point3f = Vector3f;
pub type Normal3i = Vector3i;
pub type Normal3f = Vector3f;
static SHADOW_EPSILON: Float = 0.0001;
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtNetwork/qhostaddress.h
// dst-file: /src/network/qhostaddress.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
// use super::qhostaddress::QIPv6Address; // 773
use super::super::core::qstring::QString; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QHostAddress_Class_Size() -> c_int;
// proto: void QHostAddress::QHostAddress(const Q_IPV6ADDR & ip6Addr);
fn _ZN12QHostAddressC2ERK12QIPv6Address(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: Q_IPV6ADDR QHostAddress::toIPv6Address();
fn _ZNK12QHostAddress13toIPv6AddressEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QHostAddress::QHostAddress(const quint8 * ip6Addr);
fn _ZN12QHostAddressC2EPKh(qthis: u64 /* *mut c_void*/, arg0: *mut c_uchar);
// proto: bool QHostAddress::isNull();
fn _ZNK12QHostAddress6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QHostAddress::QHostAddress(const QString & address);
fn _ZN12QHostAddressC2ERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QHostAddress::clear();
fn _ZN12QHostAddress5clearEv(qthis: u64 /* *mut c_void*/);
// proto: void QHostAddress::setAddress(quint8 * ip6Addr);
fn _ZN12QHostAddress10setAddressEPh(qthis: u64 /* *mut c_void*/, arg0: *mut c_uchar);
// proto: void QHostAddress::setAddress(quint32 ip4Addr);
fn _ZN12QHostAddress10setAddressEj(qthis: u64 /* *mut c_void*/, arg0: c_uint);
// proto: void QHostAddress::setAddress(const Q_IPV6ADDR & ip6Addr);
fn _ZN12QHostAddress10setAddressERK12QIPv6Address(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QHostAddress::QHostAddress(quint8 * ip6Addr);
fn _ZN12QHostAddressC2EPh(qthis: u64 /* *mut c_void*/, arg0: *mut c_uchar);
// proto: void QHostAddress::QHostAddress();
fn _ZN12QHostAddressC2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QHostAddress::QHostAddress(quint32 ip4Addr);
fn _ZN12QHostAddressC2Ej(qthis: u64 /* *mut c_void*/, arg0: c_uint);
// proto: void QHostAddress::QHostAddress(const QHostAddress & copy);
fn _ZN12QHostAddressC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QHostAddress::isInSubnet(const QHostAddress & subnet, int netmask);
fn _ZNK12QHostAddress10isInSubnetERKS_i(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int) -> c_char;
// proto: QString QHostAddress::toString();
fn _ZNK12QHostAddress8toStringEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QHostAddress::isLoopback();
fn _ZNK12QHostAddress10isLoopbackEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QString QHostAddress::scopeId();
fn _ZNK12QHostAddress7scopeIdEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QHostAddress::setAddress(const quint8 * ip6Addr);
fn _ZN12QHostAddress10setAddressEPKh(qthis: u64 /* *mut c_void*/, arg0: *mut c_uchar);
// proto: void QHostAddress::setScopeId(const QString & id);
fn _ZN12QHostAddress10setScopeIdERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QHostAddress::~QHostAddress();
fn _ZN12QHostAddressD2Ev(qthis: u64 /* *mut c_void*/);
// proto: quint32 QHostAddress::toIPv4Address(bool * ok);
fn _ZNK12QHostAddress13toIPv4AddressEPb(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_uint;
// proto: static QPair<QHostAddress, int> QHostAddress::parseSubnet(const QString & subnet);
fn _ZN12QHostAddress11parseSubnetERK7QString(arg0: *mut c_void);
// proto: quint32 QHostAddress::toIPv4Address();
fn _ZNK12QHostAddress13toIPv4AddressEv(qthis: u64 /* *mut c_void*/) -> c_uint;
// proto: bool QHostAddress::setAddress(const QString & address);
fn _ZN12QHostAddress10setAddressERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
fn QIPv6Address_Class_Size() -> c_int;
} // <= ext block end
// body block begin =>
// class sizeof(QHostAddress)=1
#[derive(Default)]
pub struct QHostAddress {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QIPv6Address)=16
#[derive(Default)]
pub struct QIPv6Address {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QHostAddress {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QHostAddress {
return QHostAddress{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QHostAddress::QHostAddress(const Q_IPV6ADDR & ip6Addr);
impl /*struct*/ QHostAddress {
pub fn new<T: QHostAddress_new>(value: T) -> QHostAddress {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QHostAddress_new {
fn new(self) -> QHostAddress;
}
// proto: void QHostAddress::QHostAddress(const Q_IPV6ADDR & ip6Addr);
impl<'a> /*trait*/ QHostAddress_new for (&'a QIPv6Address) {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2ERK12QIPv6Address()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QHostAddressC2ERK12QIPv6Address(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: Q_IPV6ADDR QHostAddress::toIPv6Address();
impl /*struct*/ QHostAddress {
pub fn toIPv6Address<RetType, T: QHostAddress_toIPv6Address<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toIPv6Address(self);
// return 1;
}
}
pub trait QHostAddress_toIPv6Address<RetType> {
fn toIPv6Address(self , rsthis: & QHostAddress) -> RetType;
}
// proto: Q_IPV6ADDR QHostAddress::toIPv6Address();
impl<'a> /*trait*/ QHostAddress_toIPv6Address<QIPv6Address> for () {
fn toIPv6Address(self , rsthis: & QHostAddress) -> QIPv6Address {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress13toIPv6AddressEv()};
let mut ret = unsafe {_ZNK12QHostAddress13toIPv6AddressEv(rsthis.qclsinst)};
let mut ret1 = QIPv6Address::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QHostAddress::QHostAddress(const quint8 * ip6Addr);
impl<'a> /*trait*/ QHostAddress_new for (&'a String) {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2EPKh()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.as_ptr() as *mut c_uchar;
unsafe {_ZN12QHostAddressC2EPKh(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QHostAddress::isNull();
impl /*struct*/ QHostAddress {
pub fn isNull<RetType, T: QHostAddress_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QHostAddress_isNull<RetType> {
fn isNull(self , rsthis: & QHostAddress) -> RetType;
}
// proto: bool QHostAddress::isNull();
impl<'a> /*trait*/ QHostAddress_isNull<i8> for () {
fn isNull(self , rsthis: & QHostAddress) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress6isNullEv()};
let mut ret = unsafe {_ZNK12QHostAddress6isNullEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QHostAddress::QHostAddress(const QString & address);
impl<'a> /*trait*/ QHostAddress_new for (&'a QString) {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2ERK7QString()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QHostAddressC2ERK7QString(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QHostAddress::clear();
impl /*struct*/ QHostAddress {
pub fn clear<RetType, T: QHostAddress_clear<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clear(self);
// return 1;
}
}
pub trait QHostAddress_clear<RetType> {
fn clear(self , rsthis: & QHostAddress) -> RetType;
}
// proto: void QHostAddress::clear();
impl<'a> /*trait*/ QHostAddress_clear<()> for () {
fn clear(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress5clearEv()};
unsafe {_ZN12QHostAddress5clearEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QHostAddress::setAddress(quint8 * ip6Addr);
impl /*struct*/ QHostAddress {
pub fn setAddress<RetType, T: QHostAddress_setAddress<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAddress(self);
// return 1;
}
}
pub trait QHostAddress_setAddress<RetType> {
fn setAddress(self , rsthis: & QHostAddress) -> RetType;
}
// proto: void QHostAddress::setAddress(quint8 * ip6Addr);
impl<'a> /*trait*/ QHostAddress_setAddress<()> for (&'a mut String) {
fn setAddress(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress10setAddressEPh()};
let arg0 = self.as_ptr() as *mut c_uchar;
unsafe {_ZN12QHostAddress10setAddressEPh(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QHostAddress::setAddress(quint32 ip4Addr);
impl<'a> /*trait*/ QHostAddress_setAddress<()> for (u32) {
fn setAddress(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress10setAddressEj()};
let arg0 = self as c_uint;
unsafe {_ZN12QHostAddress10setAddressEj(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QHostAddress::setAddress(const Q_IPV6ADDR & ip6Addr);
impl<'a> /*trait*/ QHostAddress_setAddress<()> for (&'a QIPv6Address) {
fn setAddress(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress10setAddressERK12QIPv6Address()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QHostAddress10setAddressERK12QIPv6Address(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QHostAddress::QHostAddress(quint8 * ip6Addr);
impl<'a> /*trait*/ QHostAddress_new for (&'a mut String) {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2EPh()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.as_ptr() as *mut c_uchar;
unsafe {_ZN12QHostAddressC2EPh(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QHostAddress::QHostAddress();
impl<'a> /*trait*/ QHostAddress_new for () {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2Ev()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN12QHostAddressC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QHostAddress::QHostAddress(quint32 ip4Addr);
impl<'a> /*trait*/ QHostAddress_new for (u32) {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2Ej()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self as c_uint;
unsafe {_ZN12QHostAddressC2Ej(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QHostAddress::QHostAddress(const QHostAddress & copy);
impl<'a> /*trait*/ QHostAddress_new for (&'a QHostAddress) {
fn new(self) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressC2ERKS_()};
let ctysz: c_int = unsafe{QHostAddress_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QHostAddressC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QHostAddress{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QHostAddress::isInSubnet(const QHostAddress & subnet, int netmask);
impl /*struct*/ QHostAddress {
pub fn isInSubnet<RetType, T: QHostAddress_isInSubnet<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isInSubnet(self);
// return 1;
}
}
pub trait QHostAddress_isInSubnet<RetType> {
fn isInSubnet(self , rsthis: & QHostAddress) -> RetType;
}
// proto: bool QHostAddress::isInSubnet(const QHostAddress & subnet, int netmask);
impl<'a> /*trait*/ QHostAddress_isInSubnet<i8> for (&'a QHostAddress, i32) {
fn isInSubnet(self , rsthis: & QHostAddress) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress10isInSubnetERKS_i()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let mut ret = unsafe {_ZNK12QHostAddress10isInSubnetERKS_i(rsthis.qclsinst, arg0, arg1)};
return ret as i8;
// return 1;
}
}
// proto: QString QHostAddress::toString();
impl /*struct*/ QHostAddress {
pub fn toString<RetType, T: QHostAddress_toString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toString(self);
// return 1;
}
}
pub trait QHostAddress_toString<RetType> {
fn toString(self , rsthis: & QHostAddress) -> RetType;
}
// proto: QString QHostAddress::toString();
impl<'a> /*trait*/ QHostAddress_toString<QString> for () {
fn toString(self , rsthis: & QHostAddress) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress8toStringEv()};
let mut ret = unsafe {_ZNK12QHostAddress8toStringEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QHostAddress::isLoopback();
impl /*struct*/ QHostAddress {
pub fn isLoopback<RetType, T: QHostAddress_isLoopback<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isLoopback(self);
// return 1;
}
}
pub trait QHostAddress_isLoopback<RetType> {
fn isLoopback(self , rsthis: & QHostAddress) -> RetType;
}
// proto: bool QHostAddress::isLoopback();
impl<'a> /*trait*/ QHostAddress_isLoopback<i8> for () {
fn isLoopback(self , rsthis: & QHostAddress) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress10isLoopbackEv()};
let mut ret = unsafe {_ZNK12QHostAddress10isLoopbackEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QString QHostAddress::scopeId();
impl /*struct*/ QHostAddress {
pub fn scopeId<RetType, T: QHostAddress_scopeId<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scopeId(self);
// return 1;
}
}
pub trait QHostAddress_scopeId<RetType> {
fn scopeId(self , rsthis: & QHostAddress) -> RetType;
}
// proto: QString QHostAddress::scopeId();
impl<'a> /*trait*/ QHostAddress_scopeId<QString> for () {
fn scopeId(self , rsthis: & QHostAddress) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress7scopeIdEv()};
let mut ret = unsafe {_ZNK12QHostAddress7scopeIdEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QHostAddress::setAddress(const quint8 * ip6Addr);
impl<'a> /*trait*/ QHostAddress_setAddress<()> for (&'a String) {
fn setAddress(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress10setAddressEPKh()};
let arg0 = self.as_ptr() as *mut c_uchar;
unsafe {_ZN12QHostAddress10setAddressEPKh(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QHostAddress::setScopeId(const QString & id);
impl /*struct*/ QHostAddress {
pub fn setScopeId<RetType, T: QHostAddress_setScopeId<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setScopeId(self);
// return 1;
}
}
pub trait QHostAddress_setScopeId<RetType> {
fn setScopeId(self , rsthis: & QHostAddress) -> RetType;
}
// proto: void QHostAddress::setScopeId(const QString & id);
impl<'a> /*trait*/ QHostAddress_setScopeId<()> for (&'a QString) {
fn setScopeId(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress10setScopeIdERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QHostAddress10setScopeIdERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QHostAddress::~QHostAddress();
impl /*struct*/ QHostAddress {
pub fn free<RetType, T: QHostAddress_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QHostAddress_free<RetType> {
fn free(self , rsthis: & QHostAddress) -> RetType;
}
// proto: void QHostAddress::~QHostAddress();
impl<'a> /*trait*/ QHostAddress_free<()> for () {
fn free(self , rsthis: & QHostAddress) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddressD2Ev()};
unsafe {_ZN12QHostAddressD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: quint32 QHostAddress::toIPv4Address(bool * ok);
impl /*struct*/ QHostAddress {
pub fn toIPv4Address<RetType, T: QHostAddress_toIPv4Address<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toIPv4Address(self);
// return 1;
}
}
pub trait QHostAddress_toIPv4Address<RetType> {
fn toIPv4Address(self , rsthis: & QHostAddress) -> RetType;
}
// proto: quint32 QHostAddress::toIPv4Address(bool * ok);
impl<'a> /*trait*/ QHostAddress_toIPv4Address<u32> for (&'a mut Vec<i8>) {
fn toIPv4Address(self , rsthis: & QHostAddress) -> u32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress13toIPv4AddressEPb()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {_ZNK12QHostAddress13toIPv4AddressEPb(rsthis.qclsinst, arg0)};
return ret as u32;
// return 1;
}
}
// proto: static QPair<QHostAddress, int> QHostAddress::parseSubnet(const QString & subnet);
impl /*struct*/ QHostAddress {
pub fn parseSubnet_s<RetType, T: QHostAddress_parseSubnet_s<RetType>>( overload_args: T) -> RetType {
return overload_args.parseSubnet_s();
// return 1;
}
}
pub trait QHostAddress_parseSubnet_s<RetType> {
fn parseSubnet_s(self ) -> RetType;
}
// proto: static QPair<QHostAddress, int> QHostAddress::parseSubnet(const QString & subnet);
impl<'a> /*trait*/ QHostAddress_parseSubnet_s<()> for (&'a QString) {
fn parseSubnet_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress11parseSubnetERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QHostAddress11parseSubnetERK7QString(arg0)};
// return 1;
}
}
// proto: quint32 QHostAddress::toIPv4Address();
impl<'a> /*trait*/ QHostAddress_toIPv4Address<u32> for () {
fn toIPv4Address(self , rsthis: & QHostAddress) -> u32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QHostAddress13toIPv4AddressEv()};
let mut ret = unsafe {_ZNK12QHostAddress13toIPv4AddressEv(rsthis.qclsinst)};
return ret as u32;
// return 1;
}
}
// proto: bool QHostAddress::setAddress(const QString & address);
impl<'a> /*trait*/ QHostAddress_setAddress<i8> for (&'a QString) {
fn setAddress(self , rsthis: & QHostAddress) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QHostAddress10setAddressERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN12QHostAddress10setAddressERK7QString(rsthis.qclsinst, arg0)};
return ret as i8;
// return 1;
}
}
impl /*struct*/ QIPv6Address {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QIPv6Address {
return QIPv6Address{qclsinst: qthis, ..Default::default()};
}
}
// <= body block end
|
// Copyright 2020 - 2021 Alex Dukhno
//
// 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::*;
#[rstest::rstest]
fn update_all_records(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name (column_test smallint);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::TableCreated));
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (123), (456);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsInserted(2)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_test".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["123".to_owned()])),
Ok(QueryEvent::DataRow(vec!["456".to_owned()])),
Ok(QueryEvent::RecordsSelected(2)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_test=789;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(2)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_test".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["789".to_owned()])),
Ok(QueryEvent::DataRow(vec!["789".to_owned()])),
Ok(QueryEvent::RecordsSelected(2)),
]);
}
#[rstest::rstest]
fn update_single_column_of_all_records(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name (col1 smallint, col2 smallint);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::TableCreated));
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (123, 789), (456, 789);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsInserted(2)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("col1".to_owned(), SMALLINT),
("col2".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec!["123".to_owned(), "789".to_owned()])),
Ok(QueryEvent::DataRow(vec!["456".to_owned(), "789".to_owned()])),
Ok(QueryEvent::RecordsSelected(2)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set col2=357;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(2)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("col1".to_owned(), SMALLINT),
("col2".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec!["123".to_owned(), "357".to_owned()])),
Ok(QueryEvent::DataRow(vec!["456".to_owned(), "357".to_owned()])),
Ok(QueryEvent::RecordsSelected(2)),
]);
}
#[rstest::rstest]
fn update_multiple_columns_of_all_records(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name (col1 smallint, col2 smallint, col3 smallint);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::TableCreated));
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (111, 222, 333), (444, 555, 666);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsInserted(2)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("col1".to_owned(), SMALLINT),
("col2".to_owned(), SMALLINT),
("col3".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec![
"111".to_owned(),
"222".to_owned(),
"333".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"444".to_owned(),
"555".to_owned(),
"666".to_owned(),
])),
Ok(QueryEvent::RecordsSelected(2)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set col3=777, col1=999;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(2)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("col1".to_owned(), SMALLINT),
("col2".to_owned(), SMALLINT),
("col3".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec![
"999".to_owned(),
"222".to_owned(),
"777".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"999".to_owned(),
"555".to_owned(),
"777".to_owned(),
])),
Ok(QueryEvent::RecordsSelected(2)),
]);
}
#[rstest::rstest]
fn update_all_records_in_multiple_columns(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name (column_1 smallint, column_2 smallint, column_3 smallint);"
.to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::TableCreated));
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (1, 2, 3), (4, 5, 6), (7, 8, 9);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsInserted(3)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("column_1".to_owned(), SMALLINT),
("column_2".to_owned(), SMALLINT),
("column_3".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec![
"1".to_owned(),
"2".to_owned(),
"3".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"4".to_owned(),
"5".to_owned(),
"6".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"7".to_owned(),
"8".to_owned(),
"9".to_owned(),
])),
Ok(QueryEvent::RecordsSelected(3)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_1=10, column_2=20, column_3=30;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(3)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("column_1".to_owned(), SMALLINT),
("column_2".to_owned(), SMALLINT),
("column_3".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec![
"10".to_owned(),
"20".to_owned(),
"30".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"10".to_owned(),
"20".to_owned(),
"30".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"10".to_owned(),
"20".to_owned(),
"30".to_owned(),
])),
Ok(QueryEvent::RecordsSelected(3)),
]);
}
#[rstest::rstest]
fn update_records_in_nonexistent_table(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_test=789;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Err(QueryError::table_does_not_exist("schema_name.table_name")));
}
#[rstest::rstest]
fn update_non_existent_columns_of_records(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name (column_test smallint);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::TableCreated));
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (123);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsInserted(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_test".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["123".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set col1=456, col2=789;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_many(vec![Err(QueryError::column_does_not_exist("col1"))]);
}
#[rstest::rstest]
fn test_update_with_dynamic_expression(database_with_schema: (InMemory, ResultCollector)) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name (\
si_column_1 smallint, \
si_column_2 smallint, \
si_column_3 smallint);"
.to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::TableCreated));
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (1, 2, 3), (4, 5, 6), (7, 8, 9);".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsInserted(3)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("si_column_1".to_owned(), SMALLINT),
("si_column_2".to_owned(), SMALLINT),
("si_column_3".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec![
"1".to_owned(),
"2".to_owned(),
"3".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"4".to_owned(),
"5".to_owned(),
"6".to_owned(),
])),
Ok(QueryEvent::DataRow(vec![
"7".to_owned(),
"8".to_owned(),
"9".to_owned(),
])),
Ok(QueryEvent::RecordsSelected(3)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name \
set \
si_column_1 = 2 * si_column_1, \
si_column_2 = 2 * (si_column_1 + si_column_2), \
si_column_3 = (si_column_3 + (2 * (si_column_1 + si_column_2)));"
.to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(3)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![
("si_column_1".to_owned(), SMALLINT),
("si_column_2".to_owned(), SMALLINT),
("si_column_3".to_owned(), SMALLINT),
])),
Ok(QueryEvent::DataRow(vec![
2.to_string(),
(2 * (1 + 2)).to_string(),
(3 + (2 * (1 + 2))).to_string(),
])),
Ok(QueryEvent::DataRow(vec![
(2 * 4).to_string(),
(2 * (4 + 5)).to_string(),
(6 + (2 * (4 + 5))).to_string(),
])),
Ok(QueryEvent::DataRow(vec![
(2 * 7).to_string(),
(2 * (7 + 8)).to_string(),
(9 + (2 * (7 + 8))).to_string(),
])),
Ok(QueryEvent::RecordsSelected(3)),
]);
}
#[cfg(test)]
mod operators {
use super::*;
#[cfg(test)]
mod integers {
use super::*;
#[rstest::fixture]
fn with_table(database_with_schema: (InMemory, ResultCollector)) -> (InMemory, ResultCollector) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name(column_si smallint);".to_owned(),
})
.expect("query executed");
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values (2);".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_till_this_moment(vec![
Ok(QueryEvent::TableCreated),
Ok(QueryEvent::QueryComplete),
Ok(QueryEvent::RecordsInserted(1)),
Ok(QueryEvent::QueryComplete),
]);
(engine, collector)
}
#[rstest::rstest]
fn addition(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 1 + 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["3".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn subtraction(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 1 - 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["-1".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn multiplication(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 3 * 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["6".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn division(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 8 / 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["4".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn modulo(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 8 % 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["0".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn exponentiation(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 8 ^ 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["64".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
#[ignore] //TODO: TypeInference#infer_static is not implemented
fn square_root(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = |/ 16;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["4".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
#[ignore] //TODO: TypeInference#infer_static is not implemented
fn cube_root(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = ||/ 8;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["2".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn factorial(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 5!;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["120".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn prefix_factorial(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = !!5;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["120".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn absolute_value(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = @ -5;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["5".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn bitwise_and(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 5 & 1;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["1".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn bitwise_or(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 5 | 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["7".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn bitwise_not(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = ~1;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["-2".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn bitwise_shift_left(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 1 << 4;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["16".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn bitwise_right_left(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 8 >> 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["2".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn evaluate_many_operations(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set column_si = 5 & 13 % 10 + 1 * 20 - 40 / 4;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("column_si".to_owned(), SMALLINT)])),
Ok(QueryEvent::DataRow(vec!["5".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
}
#[cfg(test)]
mod string {
use super::*;
#[rstest::fixture]
fn with_table(database_with_schema: (InMemory, ResultCollector)) -> (InMemory, ResultCollector) {
let (mut engine, collector) = database_with_schema;
engine
.execute(Inbound::Query {
sql: "create table schema_name.table_name(strings char(5));".to_owned(),
})
.expect("query executed");
engine
.execute(Inbound::Query {
sql: "insert into schema_name.table_name values ('x');".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_till_this_moment(vec![
Ok(QueryEvent::TableCreated),
Ok(QueryEvent::QueryComplete),
Ok(QueryEvent::RecordsInserted(1)),
Ok(QueryEvent::QueryComplete),
]);
(engine, collector)
}
#[rstest::rstest]
fn concatenation(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set strings = '123' || '45';".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("strings".to_owned(), CHAR)])),
Ok(QueryEvent::DataRow(vec!["12345".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
#[ignore] //TODO: TypeInference#infer_static is not implemented
fn concatenation_with_number(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set strings = 1 || '45';".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("strings".to_owned(), CHAR)])),
Ok(QueryEvent::DataRow(vec!["145".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set strings = '45' || 1;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Ok(QueryEvent::RecordsUpdated(1)));
engine
.execute(Inbound::Query {
sql: "select * from schema_name.table_name;".to_owned(),
})
.expect("query executed");
collector.lock().unwrap().assert_receive_many(vec![
Ok(QueryEvent::RowDescription(vec![("strings".to_owned(), CHAR)])),
Ok(QueryEvent::DataRow(vec!["451".to_owned()])),
Ok(QueryEvent::RecordsSelected(1)),
]);
}
#[rstest::rstest]
fn non_string_concatenation_not_supported(with_table: (InMemory, ResultCollector)) {
let (mut engine, collector) = with_table;
engine
.execute(Inbound::Query {
sql: "update schema_name.table_name set strings = 1 || 2;".to_owned(),
})
.expect("query executed");
collector
.lock()
.unwrap()
.assert_receive_single(Err(QueryError::undefined_function(
"||".to_owned(),
"smallint".to_owned(),
"smallint".to_owned(),
)));
}
}
}
|
use super::{Chain, Day, Link, Streak};
use chrono::{Datelike, Local, NaiveDate, Duration};
use super::FORMAT;
pub fn calculate_streak(chain: &Chain, links: &Vec<Link>) -> Streak {
let name = chain.name.to_string();
let mut date: Option<NaiveDate> = None;
let mut prev_date: Option<NaiveDate>;
let mut streak = 0;
let mut longest_streak = 0;
for link in links.iter() {
prev_date = date;
date = Some(link.date);
if date.is_some() && prev_date.is_some() {
let between = date
.unwrap()
.signed_duration_since(prev_date.unwrap())
.num_days()
- 1;
if between > 0 {
if streak > longest_streak {
longest_streak = streak;
}
streak = 0;
}
}
streak += 1;
}
if streak > longest_streak {
longest_streak = streak;
}
Streak {
name,
streak,
longest_streak,
}
}
pub fn create_days(links: &Vec<Link>) -> Vec<Day> {
let mut days: Vec<Day> = Vec::new();
if links.len() == 0 {
return create_dummy_days()
}
let start_date = links[0].date;
let end_date = Local::today().naive_local();
let difference = end_date.signed_duration_since(start_date).num_days();
let start_date = if difference < 10 {
start_date - Duration::days(9 - difference)
} else {
start_date + Duration::days(difference - 9)
};
let links = if links.len() > 10 {
links.get(links.len() - 10..).unwrap()
} else {
links.get(..).unwrap()
};
assert!(start_date.iter_days().take(10).last().unwrap().format(FORMAT).to_string() == end_date.format(FORMAT).to_string());
let mut is_done = false;
for date in start_date.iter_days().take(10) {
for link in links {
if link.date.signed_duration_since(date).num_days() == 0 {
is_done = true;
}
}
let day = Day {
day: date.day() as i32,
is_done: is_done
};
days.push(day);
is_done = false;
}
assert!(days.len() == 10);
days
}
pub fn create_dummy_days() -> Vec<Day> {
let mut days: Vec<Day> = Vec::new();
let today = Local::today().naive_local();
let start_date = today - Duration::days(9);
for date in start_date.iter_days().take(10) {
let day = Day {
day: date.day() as i32,
is_done: false
};
days.push(day);
}
assert!(days.len() == 10);
days
}
|
use std::error;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use structopt::StructOpt;
type Error = Box<dyn error::Error>;
#[derive(StructOpt)]
#[structopt(
name = "solve",
about = "solve the puzzles from the Advent of Code 2020, day 5"
)]
struct Opt {
/// path to input file; should contain list of boarding passes
input: PathBuf,
}
fn main() -> Result<(), Error> {
let opts = Opt::from_args();
let boarding_pass_ids = fs::read_to_string(opts.input.clone())?
.lines()
.map(|s| BoardingPass::from_str(s).map(|b| b.id()))
.collect::<Result<Vec<u16>, Error>>()?;
println!("part 1: highest seat id on a boarding pass");
println!("{:?}", boarding_pass_ids.iter().max());
println!("part 2: ID of seat missing from list");
println!("{:?}", find_missing_id(boarding_pass_ids));
Ok(())
}
fn find_missing_id(mut ids: Vec<u16>) -> Option<u16> {
ids.sort();
for ix in 1..ids.len() {
let prev_id = ids[ix] - 1;
if prev_id != ids[ix - 1] {
return Some(prev_id);
}
}
None
}
struct BoardingPass {
row: u8,
column: u8,
}
impl BoardingPass {
fn id(&self) -> u16 {
(self.row as u16) * 8u16 + (self.column as u16)
}
}
impl FromStr for BoardingPass {
type Err = Error;
fn from_str(s: &str) -> Result<BoardingPass, Error> {
if s.len() != 10 {
return Err(Error::from(format!(
"Illegal boarding pass {:?}, expected 10 bytes, found {}",
s,
s.len()
)));
}
let row = s[0..7]
.chars()
.map(|c| match c {
'F' => Ok('0'),
'B' => Ok('1'),
_ => Err(Error::from(format!(
"Illegal character {:?} in row of boarding pass {:?}",
c, s
))),
})
.collect::<Result<String, Error>>()
.and_then(|bs| u8::from_str_radix(&bs, 2).map_err(Error::from))?;
let column = s[7..10]
.chars()
.map(|c| match c {
'L' => Ok('0'),
'R' => Ok('1'),
_ => Err(Error::from(format!(
"Illegal character {:?} in column of boarding pass {:?}",
c, s
))),
})
.collect::<Result<String, Error>>()
.and_then(|bs| u8::from_str_radix(&bs, 2).map_err(Error::from))?;
Ok(BoardingPass { row, column })
}
}
//use std::fmt::Display;
//impl Display for BoardingPass {}
|
//! The various tmux operations commands.
use super::project::TMUX_BIN;
use super::TmuxError;
use clap::crate_name;
use shlex::Shlex;
use std::env::set_current_dir;
use std::process::Command;
use std::{env, fmt};
/// The commands. Implemented as an enum instead of traits/structs
/// to prevent dynamic dispatch.
///
/// Implements [`Display`](std::fmt::Display), formatting the commands a shell
/// command which is used to display the shell script for the `debug`
/// cli command.
#[derive(Debug)]
pub(crate) enum Commands<'a> {
/// Start the server and change into the work directory if specified.
Server {
project_name: &'a str,
project_root: &'a Option<String>,
},
/// Runs the various `on_project_<event>` commands.
ProjectEvent {
event_name: &'a str,
on_event: &'a Option<Vec<String>>,
},
/// Start the new tmux session, and cd again (for tmux < 1.9 compat).
Session {
project_name: &'a str,
first_window_name: Option<&'a str>,
},
/// `send-keys` command.
SendKeys {
command: String,
session_name: &'a str,
window_index: usize,
pane_index: Option<usize>,
comment: Option<String>,
},
/// `new-window` command.
NewWindow {
session_name: &'a str,
window_name: &'a str,
window_index: usize,
project_root: &'a Option<String>,
},
/// `split-window` command.
SplitWindow {
session_name: &'a str,
window_index: usize,
project_root: &'a Option<String>,
},
/// `select-layout` command.
SelectLayout {
session_name: &'a str,
window_index: usize,
layout: &'a str,
},
/// `select-window` command.
SelectWindow {
session_name: &'a str,
window_index: usize,
},
/// `select-pane` command
SelectPane {
session_name: &'a str,
window_index: usize,
pane_index: usize,
},
/// Attaches to a session using `attach-sesssion` or `switch-client`,
/// depends upon already running inside a tmux session or out of it.
AttachSession { session_name: &'a str },
/// `kill-session` command
StopSession { session_name: &'a str },
/// Set a hook for tmux events
SetHook {
session_name: &'a str,
hook_name: &'a str,
hook_command: String,
},
}
impl<'a> Commands<'a> {
fn fmt_server_command(
f: &mut fmt::Formatter<'_>,
project_name: &'a str,
project_root: &'a Option<String>,
) -> fmt::Result {
let shebang = env::var("SHELL").map(|x| format!("#!{x}")).ok();
let cd_command = match project_root {
Some(project_root) => format!("\ncd {project_root}"),
None => "".into(),
};
write!(
f,
"{}\n\
#\n\
# {} {} project\n\n\
{} start-server\
{}",
shebang.unwrap_or_else(|| "".into()),
crate_name!(),
project_name,
TMUX_BIN,
cd_command
)
}
fn fmt_project_command(
f: &mut fmt::Formatter<'_>,
event_name: &'a str,
on_event: &'a Option<Vec<String>>,
) -> fmt::Result {
let commands = on_event.as_ref().map_or(String::from(""), |v| v.join("\n"));
write!(f, "\n# Run on_project_{event_name} command(s)\n{commands}")
}
fn fmt_session_command(
f: &mut fmt::Formatter<'_>,
project_name: &'a str,
first_window_name: Option<&'a str>,
) -> fmt::Result {
let window_param = first_window_name.map_or("".into(), |n| format!(" -n {n}"));
write!(
f,
"\n# Create new session and first window\n\
TMUX= {TMUX_BIN} new-session -d -s {project_name}{window_param}"
)
}
fn fmt_send_keys(
f: &mut fmt::Formatter,
command: &str,
session_name: &str,
window_index: usize,
pane_index: Option<usize>,
comment: Option<&str>,
) -> fmt::Result {
let formatted_pane_index = pane_index.map_or("".into(), |idx| format!(".{idx}"));
let comment = comment.map_or("".into(), |c| format!("\n# {c}\n"));
let escaped = shell_escape::escape(command.into());
write!(
f,
"{comment}{TMUX_BIN} send-keys -t {session_name}:{window_index}{formatted_pane_index} {escaped} C-m"
)
}
fn get_cd_root_flag(project_root: &Option<String>) -> String {
match project_root {
Some(dir) => format!(" -c {dir}"),
None => "".into(),
}
}
fn fmt_new_window(
f: &mut fmt::Formatter,
session_name: &str,
window_name: &str,
window_index: usize,
project_root: &Option<String>,
) -> fmt::Result {
let cd_root = Commands::get_cd_root_flag(project_root);
write!(
f,
"\n# Create \"{window_name}\" window \n{TMUX_BIN} new-window{cd_root} -t {session_name}:{window_index} -n {window_name}"
)
}
fn fmt_split_window(
f: &mut fmt::Formatter,
session_name: &str,
window_index: usize,
project_root: &Option<String>,
) -> Result<(), fmt::Error> {
let cd_root = Commands::get_cd_root_flag(project_root);
write!(
f,
"{TMUX_BIN} splitw{cd_root} -t {session_name}:{window_index}"
)
}
fn fmt_select_layout(
f: &mut fmt::Formatter,
session_name: &str,
window_index: usize,
layout: &str,
) -> Result<(), fmt::Error> {
write!(
f,
"{TMUX_BIN} select-layout -t {session_name}:{window_index} {layout}"
)
}
fn fmt_select_window(
f: &mut fmt::Formatter,
session_name: &str,
window_index: usize,
) -> Result<(), fmt::Error> {
write!(
f,
"{TMUX_BIN} select-window -t {session_name}:{window_index}"
)
}
fn fmt_select_pane(
f: &mut fmt::Formatter,
session_name: &str,
window_index: usize,
pane_index: usize,
) -> Result<(), fmt::Error> {
write!(
f,
"{TMUX_BIN} select-pane -t {session_name}:{window_index}.{pane_index}"
)
}
fn fmt_attach_session(f: &mut fmt::Formatter, session_name: &str) -> Result<(), fmt::Error> {
write!(
f,
"\nif [ -z \"$TMUX\" ]; then\n {TMUX_BIN} -u attach-session -t {session_name}\n\
else\n {TMUX_BIN} -u switch-client -t {session_name}\nfi"
)
}
fn fmt_stop_session(f: &mut fmt::Formatter, session_name: &str) -> Result<(), fmt::Error> {
write!(f, "{TMUX_BIN} kill-session -t {session_name}")
}
fn fmt_set_hook(
f: &mut fmt::Formatter,
session_name: &str,
hook_name: &str,
hook_command: &str,
) -> Result<(), fmt::Error> {
write!(
f,
"{TMUX_BIN} set-hook -t {session_name} {hook_name} \"{hook_command}\""
)
}
/// Runs the command, based on the enum values.
pub fn run(&self) -> Result<(), TmuxError> {
match self {
Commands::Server {
project_name: _,
project_root,
} => Commands::run_server_command(project_root),
Commands::ProjectEvent {
event_name: _,
on_event,
} => Commands::run_project_event(on_event),
Commands::Session {
project_name,
first_window_name,
} => Commands::run_session_command(project_name, first_window_name),
Commands::SendKeys {
command,
session_name,
window_index,
pane_index,
comment: _,
} => Commands::run_send_keys(command, session_name, *window_index, pane_index),
Commands::NewWindow {
session_name,
window_name,
window_index,
project_root,
} => Commands::run_new_window(session_name, window_name, *window_index, project_root),
Commands::SplitWindow {
session_name,
window_index,
project_root,
} => Commands::run_split_window(session_name, *window_index, project_root),
Commands::SelectLayout {
session_name,
window_index,
layout,
} => Commands::run_select_layout(session_name, *window_index, layout),
Commands::SelectWindow {
session_name,
window_index,
} => Commands::run_select_window(session_name, *window_index),
Commands::SelectPane {
session_name,
window_index,
pane_index,
} => Commands::run_select_pane(session_name, *window_index, *pane_index),
Commands::AttachSession { session_name } => Commands::run_attach_session(session_name),
Commands::StopSession { session_name } => Commands::run_stop_session(session_name),
Commands::SetHook {
session_name,
hook_name,
hook_command,
} => Commands::run_set_hook(session_name, hook_name, hook_command),
}
}
fn run_server_command(project_root: &'a Option<String>) -> Result<(), TmuxError> {
Command::new(TMUX_BIN).arg("start-server").status()?;
if let Some(root_dir) = project_root {
set_current_dir(shellexpand::full(root_dir)?.as_ref())?;
}
Ok(())
}
fn run_project_event(on_event: &Option<Vec<String>>) -> Result<(), TmuxError> {
if let Some(commands) = on_event {
for command in commands {
let mut parts = Shlex::new(command);
let cmd_opt = parts.next();
if let Some(cmd) = cmd_opt {
let res = Command::new(cmd).args(parts.collect::<Vec<_>>()).status();
if res.is_err() {
eprintln!("Error executing command {command}");
}
}
}
}
Ok(())
}
fn run_session_command(
project_name: &str,
first_window_name: &Option<&str>,
) -> Result<(), TmuxError> {
let mut session_args = vec!["new-session", "-d", "-s", project_name];
if let Some(name) = first_window_name {
session_args.push("-n");
session_args.push(name);
}
let res = Command::new(TMUX_BIN)
.env_remove("TMUX")
.args(session_args)
.status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message("Cannot start session".to_string()))
}
}
fn run_send_keys(
command: &String,
session_name: &str,
window_index: usize,
pane_index: &Option<usize>,
) -> Result<(), TmuxError> {
let target_name = if let Some(pane_idx) = pane_index {
format!("{session_name}:{window_index}.{pane_idx}")
} else {
format!("{session_name}:{window_index}")
};
let args = ["send-keys", "-t", &target_name, command, "C-m"];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot run send-keys for {command}"
)))
}
}
fn run_new_window(
session_name: &str,
window_name: &str,
window_index: usize,
project_root: &Option<String>,
) -> Result<(), TmuxError> {
let target_name = format!("{session_name}:{window_index}");
let expanded: String;
let mut args = vec!["new-window", "-t", &target_name, "-n", window_name];
if let Some(root_dir) = project_root {
args.push("-c");
expanded = shellexpand::full(root_dir)?.to_string();
args.push(&expanded);
}
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot create window {window_name}"
)))
}
}
fn run_split_window(
session_name: &str,
window_index: usize,
project_root: &Option<String>,
) -> Result<(), TmuxError> {
let target_name = format!("{session_name}:{window_index}");
let mut args = vec!["splitw", "-t", &target_name];
let expanded: String;
if let Some(root_dir) = project_root {
args.push("-c");
expanded = shellexpand::full(root_dir)?.to_string();
args.push(&expanded);
}
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot split window {target_name}"
)))
}
}
fn run_select_layout(
session_name: &str,
window_index: usize,
layout: &str,
) -> Result<(), TmuxError> {
let target_name = format!("{session_name}:{window_index}");
let args = vec!["select-layout", "-t", &target_name];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot select layout {layout} for window {target_name}"
)))
}
}
fn run_select_window(session_name: &str, window_index: usize) -> Result<(), TmuxError> {
let target_name = format!("{session_name}:{window_index}");
let args = vec!["select-window", "-t", &target_name];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot select window {target_name}"
)))
}
}
fn run_select_pane(
session_name: &str,
window_index: usize,
pane_index: usize,
) -> Result<(), TmuxError> {
let target_name = format!("{session_name}:{window_index}.{pane_index}");
let args = vec!["select-pane", "-t", &target_name];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot select pane {target_name}"
)))
}
}
fn run_attach_session(session_name: &str) -> Result<(), TmuxError> {
let param = if env::var("TMUX").is_ok() {
"switch-client"
} else {
"attach-session"
};
let args = ["-u", param, "-t", session_name];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot {param} to session {session_name}"
)))
}
}
fn run_stop_session(session_name: &str) -> Result<(), TmuxError> {
let args = ["kill-session", "-t", session_name];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot kill session {session_name}"
)))
}
}
fn run_set_hook(
session_name: &str,
hook_name: &str,
hook_command: &str,
) -> Result<(), TmuxError> {
let args = ["set-hook", "-t", session_name, hook_name, hook_command];
let res = Command::new(TMUX_BIN).args(args).status()?;
if res.success() {
Ok(())
} else {
Err(TmuxError::Message(format!(
"Cannot set {hook_name} hook for session {session_name}"
)))
}
}
}
impl<'a> fmt::Display for Commands<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Commands::Server {
project_name,
project_root,
} => Commands::fmt_server_command(f, project_name, project_root),
Commands::ProjectEvent {
event_name,
on_event,
} => Commands::fmt_project_command(f, event_name, on_event),
Commands::Session {
project_name,
first_window_name,
} => Commands::fmt_session_command(f, project_name, *first_window_name),
Commands::SendKeys {
command,
session_name,
window_index,
pane_index,
comment,
} => Commands::fmt_send_keys(
f,
command,
session_name,
*window_index,
*pane_index,
comment.as_ref().map(|x| &**x),
),
Commands::NewWindow {
session_name,
window_name,
window_index,
project_root,
} => {
Commands::fmt_new_window(f, session_name, window_name, *window_index, project_root)
}
Commands::SplitWindow {
session_name,
window_index,
project_root,
} => Commands::fmt_split_window(f, session_name, *window_index, project_root),
Commands::SelectLayout {
session_name,
window_index,
layout,
} => Commands::fmt_select_layout(f, session_name, *window_index, layout),
Commands::SelectWindow {
session_name,
window_index,
} => Commands::fmt_select_window(f, session_name, *window_index),
Commands::SelectPane {
session_name,
window_index,
pane_index,
} => Commands::fmt_select_pane(f, session_name, *window_index, *pane_index),
Commands::AttachSession { session_name } => {
Commands::fmt_attach_session(f, session_name)
}
Commands::StopSession { session_name } => Commands::fmt_stop_session(f, session_name),
Commands::SetHook {
session_name,
hook_name,
hook_command,
} => Commands::fmt_set_hook(f, session_name, hook_name, hook_command),
}
}
}
|
use icell::{
typeid::{self, ICell},
write_all,
};
#[test]
fn create() {
typeid::make!(type TestCreate);
let owner = TestCreate::owner();
assert_eq!(std::mem::size_of_val(&owner), 0);
}
#[test]
#[cfg(feature = "std")] // on `no_std` reentrant acquires block
#[cfg_attr(miri, ignore)]
#[should_panic = "attempted a reentrant acquire of a `Type<TestReentrant>`"]
fn reentrant() {
typeid::make!(type TestReentrant);
let _owner = TestReentrant::owner();
assert!(TestReentrant::try_owner().is_none());
let _owner = TestReentrant::owner();
}
typeid::make!(type Test);
#[test]
fn read() {
let owner = Test::owner();
assert_eq!(std::mem::size_of_val(&owner), 0);
let cell = ICell::new(0xdead_beef_u32);
assert_eq!(*owner.read(&cell), 0xdead_beef);
}
#[test]
fn write() {
let mut owner = Test::owner();
assert_eq!(std::mem::size_of_val(&owner), 0);
let cell = ICell::new(0xdead_beef_u32);
let value = owner.write(&cell);
*value = 0;
assert_eq!(*owner.read(&cell), 0);
}
#[test]
fn write_all() {
let mut owner = Test::owner();
assert_eq!(std::mem::size_of_val(&owner), 0);
let a = ICell::new(0xdead_beef_u32);
let b = ICell::new(0xbeef_dead_u32);
let c = ICell::new(0xdead_baaf_u32);
let d = ICell::new(0xdeed_beef_u32);
{
let (a, b, c, d) = write_all!(owner => a, b, c, d);
std::mem::swap(a, b);
std::mem::swap(c, d);
std::mem::swap(a, d);
}
let &a = owner.read(&a);
let &b = owner.read(&b);
let &c = owner.read(&c);
let &d = owner.read(&d);
assert_eq!(a, 0xdead_baaf);
assert_eq!(b, 0xdead_beef);
assert_eq!(c, 0xdeed_beef);
assert_eq!(d, 0xbeef_dead);
}
#[test]
fn read_from_fresh() {
let owner = Test::owner();
assert_eq!(std::mem::size_of_val(&owner), 0);
let cell = owner.cell::<u32>(0xdead_beef);
drop(owner);
let owner = Test::owner();
assert_eq!(*owner.read(&cell), 0xdead_beef);
}
#[test]
fn from_rc() {
use std::rc::Rc;
let mut owner = Test::owner();
let a = Rc::new((ICell::new(0), ICell::new(1)));
let b = a.clone();
owner.swap(&a.0, &b.1);
drop(b);
let (a, b) = Rc::try_unwrap(a).ok().unwrap();
assert_eq!(a.into_inner(), 1);
assert_eq!(b.into_inner(), 0);
}
|
use nalgebra;
pub type Pose<F> = nalgebra::geometry::Isometry2<F>;
pub type PoseCovariance<F> = nalgebra::base::Matrix3<F>;
pub type Point<F> = nalgebra::geometry::Point2<F>;
pub type PointCovariance<F> = nalgebra::base::Matrix2<F>;
const GRID_OCCU: i8 = 1;
const GRID_FREE: i8 = -1;
const GRID_NONE: i8 = 0;
#[inline(always)]
pub const fn grid_occupied(x: i8) -> bool {
x > GRID_NONE
}
#[inline(always)]
pub const fn grid_mapped(x: i8) -> bool {
x != GRID_NONE
}
#[inline(always)]
pub const fn grid_freecell(x: i8) -> bool {
x < GRID_NONE
}
pub type GridMap = nalgebra::DMatrix<i8>;
pub type GridMapView<'a> = nalgebra::DMatrixSlice<'a, i8>;
pub type GridMapViewMut<'a> = nalgebra::DMatrixSliceMut<'a, i8>;
pub type PointCloud<F> = nalgebra::Matrix2xX<F>;
|
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(missing_copy_implementations)]
use std::ffi::CString;
use cql_ffi::batch::CassBatch;
use cql_ffi::future::CassFuture;
use cql_ffi::future::ResultFuture;
use cql_ffi::future::PreparedFuture;
use cql_ffi::error::CassError;
use cql_ffi::statement::CassStatement;
use cql_ffi::schema::CassSchema;
use cql_ffi::cluster::CassCluster;
use cql_bindgen::CassFuture as _CassFuture;
use cql_bindgen::cass_future_free;
use cql_bindgen::cass_future_wait;
use cql_bindgen::cass_future_error_code;
use cql_bindgen::CassSession as _CassSession;
use cql_bindgen::cass_session_new;
use cql_bindgen::cass_session_free;
use cql_bindgen::cass_session_close;
use cql_bindgen::cass_session_connect;
use cql_bindgen::cass_session_prepare;
use cql_bindgen::cass_session_execute;
use cql_bindgen::cass_session_execute_batch;
use cql_bindgen::cass_session_get_schema;
use cql_bindgen::cass_session_connect_keyspace;
pub struct CassSession(pub *mut _CassSession);
unsafe impl Sync for CassSession{}
unsafe impl Send for CassSession{}
impl Drop for CassSession {
fn drop(&mut self) {
unsafe {
cass_session_free(self.0)
}
}
}
impl CassSession {
pub fn new() -> CassSession {
unsafe {
CassSession(cass_session_new())
}
}
pub fn close(self) -> CassFuture {
unsafe {
CassFuture(cass_session_close(self.0))
}
}
pub fn connect(self, cluster: &CassCluster) -> SessionFuture {
unsafe {
SessionFuture(cass_session_connect(self.0, cluster.0), self)
}
}
pub fn prepare(&self, query: &str) -> Result<PreparedFuture, CassError> {
unsafe {
let query = CString::new(query).unwrap();
Ok(PreparedFuture(cass_session_prepare(self.0, query.as_ptr())))
}
}
pub fn execute(&self, statement: &str, parameter_count: u64) -> ResultFuture {
unsafe {
ResultFuture(cass_session_execute(self.0,
CassStatement::new(statement,parameter_count).0))
}
}
pub fn execute_statement(&self, statement: &CassStatement) -> ResultFuture {
unsafe {
ResultFuture(cass_session_execute(self.0, statement.0))
}
}
pub fn execute_batch(&self, batch: CassBatch) -> ResultFuture {
ResultFuture(unsafe {
cass_session_execute_batch(self.0, batch.0)
})
}
pub fn get_schema(&self) -> CassSchema {
unsafe {
CassSchema(cass_session_get_schema(self.0))
}
}
pub unsafe fn connect_keyspace(&self,
cluster: CassCluster,
keyspace: *const ::libc::c_char)
-> CassFuture {
CassFuture(cass_session_connect_keyspace(self.0, cluster.0, keyspace))
}
}
pub struct SessionFuture(pub *mut _CassFuture, pub CassSession);
impl SessionFuture {
pub fn wait(self) -> Result<CassSession, CassError> {
unsafe {
cass_future_wait(self.0);
self.error_code()
}
}
fn error_code(self) -> Result<CassSession, CassError> {
unsafe {
let code = cass_future_error_code(self.0);
cass_future_free(self.0);
CassError::build(code).wrap(self.1)
}
}
}
|
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate log;
use clap::App;
use clap::Arg;
use clap::ArgMatches;
use hackscanner_lib::*;
use simplelog::TerminalMode;
use std::env;
use std::path::Path;
mod ui;
fn main() {
if let Err(ref e) = run() {
use error_chain::ChainedError;
use std::io::Write; // trait which holds `display_chain`
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "{}", e.display_chain()).expect(errmsg);
::std::process::exit(1);
}
}
fn run() -> Result<(), Error> {
let app = App::new("hackscanner")
.version(env!("CARGO_PKG_VERSION"))
.author("Daniel Corn <info@cundd.net>")
.about("Scan the filesystem for hacked files")
.arg(Arg::with_name("directory")
.help("Search in this directory")
.takes_value(true)
.index(1))
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help(get_verbosity_help()))
.arg(Arg::with_name("min-severity")
.short("m")
.takes_value(true)
.help("Sets the minimum severity to display (CRITICAL, MAJOR, MINOR, NOTICE, ALL)"))
.arg(Arg::with_name("quiet")
.short("q")
.long("quiet")
.alias("silent")
.help("Do not write to standard output if no violations > min-severity are found"))
.arg(Arg::with_name("validate")
.short("l")
.long("validate")
.takes_value(true)
.value_name("test-path")
.help("Check if the given test-path would create a violation (ignores if the path exists)"))
;
#[cfg(any(feature = "json", feature = "yaml"))]
let app = app.arg(
Arg::with_name("configuration")
.help("File with additional rules")
.short("c")
.long("configuration")
.takes_value(true),
);
let matches = app.get_matches();
configure_logging(&matches).unwrap();
#[cfg(not(any(feature = "json", feature = "yaml")))]
let rules = get_merged_rules(None)?;
#[cfg(any(feature = "json", feature = "yaml"))]
let rules = get_merged_rules(match matches.value_of("configuration") {
Some(c) => Some(Path::new(c)),
None => None,
})?;
match matches.value_of("validate") {
Some(test_path) => validate(&matches, rules, test_path),
None => scan(&matches, rules),
}
}
// Trace is only supported on debug-builds
#[cfg(debug_assertions)]
fn get_verbosity_help() -> &'static str {
"Sets the level of verbosity (-v = Info, -vv = Debug, -vvv = Trace)"
}
#[cfg(not(debug_assertions))]
fn get_verbosity_help() -> &'static str {
"Sets the level of verbosity (-v = Info, -vv = Debug)"
}
fn scan(matches: &ArgMatches, rules: Vec<Rule>) -> Result<(), Error> {
let min_severity = get_minimum_severity(matches);
let root = get_root(matches);
let quiet = matches.is_present("quiet");
let files = file_finder::find_files(root, &rules);
let ratings = sort_ratings(&rating::rate_entries(&files, &rules));
let summary = Summary::build(&ratings);
if !quiet || 0 < summary.ratings_above(min_severity) {
ui::print_summary(min_severity, &summary);
ui::print_ratings(min_severity, &ratings);
}
Ok(())
}
fn validate(matches: &ArgMatches, rules: Vec<Rule>, test_path: &str) -> Result<(), Error> {
let entry = ValidationDirEntry::from_path_str(test_path);
if !entry.path().exists() {
bail!(format!("File {} does not exist", entry.path().display()))
}
let rating = rate_entry(&entry, &rules);
ui::print_validation(&rating, matches.occurrences_of("v") > 0);
Ok(())
}
fn get_root(matches: &ArgMatches<'_>) -> String {
match matches.value_of("directory") {
Some(d) => d.to_owned(),
None => String::from(env::current_dir().unwrap().to_string_lossy()),
}
}
fn get_minimum_severity(matches: &ArgMatches<'_>) -> Severity {
let min_severity = matches.value_of("min-severity");
if min_severity.is_none() {
return Severity::NOTICE;
}
match min_severity.unwrap().to_uppercase().as_ref() {
"CRITICAL" => Severity::CRITICAL,
"MAJOR" => Severity::MAJOR,
"MINOR" => Severity::MINOR,
"NOTICE" => Severity::NOTICE,
_ => Severity::WHITELIST,
}
}
/// Read the `Rule`s from the given path and merge them with the builtin rules
fn get_merged_rules(path: Option<&Path>) -> Result<Vec<Rule>, Error> {
match path {
Some(p) => hackscanner_lib::get_merged_rules(p),
None => Ok(hackscanner_lib::get_builtin_rules()),
}
}
fn configure_logging(matches: &ArgMatches<'_>) -> Result<(), Error> {
let log_level_filter = match matches.occurrences_of("v") {
1 => simplelog::LevelFilter::Info,
2 => simplelog::LevelFilter::Debug,
3 => simplelog::LevelFilter::Trace,
_ => simplelog::LevelFilter::Warn,
};
let mut loggers: Vec<Box<dyn simplelog::SharedLogger>> = vec![];
// let mut config = simplelog::Config::default();
// config.time_format = Some("%H:%M:%S%.3f");
let config = simplelog::Config {
time_format: Some("%H:%M:%S%.3f"),
..Default::default()
};
if let Some(core_logger) =
simplelog::TermLogger::new(log_level_filter, config, TerminalMode::Mixed)
{
loggers.push(core_logger);
} else {
loggers.push(simplelog::SimpleLogger::new(log_level_filter, config));
}
match simplelog::CombinedLogger::init(loggers) {
Ok(_) => Ok(()),
Err(e) => bail!(format!("{}", e)),
}
}
|
use std::collections::HashMap;
use crossterm::event::Event;
use irust_api::{Command, GlobalVariables};
use super::Script;
const SCRIPT_CONFIG_NAME: &str = "script.toml";
pub struct ScriptManager {
sm: rscript::ScriptManager,
startup_cmds: Vec<Result<Option<Command>, rscript::Error>>,
}
macro_rules! mtry {
($e: expr) => {
(|| -> Result<_, Box<dyn std::error::Error>> { Ok($e) })()
};
}
impl ScriptManager {
pub fn new() -> Option<Self> {
let mut sm = rscript::ScriptManager::default();
let script_path = dirs::config_dir()?.join("irust").join("script");
sm.add_scripts_by_path(
&script_path,
rscript::Version::parse(crate::args::VERSION).expect("correct version"),
)
.ok()?;
unsafe {
sm.add_dynamic_scripts_by_path(
script_path,
rscript::Version::parse(crate::args::VERSION).expect("correct version"),
)
.ok()?;
}
// read conf if available
let script_conf_path = dirs::config_dir()?.join("irust").join(SCRIPT_CONFIG_NAME);
// ignore any error that happens while trying to read conf
// If an error happens, a new configuration will be written anyway when ScriptManager is
// dropped
let mut startup_cmds = vec![];
if let Ok(script_state) =
mtry!(toml::from_str(&std::fs::read_to_string(script_conf_path)?)?)
{
// type inference
let script_state: HashMap<String, bool> = script_state;
sm.scripts_mut().iter_mut().for_each(|script| {
let script_name = &script.metadata().name;
if let Some(state) = script_state.get(script_name) {
if *state {
script.activate();
// Trigger startup hook, in case the script needs to be aware of it
if script.is_listening_for::<irust_api::Startup>() {
startup_cmds.push(script.trigger(&irust_api::Startup()));
}
} else {
script.deactivate();
}
}
})
}
Some(ScriptManager { sm, startup_cmds })
}
}
impl Drop for ScriptManager {
fn drop(&mut self) {
let mut script_state = HashMap::new();
for script in self.sm.scripts() {
script_state.insert(script.metadata().name.clone(), script.is_active());
}
// Ignore errors on drop
let _ = mtry!({
let script_conf_path = dirs::config_dir()
.ok_or("could not find config directory")?
.join("irust")
.join(SCRIPT_CONFIG_NAME);
std::fs::write(script_conf_path, toml::to_string(&script_state)?)
});
}
}
/* NOTE: Toml: serilizing tuple struct is not working?
#[derive(Serialize, Deserialize, Debug)]
struct ScriptState(HashMap<String, bool>);
*/
impl Script for ScriptManager {
fn input_prompt(&mut self, global_variables: &GlobalVariables) -> Option<String> {
self.sm
.trigger(irust_api::SetInputPrompt(global_variables.clone()))
.next()?
.ok()
}
fn get_output_prompt(&mut self, global_variables: &GlobalVariables) -> Option<String> {
self.sm
.trigger(irust_api::SetOutputPrompt(global_variables.clone()))
.next()?
.ok()
}
fn before_compiling(&mut self, global_variables: &GlobalVariables) -> Option<()> {
self.sm
.trigger(irust_api::BeforeCompiling(global_variables.clone()))
.collect::<Result<_, _>>()
.ok()
}
fn after_compiling(&mut self, global_variables: &GlobalVariables) -> Option<()> {
self.sm
.trigger(irust_api::AfterCompiling(global_variables.clone()))
.collect::<Result<_, _>>()
.ok()
}
fn input_event_hook(
&mut self,
global_variables: &GlobalVariables,
event: Event,
) -> Option<Command> {
self.sm
.trigger(irust_api::InputEvent(global_variables.clone(), event))
.next()?
.ok()?
}
fn output_event_hook(
&mut self,
input: &str,
global_variables: &GlobalVariables,
) -> Option<Command> {
self.sm
.trigger(irust_api::OutputEvent(
global_variables.clone(),
input.to_string(),
))
.next()?
.ok()?
}
fn trigger_set_title_hook(&mut self) -> Option<String> {
self.sm.trigger(irust_api::SetTitle()).next()?.ok()?
}
fn trigger_set_msg_hook(&mut self) -> Option<String> {
self.sm.trigger(irust_api::SetWelcomeMsg()).next()?.ok()?
}
fn list(&self) -> Option<String> {
let mut scripts: Vec<String> = self
.sm
.scripts()
.iter()
.map(|script| {
let meta = script.metadata();
format!(
"{}\t{:?}\t{:?}\t{}",
&meta.name,
&meta.script_type,
&meta.hooks,
script.is_active()
)
})
.collect();
//header
scripts.insert(0, "Name\tScriptType\tHooks\tState".into());
Some(scripts.join("\n"))
}
fn activate(&mut self, script_name: &str) -> Result<Option<Command>, &'static str> {
if let Some(script) = self
.sm
.scripts_mut()
.iter_mut()
.find(|script| script.metadata().name == script_name)
{
script.activate();
// We send a startup message in case the script is listening for one
if let Ok(maybe_command) = script.trigger(&irust_api::Startup()) {
Ok(maybe_command)
} else {
Ok(None)
}
} else {
Err("Script not found")
}
}
fn deactivate(&mut self, script_name: &str) -> Result<Option<Command>, &'static str> {
if let Some(script) = self
.sm
.scripts_mut()
.iter_mut()
.find(|script| script.metadata().name == script_name)
{
script.deactivate();
// We send a shutdown message in case the script is listening for one
if let Ok(maybe_command) = script.trigger(&irust_api::Shutdown()) {
Ok(maybe_command)
} else {
Ok(None)
}
} else {
Err("Script not found")
}
}
fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>> {
self.startup_cmds.drain(..).collect()
}
fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>> {
self.sm
.scripts_mut()
.iter_mut()
.filter(|script| script.is_listening_for::<irust_api::Shutdown>())
.map(|script| script.trigger(&irust_api::Shutdown()))
.collect()
}
}
|
//! Группа унификации плит или фундаментных плит
use crate::sig::rab_e::*;
use crate::sig::HasWrite;
use nom::{bytes::complete::take, multi::count, number::complete::le_u16, IResult};
use std::fmt;
#[derive(Debug)]
pub struct UnificationSlab {
unification_group: u16, //Номер группы унификаций
amount: u16, //Количество элементов в группе унификаций
//40b WS
elements: Vec<u16>, //Вектор номеров элементов в группе
ws: Vec<u8>, //40b
}
impl HasWrite for UnificationSlab {
fn write(&self) -> Vec<u8> {
let mut out: Vec<u8> = vec![];
out.extend(&self.unification_group.to_le_bytes());
out.extend(&self.amount.to_le_bytes());
out.extend(&self.ws[0..40]);
for i in &self.elements {
out.extend(&i.to_le_bytes());
}
out
}
fn name(&self) -> &str {
""
}
}
impl fmt::Display for UnificationSlab {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"group: {}, amount: {}",
&self.unification_group, &self.amount
)
}
}
pub fn read_unification_slab(i: &[u8]) -> IResult<&[u8], UnificationSlab> {
let (i, unification_group) = le_u16(i)?;
let (i, amount) = le_u16(i)?;
let (i, ws) = take(40u8)(i)?; //40b WS
let (i, elements) = count(le_u16, amount as usize)(i)?;
let ws = ws.to_vec();
Ok((
i,
UnificationSlab {
unification_group,
amount,
elements,
ws,
},
))
}
#[cfg(test)]
fn test_unification_slab(path_str: &str) {
use crate::tests::rab_e_sig_test::read_test_sig;
let original_in = read_test_sig(path_str);
let (_, unification) =
read_unification_slab(&original_in).expect("couldn't read_unification_slab");
assert_eq!(original_in, unification.write());
}
#[test]
fn unification_test() {
test_unification_slab("test_sig/unification_slabs/uni.test");
}
#[test]
fn unification_11el_test() {
test_unification_slab("test_sig/unification_slabs/uni_11el.test");
}
#[test]
fn s_unification_slab_full_value_test() {
use crate::tests::rab_e_sig_test::read_test_sig;
let original_in = read_test_sig("test_sig/unification_slabs/S_uni.test");
let (_, unification) =
read_unification_slab(&original_in).expect("couldn't read_unification_slab");
let mut ws = vec![];
for i in 1..=40 {
ws.push(i);
}
let c_unification = UnificationSlab {
unification_group: 1u16,
amount: 2u16,
elements: vec![0u16, 1u16],
ws,
};
assert_eq!(unification.write(), c_unification.write())
}
|
//= {
//= "output": {
//= "2": [
//= "thread 'main' panicked at 'qwertyuiop', tests/a\\.rs:[0-9]+:[0-9]+\n",
//= true
//= ],
//= "1": [
//= "",
//= true
//= ]
//= },
//= "children": [],
//= "exit": {
//= "Error": {
//= "Unix": {
//= "Signal": "SIGABRT"
//= }
//= }
//= }
//= }
#![deny(warnings, deprecated)]
extern crate constellation;
extern crate nix;
use constellation::*;
use std::{panic, process, thread};
fn main() {
init(Resources {
mem: 20 * 1024 * 1024,
..Resources::default()
});
panic::set_hook(Box::new(|info| {
eprintln!("thread '{}' {}", thread::current().name().unwrap(), info);
let err = unsafe {
nix::libc::setrlimit(
nix::libc::RLIMIT_CORE,
&nix::libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
},
)
};
assert_eq!(err, 0);
process::abort()
}));
panic!("qwertyuiop");
}
|
use oxygengine_composite_renderer::{
component::{
CompositeCamera, CompositeCameraAlignment, CompositeRenderAlpha, CompositeRenderLayer,
CompositeRenderable, CompositeScalingMode, CompositeScalingTarget, CompositeTransform,
CompositeUiElement, CompositeVisibility, UiElementType, UiImage, UiMargin,
},
composite_renderer::{Command, Image, Renderable, Text},
math::{Color, Mat2d, Vec2},
resource::{CompositeCameraCache, CompositeUiInteractibles},
};
use oxygengine_core::{
app::AppBuilder,
assets::{
asset::AssetId,
database::AssetsDatabase,
protocol::{AssetLoadResult, AssetProtocol},
},
ecs::{
world::{Builder, EntitiesRes},
Component, Entity, Join, LazyUpdate, Read, ReadExpect, System, VecStorage, Write,
WriteStorage,
},
hierarchy::{Name, Tag},
prefab::{Prefab, PrefabError, PrefabManager, PrefabProxy},
state::StateToken,
Ignite, Scalar,
};
use oxygengine_input::resource::InputController;
use oxygengine_visual_novel::resource::VnStoryManager;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "scalar64"))]
use std::f32::consts::PI;
#[cfg(feature = "scalar64")]
use std::f64::consts::PI;
use std::{collections::HashMap, str::from_utf8};
pub mod prelude {
pub use crate::*;
}
pub fn bundle_installer(builder: &mut AppBuilder, _: ()) {
builder.install_resource(VnRenderingManager::default());
builder.install_system(
ApplyVisualNovelToCompositeRenderer::default(),
"apply-visual-novel-to-composite-renderer",
&["vn-story"],
);
}
pub fn protocols_installer(database: &mut AssetsDatabase) {
database.register(VnRenderingConfigAssetProtocol);
}
pub fn prefabs_installer(prefabs: &mut PrefabManager) {
prefabs.register_component_factory_proxy::<PositionCameraAlignment, PositionCameraAlignmentPrefabProxy>("PositionCameraAlignment");
}
#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub enum VnRenderingOverlayStyle {
Color(Color),
Image(String),
}
impl Default for VnRenderingOverlayStyle {
fn default() -> Self {
Self::Color(Color::black())
}
}
#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct VnRenderingConfig {
#[serde(default = "VnRenderingConfig::default_background_camera_scaling_target")]
pub background_camera_scaling_target: CompositeScalingTarget,
#[serde(default = "VnRenderingConfig::default_background_camera_resolution")]
pub background_camera_resolution: Scalar,
#[serde(default = "VnRenderingConfig::default_background_camera_layer")]
pub background_camera_layer: usize,
#[serde(default = "VnRenderingConfig::default_characters_camera_scaling_target")]
pub characters_camera_scaling_target: CompositeScalingTarget,
#[serde(default = "VnRenderingConfig::default_characters_camera_resolution")]
pub characters_camera_resolution: Scalar,
#[serde(default = "VnRenderingConfig::default_characters_camera_layer")]
pub characters_camera_layer: usize,
#[serde(default = "VnRenderingConfig::default_ui_camera_scaling_target")]
pub ui_camera_scaling_target: CompositeScalingTarget,
#[serde(default = "VnRenderingConfig::default_ui_camera_resolution")]
pub ui_camera_resolution: Scalar,
#[serde(default = "VnRenderingConfig::default_ui_camera_layer")]
pub ui_camera_layer: usize,
#[serde(default)]
pub overlay_style: VnRenderingOverlayStyle,
#[serde(default)]
pub hide_on_story_pause: bool,
#[serde(default)]
pub ui_component_template: Option<CompositeUiElement>,
#[serde(default)]
pub ui_dialogue_option_component_template: Option<CompositeUiElement>,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_default_theme")]
pub ui_dialogue_default_theme: Option<String>,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_panel_path")]
pub ui_dialogue_panel_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_text_path")]
pub ui_dialogue_text_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_name_path")]
pub ui_dialogue_name_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_skip_path")]
pub ui_dialogue_skip_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_options_path")]
pub ui_dialogue_options_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_option_text_path")]
pub ui_dialogue_option_text_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_option_button_path")]
pub ui_dialogue_option_button_path: String,
#[serde(default = "VnRenderingConfig::default_ui_dialogue_default_name_color")]
pub ui_dialogue_default_name_color: Color,
#[serde(default = "VnRenderingConfig::default_input_pointer_trigger")]
pub input_pointer_trigger: String,
#[serde(default = "VnRenderingConfig::default_input_pointer_axis_x")]
pub input_pointer_axis_x: String,
#[serde(default = "VnRenderingConfig::default_input_pointer_axis_y")]
pub input_pointer_axis_y: String,
#[serde(default)]
pub pointer_image: Option<String>,
#[serde(default)]
pub pointer_align: Vec2,
#[serde(default = "VnRenderingConfig::default_forced_constant_refresh")]
pub forced_constant_refresh: bool,
}
impl Default for VnRenderingConfig {
fn default() -> Self {
Self {
background_camera_scaling_target: Self::default_background_camera_scaling_target(),
background_camera_resolution: 1080.0,
background_camera_layer: 1000,
characters_camera_scaling_target: Self::default_characters_camera_scaling_target(),
characters_camera_resolution: Self::default_characters_camera_resolution(),
characters_camera_layer: Self::default_characters_camera_layer(),
ui_camera_scaling_target: Self::default_ui_camera_scaling_target(),
ui_camera_resolution: Self::default_ui_camera_resolution(),
ui_camera_layer: Self::default_ui_camera_layer(),
overlay_style: Default::default(),
hide_on_story_pause: false,
ui_component_template: None,
ui_dialogue_option_component_template: None,
ui_dialogue_default_theme: Self::default_ui_dialogue_default_theme(),
ui_dialogue_panel_path: Self::default_ui_dialogue_panel_path(),
ui_dialogue_text_path: Self::default_ui_dialogue_text_path(),
ui_dialogue_name_path: Self::default_ui_dialogue_name_path(),
ui_dialogue_skip_path: Self::default_ui_dialogue_skip_path(),
ui_dialogue_options_path: Self::default_ui_dialogue_options_path(),
ui_dialogue_option_text_path: Self::default_ui_dialogue_option_text_path(),
ui_dialogue_option_button_path: Self::default_ui_dialogue_option_button_path(),
ui_dialogue_default_name_color: Self::default_ui_dialogue_default_name_color(),
input_pointer_trigger: Self::default_input_pointer_trigger(),
input_pointer_axis_x: Self::default_input_pointer_axis_x(),
input_pointer_axis_y: Self::default_input_pointer_axis_y(),
pointer_image: None,
pointer_align: Default::default(),
forced_constant_refresh: Self::default_forced_constant_refresh(),
}
}
}
impl VnRenderingConfig {
fn default_background_camera_scaling_target() -> CompositeScalingTarget {
CompositeScalingTarget::BothMinimum
}
fn default_background_camera_resolution() -> Scalar {
1080.0
}
fn default_background_camera_layer() -> usize {
1000
}
fn default_characters_camera_scaling_target() -> CompositeScalingTarget {
CompositeScalingTarget::Height
}
fn default_characters_camera_resolution() -> Scalar {
1080.0
}
fn default_characters_camera_layer() -> usize {
1001
}
fn default_ui_camera_scaling_target() -> CompositeScalingTarget {
CompositeScalingTarget::Both
}
fn default_ui_camera_resolution() -> Scalar {
1080.0
}
fn default_ui_camera_layer() -> usize {
1002
}
#[allow(clippy::unnecessary_wraps)]
fn default_ui_dialogue_default_theme() -> Option<String> {
Some("default".to_owned())
}
fn default_ui_dialogue_panel_path() -> String {
"panel".to_owned()
}
fn default_ui_dialogue_text_path() -> String {
"panel/text".to_owned()
}
fn default_ui_dialogue_name_path() -> String {
"panel/name".to_owned()
}
fn default_ui_dialogue_skip_path() -> String {
"panel/skip".to_owned()
}
fn default_ui_dialogue_options_path() -> String {
"panel/options".to_owned()
}
fn default_ui_dialogue_option_text_path() -> String {
"button/text".to_owned()
}
fn default_ui_dialogue_option_button_path() -> String {
"button".to_owned()
}
fn default_ui_dialogue_default_name_color() -> Color {
Color::white()
}
fn default_input_pointer_trigger() -> String {
"mouse-left".to_owned()
}
fn default_input_pointer_axis_x() -> String {
"mouse-x".to_owned()
}
fn default_input_pointer_axis_y() -> String {
"mouse-y".to_owned()
}
fn default_forced_constant_refresh() -> bool {
true
}
}
impl Prefab for VnRenderingConfig {}
pub struct VnRenderingConfigAsset(VnRenderingConfig);
impl VnRenderingConfigAsset {
pub fn config(&self) -> &VnRenderingConfig {
&self.0
}
}
pub struct VnRenderingConfigAssetProtocol;
impl AssetProtocol for VnRenderingConfigAssetProtocol {
fn name(&self) -> &str {
"vn-rendering"
}
fn on_load(&mut self, data: Vec<u8>) -> AssetLoadResult {
let data = from_utf8(&data).unwrap();
match VnRenderingConfig::from_prefab_str(&data) {
Ok(result) => AssetLoadResult::Data(Box::new(VnRenderingConfigAsset(result))),
Err(error) => AssetLoadResult::Error(format!(
"Error loading visual novel rendering config asset: {:?}",
error
)),
}
}
}
#[derive(Debug, Clone)]
pub struct VnStoryRenderer {
background_camera: Entity,
characters_camera: Entity,
ui_camera: Entity,
characters: HashMap<String, Entity>,
background: Entity,
dialogue_ui_element: Entity,
dialogue_option_template: CompositeUiElement,
overlay: Entity,
pointer: Option<Entity>,
}
#[derive(Debug, Clone)]
pub enum VnRenderingManagerError {
RenderingConfigNotFound(String),
}
#[derive(Debug, Default, Clone)]
pub struct VnRenderingManager {
configs: HashMap<String, VnRenderingConfig>,
stories: HashMap<String, VnStoryRenderer>,
active_config: VnRenderingConfig,
dirty_config: bool,
}
impl VnRenderingManager {
pub fn config(&self) -> &VnRenderingConfig {
&self.active_config
}
pub fn register_config(&mut self, name: &str, config: VnRenderingConfig) {
self.configs.insert(name.to_owned(), config);
}
pub fn unregister_config(&mut self, name: &str) -> Option<VnRenderingConfig> {
self.configs.remove(name)
}
pub fn select_config(&mut self, name: &str) -> Result<(), VnRenderingManagerError> {
if let Some(config) = self.configs.get(name) {
self.active_config = config.clone();
self.dirty_config = true;
Ok(())
} else {
Err(VnRenderingManagerError::RenderingConfigNotFound(
name.to_owned(),
))
}
}
pub fn use_default_config(&mut self) {
self.active_config = Default::default();
self.dirty_config = true;
}
}
#[derive(Ignite, Debug, Clone, Copy)]
pub struct PositionCameraAlignment(pub Entity, pub Vec2);
impl Component for PositionCameraAlignment {
type Storage = VecStorage<Self>;
}
impl PrefabProxy<PositionCameraAlignmentPrefabProxy> for PositionCameraAlignment {
fn from_proxy_with_extras(
proxy: PositionCameraAlignmentPrefabProxy,
named_entities: &HashMap<String, Entity>,
_: StateToken,
) -> Result<Self, PrefabError> {
if let Some(entity) = named_entities.get(&proxy.0) {
Ok(Self(*entity, proxy.1))
} else {
Err(PrefabError::Custom(format!(
"Could not find entity named: {}",
proxy.0
)))
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PositionCameraAlignmentPrefabProxy(String, Vec2);
impl Prefab for PositionCameraAlignmentPrefabProxy {}
#[derive(Debug, Default)]
pub struct ApplyVisualNovelToCompositeRenderer {
config_table: HashMap<AssetId, String>,
dialogue_options_focus_phases: Vec<Scalar>,
}
impl<'s> System<'s> for ApplyVisualNovelToCompositeRenderer {
#[allow(clippy::type_complexity)]
type SystemData = (
Read<'s, EntitiesRes>,
Read<'s, LazyUpdate>,
ReadExpect<'s, AssetsDatabase>,
Write<'s, VnStoryManager>,
Read<'s, CompositeCameraCache>,
Read<'s, CompositeUiInteractibles>,
Read<'s, InputController>,
Write<'s, VnRenderingManager>,
WriteStorage<'s, CompositeRenderable>,
WriteStorage<'s, CompositeVisibility>,
WriteStorage<'s, CompositeRenderAlpha>,
WriteStorage<'s, CompositeTransform>,
WriteStorage<'s, PositionCameraAlignment>,
WriteStorage<'s, CompositeUiElement>,
);
// TODO: REFACTOR THIS SHIT
#[allow(clippy::cognitive_complexity)]
#[allow(clippy::many_single_char_names)]
fn run(
&mut self,
(
entities,
lazy_update,
assets,
mut stories,
camera_cache,
interactibles,
input,
mut rendering,
mut renderables,
mut visibilities,
mut alphas,
mut transforms,
mut alignments,
mut ui_elements,
): Self::SystemData,
) {
for id in assets.lately_unloaded_protocol("vn-rendering") {
if let Some(path) = self.config_table.remove(id) {
rendering.unregister_config(&path);
}
}
for id in assets.lately_loaded_protocol("vn-rendering") {
let id = *id;
let asset = assets
.asset_by_id(id)
.expect("trying to use not loaded visual novel rendering config asset");
let path = asset.path().to_owned();
let asset = asset
.get::<VnRenderingConfigAsset>()
.expect("trying to use non visual novel rendering config asset");
let config = asset.config().clone();
rendering.register_config(&path, config);
self.config_table.insert(id, path);
}
let config_changed = rendering.dirty_config;
rendering.dirty_config = false;
let to_remove = if config_changed {
stories.stories_names().collect::<Vec<_>>()
} else {
stories.lately_unregistered().collect::<Vec<_>>()
};
for id in to_remove {
if let Some(story) = rendering.stories.remove(id) {
drop(entities.delete(story.background_camera));
drop(entities.delete(story.characters_camera));
drop(entities.delete(story.ui_camera));
for entity in story.characters.values() {
drop(entities.delete(*entity));
}
drop(entities.delete(story.background));
drop(entities.delete(story.dialogue_ui_element));
drop(entities.delete(story.overlay));
if let Some(pointer) = story.pointer {
drop(entities.delete(pointer));
}
}
}
let to_add = if config_changed {
stories.stories_names().collect::<Vec<_>>()
} else {
stories.lately_registered().collect::<Vec<_>>()
};
for id in to_add {
if let Some(story) = stories.get(id) {
let background_camera = lazy_update
.create_entity(&entities)
.with(Name(format!("vn-camera-background-{}", id).into()))
.with(
CompositeCamera::with_scaling_target(
CompositeScalingMode::CenterAspect,
rendering.config().background_camera_scaling_target,
)
.tag(format!("vn-background-{}", id).into()),
)
.with(CompositeVisibility(false))
.with(CompositeRenderLayer(
rendering.config().background_camera_layer,
))
.with(CompositeTransform::scale(
rendering.config().background_camera_resolution.into(),
))
.build();
let characters_camera = lazy_update
.create_entity(&entities)
.with(Name(format!("vn-camera-characters-{}", id).into()))
.with(
CompositeCamera::with_scaling_target(
CompositeScalingMode::CenterAspect,
rendering.config().characters_camera_scaling_target,
)
.tag(format!("vn-characters-{}", id).into()),
)
.with(CompositeVisibility(false))
.with(CompositeRenderLayer(
rendering.config().characters_camera_layer,
))
.with(CompositeTransform::scale(
rendering.config().characters_camera_resolution.into(),
))
.build();
let ui_camera = lazy_update
.create_entity(&entities)
.with(Name(format!("vn-camera-ui-{}", id).into()))
.with(
CompositeCamera::with_scaling_target(
CompositeScalingMode::Aspect,
rendering.config().ui_camera_scaling_target,
)
.tag(format!("vn-ui-{}", id).into()),
)
.with(CompositeVisibility(false))
.with(CompositeRenderLayer(rendering.config().ui_camera_layer))
.with(CompositeTransform::scale(
rendering.config().ui_camera_resolution.into(),
))
.build();
let characters = story
.characters()
.map(|(n, _)| {
let entity = lazy_update
.create_entity(&entities)
.with(Tag(format!("vn-characters-{}", id).into()))
.with(Name(format!("vn-character-{}-{}", id, n).into()))
.with(CompositeRenderAlpha(0.0))
.with(CompositeRenderLayer(1))
.with(CompositeRenderable(().into()))
.with(PositionCameraAlignment(characters_camera, 0.0.into()))
.with(CompositeTransform::default())
.build();
(n.to_owned(), entity)
})
.collect::<HashMap<_, _>>();
let background = lazy_update
.create_entity(&entities)
.with(Tag(format!("vn-background-{}", id).into()))
.with(Name(format!("vn-background-{}", id).into()))
.with(CompositeRenderable(().into()))
.with(CompositeTransform::default())
.build();
let ui_element =
if let Some(mut component) = rendering.config().ui_component_template.clone() {
component.camera_name = format!("vn-camera-ui-{}", id).into();
if let Some(child) =
component.find_mut(&rendering.config().ui_dialogue_panel_path)
{
child.interactive = Some(format!("vn-ui-panel-{}", id).into());
}
if let Some(child) =
component.find_mut(&rendering.config().ui_dialogue_text_path)
{
child.interactive = Some(format!("vn-ui-text-{}", id).into());
}
if let Some(child) =
component.find_mut(&rendering.config().ui_dialogue_name_path)
{
child.interactive = Some(format!("vn-ui-name-{}", id).into());
}
if let Some(child) =
component.find_mut(&rendering.config().ui_dialogue_skip_path)
{
child.interactive = Some(format!("vn-ui-skip-{}", id).into());
}
component
} else {
let mut text = CompositeUiElement::default();
text.id = Some("text".into());
text.theme = rendering
.config()
.ui_dialogue_default_theme
.as_ref()
.map(|theme| format!("{}@text", theme).into());
text.interactive = Some(format!("vn-ui-text-{}", id).into());
text.element_type = UiElementType::Text(
Text::new_owned("Verdana".to_owned(), "".to_owned())
.size(48.0)
.color(Color::white()),
);
text.padding = UiMargin {
left: 64.0,
right: 64.0,
top: 64.0,
bottom: 0.0,
};
text.left_anchor = 0.0.into();
text.right_anchor = 1.0.into();
text.top_anchor = 0.0.into();
text.bottom_anchor = 1.0.into();
let mut name = CompositeUiElement::default();
name.id = Some("name".into());
name.theme = rendering
.config()
.ui_dialogue_default_theme
.as_ref()
.map(|theme| format!("{}@name", theme).into());
name.element_type = UiElementType::Text(
Text::new_owned("Verdana".to_owned(), "".to_owned())
.size(32.0)
.color(Color::white()),
);
name.interactive = Some(format!("vn-ui-name-{}", id).into());
name.padding = UiMargin {
left: 32.0,
right: 32.0,
top: 32.0,
bottom: 0.0,
};
name.left_anchor = 0.0.into();
name.right_anchor = 1.0.into();
name.top_anchor = 0.0.into();
name.bottom_anchor = 0.0.into();
name.alignment = (0.0.into(), 0.0.into()).into();
name.fixed_height = Some(64.0.into());
let mut options = CompositeUiElement::default();
options.id = Some("options".into());
options.element_type = UiElementType::None;
options.left_anchor = 0.0.into();
options.right_anchor = 1.0.into();
options.top_anchor = 0.0.into();
options.bottom_anchor = 0.0.into();
options.alignment = (0.0.into(), 1.0.into()).into();
let mut panel = CompositeUiElement::default();
panel.id = Some("panel".into());
panel.theme = rendering
.config()
.ui_dialogue_default_theme
.as_ref()
.map(|theme| format!("{}@panel", theme).into());
panel.interactive = Some(format!("vn-ui-panel-{}", id).into());
panel.element_type = UiElementType::Image(Box::new(UiImage::default()));
panel.padding = UiMargin {
left: 128.0,
right: 128.0,
top: 0.0,
bottom: 32.0,
};
panel.left_anchor = 0.0.into();
panel.right_anchor = 1.0.into();
panel.top_anchor = 1.0.into();
panel.bottom_anchor = 1.0.into();
panel.alignment = (0.0.into(), 1.0.into()).into();
panel.fixed_height = Some(256.0.into());
panel.children = vec![text, name, options];
let mut root = CompositeUiElement::default();
root.camera_name = format!("vn-camera-ui-{}", id).into();
root.element_type = UiElementType::None;
root.left_anchor = 0.0.into();
root.right_anchor = 1.0.into();
root.top_anchor = 0.0.into();
root.bottom_anchor = 1.0.into();
root.children = vec![panel];
root
};
let dialogue_ui_element = lazy_update
.create_entity(&entities)
.with(Tag(format!("vn-ui-{}", id).into()))
.with(Name(format!("vn-dialogue-{}", id).into()))
.with(CompositeRenderAlpha(0.0))
.with(CompositeRenderable(().into()))
.with(ui_element)
.with(CompositeTransform::default())
.build();
let dialogue_option_template = if let Some(mut component) = rendering
.config()
.ui_dialogue_option_component_template
.clone()
{
component.left_anchor = 0.0.into();
component.right_anchor = 1.0.into();
component.top_anchor = 0.0.into();
component.bottom_anchor = 0.0.into();
component.alignment = (0.0.into(), 0.0.into()).into();
component
} else {
let mut text = CompositeUiElement::default();
text.id = Some("text".into());
text.theme = rendering
.config()
.ui_dialogue_default_theme
.as_ref()
.map(|theme| format!("{}@option-text", theme).into());
text.element_type = UiElementType::Text(
Text::new_owned("Verdana".to_owned(), "".to_owned())
.size(28.0)
.color(Color::white()),
);
text.padding = UiMargin {
left: 32.0,
right: 32.0,
top: 8.0,
bottom: 0.0,
};
text.left_anchor = 0.0.into();
text.right_anchor = 1.0.into();
text.top_anchor = 0.0.into();
text.bottom_anchor = 1.0.into();
let mut background = CompositeUiElement::default();
background.theme = rendering
.config()
.ui_dialogue_default_theme
.as_ref()
.map(|theme| format!("{}@option-background", theme).into());
background.element_type = UiElementType::Image(Box::new(UiImage::default()));
background.left_anchor = 0.0.into();
background.right_anchor = 1.0.into();
background.top_anchor = 0.0.into();
background.bottom_anchor = 1.0.into();
let mut background_focused = CompositeUiElement::default();
background_focused.theme = rendering
.config()
.ui_dialogue_default_theme
.as_ref()
.map(|theme| format!("{}@option-background-focused", theme).into());
background_focused.element_type =
UiElementType::Image(Box::new(UiImage::default()));
background_focused.left_anchor = 0.0.into();
background_focused.right_anchor = 1.0.into();
background_focused.top_anchor = 0.0.into();
background_focused.bottom_anchor = 1.0.into();
let mut button = CompositeUiElement::default();
button.id = Some("button".into());
button.element_type = UiElementType::None;
button.left_anchor = 0.0.into();
button.right_anchor = 1.0.into();
button.top_anchor = 0.0.into();
button.bottom_anchor = 1.0.into();
button.children = vec![background, background_focused, text];
let mut root = CompositeUiElement::default();
root.camera_name = format!("vn-camera-ui-{}", id).into();
root.element_type = UiElementType::None;
root.padding = UiMargin {
left: 256.0,
right: 64.0,
top: 0.0,
bottom: 8.0,
};
root.left_anchor = 0.0.into();
root.right_anchor = 1.0.into();
root.top_anchor = 0.0.into();
root.bottom_anchor = 0.0.into();
root.fixed_height = Some(48.0.into());
root.children = vec![button];
root
};
let overlay_renderable = match &rendering.config().overlay_style {
VnRenderingOverlayStyle::Color(color) => {
Renderable::FullscreenRectangle(*color)
}
VnRenderingOverlayStyle::Image(image) => {
Image::new_owned(image.to_owned()).align(0.5.into()).into()
}
};
let overlay = lazy_update
.create_entity(&entities)
.with(Tag(format!("vn-ui-{}", id).into()))
.with(Name(format!("vn-overlay-{}", id).into()))
.with(CompositeRenderAlpha(0.0))
.with(CompositeRenderLayer(1))
.with(CompositeRenderable(overlay_renderable))
.with(CompositeCameraAlignment(0.0.into()))
.with(CompositeTransform::default())
.build();
let pointer = rendering.config().pointer_image.as_ref().map(|image| {
lazy_update
.create_entity(&entities)
.with(Tag(format!("vn-ui-{}", id).into()))
.with(Name(format!("vn-pointer-{}", id).into()))
.with(CompositeRenderLayer(2))
.with(CompositeRenderable(
Image::new_owned(image.to_owned())
.align(rendering.config().pointer_align)
.into(),
))
.with(CompositeTransform::default())
.build()
});
rendering.stories.insert(
id.to_owned(),
VnStoryRenderer {
background_camera,
characters_camera,
ui_camera,
characters,
background,
dialogue_ui_element,
dialogue_option_template,
overlay,
pointer,
},
);
}
}
// apply data to renderers.
for (story_name, story_data) in &rendering.stories {
if let Some(story) = stories.get(story_name) {
let show = !story.is_paused() || !rendering.config().hide_on_story_pause;
if let Some(visibility) = visibilities.get_mut(story_data.background_camera) {
visibility.0 = show;
}
if let Some(visibility) = visibilities.get_mut(story_data.characters_camera) {
visibility.0 = show;
}
if let Some(visibility) = visibilities.get_mut(story_data.ui_camera) {
visibility.0 = show;
}
if !show {
continue;
}
let show_characters = !story.is_complete() || story.active_scene().phase() < 0.5;
let refresh = rendering.config().forced_constant_refresh;
let scene_phase = story.active_scene().phase();
let update_scene = refresh || story.active_scene().in_progress();
let scene = if scene_phase < 0.5 {
if let Some(name) = story.active_scene().from() {
story.scene(name)
} else {
None
}
} else if scene_phase > 0.5 {
if let Some(name) = story.active_scene().to() {
story.scene(name)
} else {
None
}
} else {
None
};
if update_scene {
if let Some(alpha) = alphas.get_mut(story_data.overlay) {
alpha.0 = (scene_phase * PI).sin();
}
}
let background_renderable = if let Some(scene) = &scene {
if update_scene || scene.background_style.in_progress() {
let from = story.background(scene.background_style.from());
let to = story.background(scene.background_style.to());
if let (Some(from), Some(to)) = (from, to) {
let phase = scene.background_style.phase();
let transform_prev = {
let [a, b, c, d, e, f] = Mat2d::scale(from.scale.into()).0;
Command::Transform(a, b, c, d, e, f)
};
let transform_next = {
let [a, b, c, d, e, f] = Mat2d::scale(to.scale.into()).0;
Command::Transform(a, b, c, d, e, f)
};
Some(Renderable::Commands(vec![
Command::Store,
transform_prev,
Command::Alpha(1.0 - phase),
Command::Draw(
Image::new_owned(from.image.to_owned())
.align(0.5.into())
.into(),
),
Command::Restore,
Command::Store,
transform_next,
Command::Alpha(phase),
Command::Draw(
Image::new_owned(to.image.to_owned())
.align(0.5.into())
.into(),
),
Command::Restore,
]))
} else {
Some(Renderable::None)
}
} else {
None
}
} else {
Some(Renderable::None)
};
if let Some(background_renderable) = background_renderable {
if let Some(renderable) = renderables.get_mut(story_data.background) {
renderable.0 = background_renderable;
}
}
if let Some(scene) = &scene {
if update_scene
|| scene.camera_position.in_progress()
|| scene.camera_rotation.in_progress()
{
let position = scene.camera_position.value();
let rotation = scene.camera_rotation.value();
if let Some(transform) = transforms.get_mut(story_data.background_camera) {
transform.set_translation(Vec2::new(position.0, position.1));
transform.set_rotation(rotation);
}
if let Some(transform) = transforms.get_mut(story_data.characters_camera) {
transform.set_translation(Vec2::new(position.0, position.1));
transform.set_rotation(rotation);
}
}
}
if refresh || story.active_dialogue().in_progress() {
let from = story.active_dialogue().from();
let to = story.active_dialogue().to();
let phase = story.active_dialogue().phase();
let (main_alpha, name_alpha, text, name, options) = match (from, to) {
(Some(from), Some(to)) => {
if phase < 0.5 {
(
1.0,
1.0 - phase * 2.0,
from.text.as_str(),
from.character.as_str(),
from.options.as_slice(),
)
} else {
(
1.0,
phase * 2.0,
to.text.as_str(),
to.character.as_str(),
to.options.as_slice(),
)
}
}
(None, Some(to)) => (
phase,
1.0,
to.text.as_str(),
to.character.as_str(),
to.options.as_slice(),
),
(Some(from), None) => (
1.0 - phase,
1.0,
from.text.as_str(),
from.character.as_str(),
from.options.as_slice(),
),
(None, None) => (0.0, 1.0, "", "", [].as_ref()),
};
let name_color = if let Some(c) = story.character(name) {
let color = c.name_color();
Color::rgb(
(color.0 * 255.0).max(0.0).min(255.0) as u8,
(color.1 * 255.0).max(0.0).min(255.0) as u8,
(color.2 * 255.0).max(0.0).min(255.0) as u8,
)
} else {
Color::white()
};
if let Some(alpha) = alphas.get_mut(story_data.dialogue_ui_element) {
alpha.0 = main_alpha;
}
if let Some(ui_element) = ui_elements.get_mut(story_data.dialogue_ui_element) {
let item_height =
if let Some(v) = &story_data.dialogue_option_template.fixed_height {
ui_element.calculate_value(v, &[])
} else {
0.0
};
if let Some(child) =
ui_element.find_mut(&rendering.config().ui_dialogue_options_path)
{
child.alpha = phase.into();
if options.is_empty() {
child.fixed_height = None;
child.children.clear();
child.rebuild();
} else {
child.fixed_height =
Some((item_height * options.len() as Scalar).into());
child.children.clear();
for (i, option) in options.iter().enumerate() {
let mut element = story_data.dialogue_option_template.clone();
if let Some(child) = element
.find_mut(&rendering.config().ui_dialogue_option_text_path)
{
if let UiElementType::Text(t) = &mut child.element_type {
t.text = option.text.clone().into();
}
}
let focused_phase = option.focused.phase();
if let Some(child) = element.find_mut(
&rendering.config().ui_dialogue_option_button_path,
) {
child.state.insert("focused".into(), focused_phase);
}
element.interactive =
Some(format!("vn-ui-option-{}-{}", story_name, i).into());
element.offset.y = (i as Scalar * item_height).into();
child.children.push(element);
}
child.rebuild();
}
}
if let Some(child) =
ui_element.find_mut(&rendering.config().ui_dialogue_name_path)
{
child.alpha = name_alpha.into();
if let UiElementType::Text(t) = &mut child.element_type {
t.text = name.to_owned().into();
t.color = name_color;
}
child.rebuild();
}
if let Some(child) =
ui_element.find_mut(&rendering.config().ui_dialogue_text_path)
{
if let UiElementType::Text(t) = &mut child.element_type {
t.text = text.to_owned().into();
}
child.rebuild();
}
ui_element.rebuild();
}
}
for (name, entity) in &story_data.characters {
if let Some(character) = story.character(name) {
if refresh || character.visibility_anim().in_progress() {
if let Some(alpha) = alphas.get_mut(*entity) {
alpha.0 = if show_characters {
character.visibility()
} else {
0.0
};
}
}
if refresh || character.position_anim().in_progress() {
if let Some(alignment) = alignments.get_mut(*entity) {
let pos = character.position();
alignment.1 = Vec2::new(pos.0, pos.1);
}
}
if refresh
|| character.rotation_anim().in_progress()
|| character.scale_anim().in_progress()
{
if let Some(transform) = transforms.get_mut(*entity) {
let scl = character.scale();
transform.set_rotation(character.rotation());
transform.set_scale(Vec2::new(scl.0, scl.1));
}
}
if refresh
|| character.style_transition().in_progress()
|| character.alignment_anim().in_progress()
{
let (from_style, style_phase, to_style) = character.style();
let from = character.styles.get(from_style);
let to = character.styles.get(to_style);
let character_renderable = if let (Some(from), Some(to)) = (from, to) {
let align = character.alignment();
let align = Vec2::new(align.0, align.1);
Renderable::Commands(vec![
Command::Store,
Command::Alpha(1.0 - style_phase),
Command::Draw(
Image::new_owned(from.to_owned()).align(align).into(),
),
Command::Alpha(style_phase),
Command::Draw(
Image::new_owned(to.to_owned()).align(align).into(),
),
Command::Restore,
])
} else {
Renderable::None
};
if let Some(renderable) = renderables.get_mut(*entity) {
renderable.0 = character_renderable;
}
}
} else if let Some(alpha) = alphas.get_mut(*entity) {
alpha.0 = 0.0;
}
}
}
if let Some(story) = stories.get_mut(story_name) {
let x = input.axis_or_default(&rendering.config().input_pointer_axis_x);
let y = input.axis_or_default(&rendering.config().input_pointer_axis_y);
let point = [x, y].into();
if let Some(pos) = camera_cache.screen_to_world_space(story_data.ui_camera, point) {
if let Some(pointer) = &story_data.pointer {
if let Some(transform) = transforms.get_mut(*pointer) {
transform.set_translation(pos);
}
}
if story.is_waiting_for_dialogue_option_selection()
&& story.active_dialogue().is_complete()
{
let dialogue = story.active_dialogue().to();
if let Some(dialogue) = dialogue {
let mut selected = None;
let mut focused = None;
let click = input
.trigger_or_default(&rendering.config().input_pointer_trigger)
.is_pressed();
for i in 0..dialogue.options.len() {
if interactibles.does_rect_contains_point(
&format!("vn-ui-option-{}-{}", story_name, i),
pos,
) {
focused = Some(i);
if click {
selected = Some(i);
}
}
}
drop(story.focus_dialogue_option(focused));
if let Some(selected) = selected {
drop(story.select_dialogue_option(selected));
}
}
}
}
}
}
for (transform, alignment) in (&mut transforms, &alignments).join() {
if let Some(size) = camera_cache.calculate_world_size(alignment.0) {
transform.set_translation(alignment.1 * size);
}
}
}
}
|
use std::fmt::{Debug, Display};
use std::sync::Arc;
use async_trait::async_trait;
use parquet_file::ParquetFilePath;
use uuid::Uuid;
pub mod noop;
pub mod prod;
mod util;
#[cfg(test)]
mod test_util;
/// Create a [`Scratchpad`] for use as intermediate storage
pub trait ScratchpadGen: Debug + Display + Send + Sync {
fn pad(&self) -> Arc<dyn Scratchpad>;
}
/// An intermediate in-memory store (can be a disk later if we want)
/// to stage all inputs and outputs of the compaction. The reasons
/// are:
///
/// **fewer IO ops:** DataFusion's streaming IO requires slightly more IO
/// requests (at least 2 per file) due to the way it is optimized to
/// read as little as possible. It first reads the metadata and then
/// decides which content to fetch. In the compaction case this is
/// (esp. w/o delete predicates) EVERYTHING. So in contrast to the
/// querier, there is no advantage of this approach. In contrary this
/// easily adds 100ms latency to every single input file.
///
/// **less traffic**: For divide&conquer partitions (i.e. when we need
/// to run multiple compaction steps to deal with them) it is kinda
/// pointless to upload an intermediate result just to download it
/// again. The scratchpad avoids that.
///
/// **higher throughput**: We want to limit the number of concurrent
/// DataFusion jobs because we don't wanna blow up the whole process
/// by having too much in-flight arrow data at the same time. However
/// while we perform the actual computation, we were waiting for
/// object store IO. This was limiting our throughput substantially.
///
/// **shadow mode**: De-coupling the stores in this way makes it easier
/// to implement compactor: shadow mode #6645. Shadow mode relies on
/// leaving the compaction output in the scratchpad so
/// `clean_written_from_scratchpad` is a no-op for shadow mode.
///
/// Note that we assume here that the input parquet files are WAY
/// SMALLER than the uncompressed Arrow data during compaction itself.
#[async_trait]
pub trait Scratchpad: Debug + Send + Sync + 'static {
fn uuids(&self, files: &[ParquetFilePath]) -> Vec<Uuid>;
async fn load_to_scratchpad(&self, files: &[ParquetFilePath]) -> Vec<Uuid>;
async fn make_public(&self, files: &[ParquetFilePath]) -> Vec<Uuid>;
async fn clean_from_scratchpad(&self, files: &[ParquetFilePath]);
async fn clean_written_from_scratchpad(&self, files: &[ParquetFilePath]);
async fn clean(&self);
}
|
use ted_interface::*;
use id_types::*;
pub struct Drawn{
pub id: u32,
pub mover_id: MoverID,
pub sprite: EntitySprite,
pub invisible: bool
}
pub struct BasicDrawn{
pub drawn_id: DrawnID,
pub sprite: u32
}
pub struct HealthDrawn{
pub drawn_id: DrawnID,
pub damageable_id: DamageableID,
pub sprite: u32
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Instruction and Data Tightly-Coupled Memory Control Registers"]
pub itcmcr: ITCMCR,
#[doc = "0x04 - Instruction and Data Tightly-Coupled Memory Control Registers"]
pub dtcmcr: DTCMCR,
#[doc = "0x08 - AHBP Control register"]
pub ahbpcr: AHBPCR,
#[doc = "0x0c - Auxiliary Cache Control register"]
pub cacr: CACR,
#[doc = "0x10 - AHB Slave Control register"]
pub ahbscr: AHBSCR,
_reserved5: [u8; 4usize],
#[doc = "0x18 - Auxiliary Bus Fault Status register"]
pub abfsr: ABFSR,
}
#[doc = "Instruction and Data Tightly-Coupled Memory Control Registers\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [itcmcr](itcmcr) module"]
pub type ITCMCR = crate::Reg<u32, _ITCMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ITCMCR;
#[doc = "`read()` method returns [itcmcr::R](itcmcr::R) reader structure"]
impl crate::Readable for ITCMCR {}
#[doc = "`write(|w| ..)` method takes [itcmcr::W](itcmcr::W) writer structure"]
impl crate::Writable for ITCMCR {}
#[doc = "Instruction and Data Tightly-Coupled Memory Control Registers"]
pub mod itcmcr;
#[doc = "Instruction and Data Tightly-Coupled Memory Control Registers\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dtcmcr](dtcmcr) module"]
pub type DTCMCR = crate::Reg<u32, _DTCMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DTCMCR;
#[doc = "`read()` method returns [dtcmcr::R](dtcmcr::R) reader structure"]
impl crate::Readable for DTCMCR {}
#[doc = "`write(|w| ..)` method takes [dtcmcr::W](dtcmcr::W) writer structure"]
impl crate::Writable for DTCMCR {}
#[doc = "Instruction and Data Tightly-Coupled Memory Control Registers"]
pub mod dtcmcr;
#[doc = "AHBP Control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahbpcr](ahbpcr) module"]
pub type AHBPCR = crate::Reg<u32, _AHBPCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AHBPCR;
#[doc = "`read()` method returns [ahbpcr::R](ahbpcr::R) reader structure"]
impl crate::Readable for AHBPCR {}
#[doc = "`write(|w| ..)` method takes [ahbpcr::W](ahbpcr::W) writer structure"]
impl crate::Writable for AHBPCR {}
#[doc = "AHBP Control register"]
pub mod ahbpcr;
#[doc = "Auxiliary Cache Control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cacr](cacr) module"]
pub type CACR = crate::Reg<u32, _CACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CACR;
#[doc = "`read()` method returns [cacr::R](cacr::R) reader structure"]
impl crate::Readable for CACR {}
#[doc = "`write(|w| ..)` method takes [cacr::W](cacr::W) writer structure"]
impl crate::Writable for CACR {}
#[doc = "Auxiliary Cache Control register"]
pub mod cacr;
#[doc = "AHB Slave Control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahbscr](ahbscr) module"]
pub type AHBSCR = crate::Reg<u32, _AHBSCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AHBSCR;
#[doc = "`read()` method returns [ahbscr::R](ahbscr::R) reader structure"]
impl crate::Readable for AHBSCR {}
#[doc = "`write(|w| ..)` method takes [ahbscr::W](ahbscr::W) writer structure"]
impl crate::Writable for AHBSCR {}
#[doc = "AHB Slave Control register"]
pub mod ahbscr;
#[doc = "Auxiliary Bus Fault Status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [abfsr](abfsr) module"]
pub type ABFSR = crate::Reg<u32, _ABFSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ABFSR;
#[doc = "`read()` method returns [abfsr::R](abfsr::R) reader structure"]
impl crate::Readable for ABFSR {}
#[doc = "`write(|w| ..)` method takes [abfsr::W](abfsr::W) writer structure"]
impl crate::Writable for ABFSR {}
#[doc = "Auxiliary Bus Fault Status register"]
pub mod abfsr;
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Devices_Spi_Provider")]
pub mod Provider;
#[link(name = "windows")]
extern "system" {}
pub type ISpiDeviceStatics = *mut ::core::ffi::c_void;
pub type SpiBusInfo = *mut ::core::ffi::c_void;
pub type SpiConnectionSettings = *mut ::core::ffi::c_void;
pub type SpiController = *mut ::core::ffi::c_void;
pub type SpiDevice = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SpiMode(pub i32);
impl SpiMode {
pub const Mode0: Self = Self(0i32);
pub const Mode1: Self = Self(1i32);
pub const Mode2: Self = Self(2i32);
pub const Mode3: Self = Self(3i32);
}
impl ::core::marker::Copy for SpiMode {}
impl ::core::clone::Clone for SpiMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SpiSharingMode(pub i32);
impl SpiSharingMode {
pub const Exclusive: Self = Self(0i32);
pub const Shared: Self = Self(1i32);
}
impl ::core::marker::Copy for SpiSharingMode {}
impl ::core::clone::Clone for SpiSharingMode {
fn clone(&self) -> Self {
*self
}
}
|
fn testpalindrome(x: i32) -> bool{
let xstr=x.to_string();
let leng:usize = xstr.len();
let mut v=vec![];
for i in xstr.chars(){
v.push(i);
}
let mut test: bool =true;
for i in 0..v.len()-1{
if v[i as usize]==v[leng-1-i as usize]{
test=true;
}
else{
return false;
}
}
return test;
}
fn main(){
let mut largest: i32=0;
let mut i: i32=100;
let mut j: i32=100;
while j < 1000{
let test: i32 = i*j;
if testpalindrome(test)==true{
if test > largest{
largest=test;
}
}
j+=1;
if j==999{
i+=1;
j=0;
if i==999{
break;
}
}
}
println!("{}", largest);
}
|
use rocket::*;
use rocket::http::Status;
use rocket::response::NamedFile;
use rocket_contrib::json::*;
use std::collections::HashMap;
use reqwest::header::AUTHORIZATION;
use super::BASE_URL;
use super::receiver::*;
use super::guards::*;
use super::super::database::Database;
use log::{error, warn, info, debug};
lazy_static! {
static ref ACCESS_TOKEN: String = std::env::var("BOT_ACCESS_TOKEN").unwrap();
}
#[get("/")]
pub fn index() -> std::io::Result<NamedFile> {
NamedFile::open("static/index.html")
}
// PING
#[post("/", data="<_data>", rank=1)]
pub fn ping(_header: Header, _ping_header: PingHeader, _data: Json<Ping>,) -> Status {
Status::NoContent
}
// JOINED, LEFT
#[post("/", data="<_data>", rank=2)]
pub fn join_left(_header: Header, _join_left_header: JoinLeftHeader, _data: Json<JoinLeft>) -> Status {
Status::NoContent
}
// MESSAGE_CREATED
#[post("/", data="<data>", rank=3)]
pub fn message(_header: Header, _message_header: MessageHeader, data: Json<MessageCreated>, conn: Database) -> Status {
use super::functions::*;
// 投稿するメッセージ
let mut body = HashMap::new();
let command = parse_command(&data.message.plainText);
match command {
Some(Command::Help) => {
body.insert("text", HELP_TEXT.to_string());
},
Some(Command::Random(terms)) => {
body.insert("text", random_choice(terms, &data, &conn));
},
None => {
return Status::NoContent;
}
}
// チャンネル
let channel_id = data.message.channelId.clone();
let endpoint = reqwest::Url::parse(&format!("{}/channels/{}/messages", BASE_URL, channel_id)).unwrap();
// 投げる
let client = reqwest::Client::new();
let res = client.post(endpoint)
.header(AUTHORIZATION, format!("Bearer {}", &*ACCESS_TOKEN))
.json(&body)
.send();
match res {
Ok(resp) => info!("Sending was succeeded. Here's response code: {}", resp.status().as_u16()),
Err(_) => warn!("Failed to post")
};
Status::NoContent
}
|
use crate::shared::cleos;
use std::io;
use std::process::ExitStatus;
fn deploy_example_contract(account: &str, bin: &str) -> io::Result<ExitStatus> {
cleos()
.arg("set")
.arg("abi")
.arg(account)
.arg(format!("mnt/dev/examples/{}/{}.abi.json", bin, bin))
.status()?;
cleos()
.arg("set")
.arg("code")
.arg(account)
.arg(format!("mnt/dev/release/{}_gc.wasm", bin))
.status()
}
pub fn run_deploy_examples() -> io::Result<()> {
for (package, bin, account) in &[
("addressbook", "addressbook", "addressbook"),
("hello", "hello", "hello"),
("hello_bare", "hello_bare", "hellobare"),
("tictactoe", "tictactoe", "tictactoe"),
] {
crate::build_contract(package);
deploy_example_contract(account, bin)?;
}
Ok(())
}
|
use hyper::{Body, Response};
// use std::convert::Infallible;
// std::fs::read_to_string(path: P);
use std::io::Error;
pub fn get_static_content(file: &str) -> Result<String, Error> {
let path = format!("./static/{}", file);
std::fs::read_to_string(&path)
}
pub fn get_static_image(file: &str) -> Result<Vec<u8>, Error> {
let path = format!("./static/{}", file);
// std::fs::read(&path)
std::fs::read(&path)
}
pub fn get_html(file: &str) -> Response<Body> {
// get content of html file
let content = get_static_content(file).unwrap();
// build response
Response::builder()
.status(200)
.header("Content-Type", "text/html")
.body(content.into())
.unwrap()
}
pub fn get_favicon() -> Response<Body> {
// get content of html file
let content = get_static_image("favicon.png").unwrap();
// build response
Response::builder()
.status(200)
.header("Content-Type", "image/png")
.body(content.into())
.unwrap()
}
pub fn get_css(file: &str) -> Response<Body> {
// get content of html file
let content = get_static_content(file).unwrap();
// build response
Response::builder()
.status(200)
.header("Content-Type", "text/css")
.body(content.into())
.unwrap()
}
|
use std::ops::Range;
use allocator::*;
use smallvec::SmallVec;
use block::Block;
use device::Device;
use error::*;
use mapping::*;
use memory::*;
use usage::{Usage, UsageValue};
use util::*;
/// Config for `Heaps` allocator.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Config {
/// Config for arena sub-allocator.
pub arena: Option<ArenaConfig>,
/// Config for dynamic sub-allocator.
pub dynamic: Option<DynamicConfig>,
// chunk: Option<ChunkConfig>,
}
/// Heaps available on particular physical device.
#[derive(Debug)]
pub struct Heaps<T> {
types: Vec<MemoryType<T>>,
heaps: Vec<MemoryHeap>,
}
impl<T: 'static> Heaps<T> {
/// This must be called with `Properties` fetched from physical device.
pub unsafe fn new<P, H>(types: P, heaps: H) -> Self
where
P: IntoIterator<Item = (Properties, u32, Config)>,
H: IntoIterator<Item = u64>,
{
let heaps = heaps
.into_iter()
.map(|size| MemoryHeap::new(size))
.collect::<Vec<_>>();
Heaps {
types: types
.into_iter()
.enumerate()
.map(|(index, (properties, heap_index, config))| {
assert!(
fits_u32(index),
"Number of memory types must fit in u32 limit"
);
assert!(
fits_usize(heap_index),
"Number of memory types must fit in u32 limit"
);
let memory_type = index as u32;
let heap_index = heap_index as usize;
assert!(heap_index < heaps.len());
MemoryType::new(memory_type, heap_index, properties, config)
}).collect(),
heaps,
}
}
/// Allocate memory block
/// from one of memory types specified by `mask`,
/// for intended `usage`,
/// with `size`
/// and `align` requirements.
pub fn allocate<D, U>(
&mut self,
device: &D,
mask: u32,
usage: U,
size: u64,
align: u64,
) -> Result<MemoryBlock<T>, MemoryError>
where
D: Device<Memory = T>,
U: Usage,
{
debug_assert!(fits_u32(self.types.len()));
let (memory_index, _, _) = {
let suitable_types = self
.types
.iter()
.enumerate()
.filter(|(index, _)| (mask & (1u32 << index)) != 0)
.filter_map(|(index, mt)| {
usage
.memory_fitness(mt.properties)
.map(move |fitness| (index, mt, fitness))
}).collect::<SmallVec<[_; 64]>>();
if suitable_types.is_empty() {
return Err(AllocationError::NoSuitableMemory(mask, usage.value()).into());
}
suitable_types
.into_iter()
.filter(|(_, mt, _)| self.heaps[mt.heap_index].available() > size + align)
.max_by_key(|&(_, _, fitness)| fitness)
.ok_or(OutOfMemoryError::HeapsExhausted)?
};
self.allocate_from::<D, U>(device, memory_index as u32, usage, size, align)
}
/// Allocate memory block
/// from `memory_index` specified,
/// for intended `usage`,
/// with `size`
/// and `align` requirements.
fn allocate_from<D, U>(
&mut self,
device: &D,
memory_index: u32,
usage: U,
size: u64,
align: u64,
) -> Result<MemoryBlock<T>, MemoryError>
where
D: Device<Memory = T>,
U: Usage,
{
assert!(fits_usize(memory_index));
let ref mut memory_type = self.types[memory_index as usize];
let ref mut memory_heap = self.heaps[memory_type.heap_index];
if memory_heap.available() < size {
return Err(OutOfMemoryError::HeapsExhausted.into());
}
let (block, allocated) = memory_type.alloc(device, usage, size, align)?;
memory_heap.used += allocated;
Ok(MemoryBlock {
block,
memory_index,
})
}
/// Free memory block.
///
/// Memory block must be allocated from this heap.
pub fn free<D>(&mut self, device: &D, block: MemoryBlock<T>)
where
D: Device<Memory = T>,
{
let memory_index = block.memory_index;
debug_assert!(fits_usize(memory_index));
let ref mut memory_type = self.types[memory_index as usize];
let ref mut memory_heap = self.heaps[memory_type.heap_index];
let freed = memory_type.free(device, block.block);
memory_heap.used -= freed;
}
/// Dispose of allocator.
/// Cleanup allocators before dropping.
/// Will panic if memory instances are left allocated.
pub fn dispose<D>(self, device: &D)
where
D: Device<Memory = T>,
{
for mt in self.types {
mt.dispose(device)
}
}
}
/// Memory block allocated from `Heaps`.
#[derive(Debug)]
pub struct MemoryBlock<T> {
block: BlockFlavor<T>,
memory_index: u32,
}
impl<T> MemoryBlock<T> {
/// Get memory type id.
pub fn memory_type(&self) -> u32 {
self.memory_index
}
}
#[derive(Debug)]
enum BlockFlavor<T> {
Dedicated(DedicatedBlock<T>),
Arena(ArenaBlock<T>),
Dynamic(DynamicBlock<T>),
// Chunk(ChunkBlock<T>),
}
macro_rules! any_block {
($self:ident. $block:ident => $expr:expr) => {{
use self::BlockFlavor::*;
match $self.$block {
Dedicated($block) => $expr,
Arena($block) => $expr,
Dynamic($block) => $expr,
// Chunk($block) => $expr,
}
}};
(& $self:ident. $block:ident => $expr:expr) => {{
use self::BlockFlavor::*;
match &$self.$block {
Dedicated($block) => $expr,
Arena($block) => $expr,
Dynamic($block) => $expr,
// Chunk($block) => $expr,
}
}};
(&mut $self:ident. $block:ident => $expr:expr) => {{
use self::BlockFlavor::*;
match &mut $self.$block {
Dedicated($block) => $expr,
Arena($block) => $expr,
Dynamic($block) => $expr,
// Chunk($block) => $expr,
}
}};
}
impl<T: 'static> Block for MemoryBlock<T> {
type Memory = T;
#[inline]
fn properties(&self) -> Properties {
any_block!(&self.block => block.properties())
}
#[inline]
fn memory(&self) -> &T {
any_block!(&self.block => block.memory())
}
#[inline]
fn range(&self) -> Range<u64> {
any_block!(&self.block => block.range())
}
fn map<'a, D>(
&'a mut self,
device: &D,
range: Range<u64>,
) -> Result<MappedRange<'a, T>, MappingError>
where
D: Device<Memory = T>,
{
any_block!(&mut self.block => block.map(device, range))
}
fn unmap<D>(&mut self, device: &D)
where
D: Device<Memory = T>,
{
any_block!(&mut self.block => block.unmap(device))
}
}
#[derive(Debug)]
struct MemoryHeap {
size: u64,
used: u64,
}
impl MemoryHeap {
fn new(size: u64) -> Self {
MemoryHeap { size, used: 0 }
}
fn available(&self) -> u64 {
self.size - self.used
}
}
#[derive(Debug)]
struct MemoryType<T> {
heap_index: usize,
properties: Properties,
dedicated: DedicatedAllocator<T>,
arena: Option<ArenaAllocator<T>>,
dynamic: Option<DynamicAllocator<T>>,
// chunk: Option<ChunkAllocator<T>>,
}
impl<T: 'static> MemoryType<T> {
fn new(memory_type: u32, heap_index: usize, properties: Properties, config: Config) -> Self {
MemoryType {
properties,
heap_index,
dedicated: DedicatedAllocator::new(memory_type, properties),
arena: if properties.contains(ArenaAllocator::<T>::properties_required()) {
config
.arena
.map(|config| ArenaAllocator::new(memory_type, properties, config))
} else {
None
},
dynamic: if properties.contains(DynamicAllocator::<T>::properties_required()) {
config
.dynamic
.map(|config| DynamicAllocator::new(memory_type, properties, config))
} else {
None
},
// chunk: if properties.contains(ChunkAllocator::<T>::properties_required()) {
// config.chunk.map(|config| ChunkAllocator::new(memory_type, properties, config))
// } else {
// None
// },
}
}
fn alloc<D, U>(
&mut self,
device: &D,
usage: U,
size: u64,
align: u64,
) -> Result<(BlockFlavor<T>, u64), MemoryError>
where
D: Device<Memory = T>,
U: Usage,
{
match (usage.value(), self.arena.as_mut(), self.dynamic.as_mut()) {
(UsageValue::Upload, Some(ref mut arena), _)
| (UsageValue::Download, Some(ref mut arena), _)
if size <= arena.max_allocation() =>
{
arena
.alloc(device, size, align)
.map(|(block, allocated)| (BlockFlavor::Arena(block), allocated))
}
(UsageValue::Dynamic, _, Some(ref mut dynamic)) if size <= dynamic.max_allocation() => {
dynamic
.alloc(device, size, align)
.map(|(block, allocated)| (BlockFlavor::Dynamic(block), allocated))
}
(UsageValue::Data, _, Some(ref mut dynamic)) if size <= dynamic.max_allocation() => {
dynamic
.alloc(device, size, align)
.map(|(block, allocated)| (BlockFlavor::Dynamic(block), allocated))
}
_ => self
.dedicated
.alloc(device, size, align)
.map(|(block, allocated)| (BlockFlavor::Dedicated(block), allocated)),
}
}
fn free<D>(&mut self, device: &D, block: BlockFlavor<T>) -> u64
where
D: Device<Memory = T>,
{
match block {
BlockFlavor::Dedicated(block) => self.dedicated.free(device, block),
BlockFlavor::Arena(block) => self.arena.as_mut().unwrap().free(device, block),
BlockFlavor::Dynamic(block) => self.dynamic.as_mut().unwrap().free(device, block),
// BlockFlavor::Chunk(block) => self.chunk.free(device, block),
}
}
fn dispose<D>(self, device: &D)
where
D: Device<Memory = T>,
{
if let Some(arena) = self.arena {
arena.dispose(device);
}
}
}
|
use serenity::prelude::*;
use serenity::model::prelude::*;
use serenity::framework::standard::{
Args, CommandResult,
macros::command,
};
use serenity::utils::Colour;
use requests::ToJson;
use std::collections::HashMap;
use std::time::Instant;
use std::sync::mpsc;
use std::thread;
use std::sync::mpsc::Sender;
#[command]
pub async fn multiply(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let one = args.single::<f64>()?;
let two = args.single::<f64>()?;
let product = one * two;
msg.channel_id.say(&ctx.http, product).await?;
Ok(())
}
const ITEMS: &[&str; 24] = &["Ender Artifact", "Wither Artifact", "Hegemony Artifact",
"Sharpness VI", "Giant Killer VI", "Power VI", "Growth VI", "Protection VI",
"Sharpness VII", "Giant Killer VII", "Power VII", "Growth VII", "Protection VII", "Counter-Strike V",
"Big Brain III", "Vicious III",
"Parrot Legendary", "Parrot Epic", "Turtle Legendary", "Turtle Epic", "Jellyfish Legendary", "Jellyfish Epic",
"Travel Scroll to Dark Auction", "Plasma Nucleus"];
const CATEGORIES: &[&str; 5] = &["Artifacts", "Books","Book Bundles", "Pets", "Misc"];
const CATEGORIES_COUNT: [i32; 5] = [3, 11, 2, 6, 2];
#[command]
pub async fn da(ctx: &Context, msg: &Message) -> CommandResult {
let start = Instant::now();
msg.channel_id.say(&ctx.http, "Working...").await?;
// let mojang_response = requests::get("https://api.mojang.com/users/profiles/minecraft/PikachuPals").unwrap();
// let mojang_data = mojang_response.json().unwrap();
// let user_uuid = mojang_data["id"].as_str().unwrap();
// let mut skyblock_request = String::from("https://api.hypixel.net/Skyblock/profiles?key=...&uuid=");
// skyblock_request.push_str(&user_uuid);
// let response = requests::get(skyblock_request).unwrap();
// let data = response.json().unwrap();
let skyblock_auctions = String::from("https://api.hypixel.net/skyblock/auctions?page=0");
let response = requests::get(skyblock_auctions).unwrap();
let data = response.json().unwrap();
let auction_pages = data["totalPages"].as_i32().unwrap();
let dark_auction_lowest_prices = get_lowest_bin_values(auction_pages);
let mut item_prices: HashMap<String, String> = HashMap::new();
for item in ITEMS.iter(){
item_prices.insert(item.to_string() ,format!("$: {}", *dark_auction_lowest_prices.get(&item.to_string()).unwrap()));
}
let mut output_fields_vec = Vec::with_capacity(32);
let mut output_fields_vec2 = Vec::with_capacity(32);
let mut count = 0;
let mut category = 0;
let mut input_count = 0;
output_fields_vec.push((format!("ᅠᅠ\n__{}__", CATEGORIES[0]),
"ᅠᅠ",
false,));
for item in ITEMS.iter(){
if input_count < 24 {
if CATEGORIES_COUNT[category] > count {
count += 1;
}
else {
category += 1;
output_fields_vec.push((format!("ᅠᅠ\n__{}__", CATEGORIES[category]),
"ᅠᅠ",
false,));
count = 1;
input_count += 1;
}
output_fields_vec.push((format!("{}", item),
item_prices.get(&item.to_string()).unwrap(),
true,));
input_count += 1;
}
else {
if CATEGORIES_COUNT[category] > count {
count += 1;
}
else {
category += 1;
output_fields_vec2.push((format!("ᅠᅠ\n__{}__", CATEGORIES[category]),
"ᅠᅠ",
false,));
count = 1;
input_count += 1;
}
output_fields_vec2.push((format!("{}", item),
item_prices.get(&item.to_string()).unwrap(),
true,));
input_count += 1;
}
}
let timed_search = format!("Completed in {:.2?}.", start.elapsed());
msg.channel_id.send_message(&ctx.http, |m|{
m.content(timed_search);
m.embed(|e| {
e.title("`Dark Auction BIN Prices`");
e.description("");
e.thumbnail("https://i.imgur.com/JNpxJ7I.png");
e.colour(Colour::FOOYOO);
e.fields(output_fields_vec);
e });
m
}).await?;
msg.channel_id.send_message(&ctx.http, |m|{
m.embed(|e| {
e.colour(Colour::FOOYOO);
e.fields(output_fields_vec2);
e });
m
}).await?;
Ok(())
}
fn get_lowest_bin_values(auction_pages: i32) -> HashMap<String, i32>{
let mut lowest_prices: HashMap<String, i32> = HashMap::new();
for item in ITEMS.iter(){
lowest_prices.insert(item.to_string(), 999999999);
}
let mut sender_vector: Vec<Sender<i32>> = Vec::with_capacity(ITEMS.len());
let mut receiver_vector = Vec::with_capacity(ITEMS.len());
for _n in 0..ITEMS.len(){
let (tx, rx) = mpsc::channel();
sender_vector.push(tx);
receiver_vector.push(rx);
}
let mut handles = vec![];
let mut threads_pages: Vec<i32> = vec![0];
let threads: i32 = 8;
let pages_per_thread: i32 = auction_pages / threads;
let rem_pages: i32 = auction_pages % threads;
for thread in 1..=threads{
if thread != threads{
threads_pages.push(thread * pages_per_thread);
}
else{
threads_pages.push((thread * pages_per_thread) + rem_pages);
}
}
for i in 0..threads_pages.len() - 1 {
let mut sender_vector_clone: Vec<Sender<i32>> = Vec::with_capacity(ITEMS.len());
let start_page = threads_pages[i].clone();
let end_page = threads_pages[i + 1].clone();
for tx in &sender_vector{
let tx_clone = tx.clone();
sender_vector_clone.push(tx_clone);
}
let handle = thread::spawn(move || work_thread(sender_vector_clone,
start_page, end_page));
handles.push(handle);
}
for handle in handles{
handle.join().unwrap();
}
for sender in sender_vector{
drop(sender);
}
for item in ITEMS.iter() {
let index = ITEMS.iter().position(|x| x == item).unwrap();
for price in &receiver_vector[index]{
if price < *lowest_prices.get(&item.to_string()).unwrap() {
lowest_prices.insert(item.to_string(), price);
}
}
}
return lowest_prices;
}
fn work_thread(sender_vector: Vec<Sender<i32>>, i: i32, e: i32){
for page in i..e{
let mut page_auctions = String::from(" https://api.hypixel.net/skyblock/auctions?page=");
let page_number = page.to_string();
page_auctions.push_str(&page_number);
let response = requests::get(page_auctions).unwrap();
let data = response.json().unwrap();
let ebook = "Enchanted Book".to_string();
let enchants: [String; 11] = ["Sharpness VI".to_string(), "Giant Killer VI".to_string(), "Power VI".to_string(), "Growth VI".to_string(), "Protection VI".to_string(),
"Sharpness VII".to_string(), "Giant Killer VII".to_string(), "Power VII".to_string(), "Growth VII".to_string(), "Protection VII".to_string(), "Counter-Strike V".to_string()];
let unwanted_enchants: [String; 3] = ["Fire".to_string(), "Projectile".to_string(), "Blast".to_string()];
let mut fake_enchant;
let ebundle = "Enchanted Book Bundle".to_string();
let bundles: [String; 2] = ["Big Brain III".to_string(), "Vicious III".to_string()];
for auc in data["auctions"].members(){
for auc_item in ITEMS.iter() {
if auc["bin"].as_bool() != None{
if auc["item_name"].as_str().unwrap() == *auc_item && auc["bin"].as_bool() != None {
let index = ITEMS.iter().position(|x| x == auc_item).unwrap();
let auc_item_price = auc["starting_bid"].as_i32().unwrap();
sender_vector[index].send(auc_item_price).unwrap();
}
else if auc["item_name"].as_str().unwrap() == &ebook {
for enchant in enchants.iter() {
if auc["item_lore"].as_str().unwrap().contains(enchant){
if auc["item_lore"].as_str().unwrap().contains(&"Protection".to_string()){
fake_enchant = false;
for unwanted_enchant in unwanted_enchants.iter(){
if auc["item_lore"].as_str().unwrap().contains(unwanted_enchant) {
fake_enchant = true;
}
}
if !fake_enchant{
let index = ITEMS.iter().position(|x| x == enchant).unwrap();
let auc_item_price = auc["starting_bid"].as_i32().unwrap();
sender_vector[index].send(auc_item_price).unwrap();
}
}
else{
let index = ITEMS.iter().position(|x| x == enchant).unwrap();
let auc_item_price = auc["starting_bid"].as_i32().unwrap();
sender_vector[index].send(auc_item_price).unwrap();
}
}
}
}
else if auc["item_name"].as_str().unwrap() == &ebundle {
for bundle in bundles.iter() {
if auc["item_lore"].as_str().unwrap().contains(bundle){
let index = ITEMS.iter().position(|x| x == bundle).unwrap();
let auc_item_price = auc["starting_bid"].as_i32().unwrap();
sender_vector[index].send(auc_item_price).unwrap();
}
}
}
else if auc_item.contains(&"Epic".to_string()) || auc_item.contains(&"Legendary".to_string()) {
let mut pet = auc_item.split_whitespace();
if auc["item_name"].as_str().unwrap().contains(pet.next().unwrap()) && auc["item_lore"].as_str().unwrap().contains(&pet.next().unwrap().to_uppercase()){
let index = ITEMS.iter().position(|x| x == auc_item).unwrap();
let auc_item_price = auc["starting_bid"].as_i32().unwrap();
sender_vector[index].send(auc_item_price).unwrap();
}
}
}
}
}
}
}
|
use std::process::Command;
fn main() {
run_with_cd();
}
fn run() {
let output = Command::new("sh")
.arg("-c")
.arg("/home/susilo/var/www/ecc4/protected/yii-dev")
.output()
.expect("Tidak dapat menjalankan command!.");
let ls = output.stdout;
println!("{:#?}", ls.iter().map(|&x| x as char).collect::<String>());
}
fn run_with_cd() {
let output = Command::new("./yii-dev")
.current_dir("/home/susilo/var/www/ecc4/protected")
.output()
.expect("Tidak dapat menjalankan command!.");
let ls = output.stdout;
println!("{:#?}", ls.iter().map(|&x| x as char).collect::<String>());
}
|
pub trait LocalApic {
fn is_supported() -> bool;
} |
use crate::common::{BuildingColorer, BuildingColorerBuilder, CommonState, Warping};
use crate::game::{State, Transition, WizardState};
use crate::helpers::ID;
use crate::mission::pick_time_range;
use crate::sandbox::SandboxMode;
use crate::ui::UI;
use abstutil::{prettyprint_usize, MultiMap, WeightedUsizeChoice};
use ezgui::{
hotkey, Choice, Color, EventCtx, EventLoopMode, GfxCtx, Key, Line, ModalMenu, Text, Wizard,
WrappedWizard,
};
use geom::Duration;
use map_model::{BuildingID, IntersectionID, Map, Neighborhood};
use sim::{
BorderSpawnOverTime, DrivingGoal, OriginDestination, Scenario, SeedParkedCars, SidewalkPOI,
SidewalkSpot, SpawnOverTime, SpawnTrip,
};
use std::collections::{BTreeSet, HashMap};
use std::fmt;
pub struct ScenarioManager {
menu: ModalMenu,
common: CommonState,
scenario: Scenario,
// The usizes are indices into scenario.individ_trips
trips_from_bldg: MultiMap<BuildingID, usize>,
trips_to_bldg: MultiMap<BuildingID, usize>,
cars_needed_per_bldg: HashMap<BuildingID, CarCount>,
total_cars_needed: CarCount,
total_parking_spots: usize,
bldg_colors: BuildingColorer,
}
impl ScenarioManager {
pub fn new(scenario: Scenario, ctx: &mut EventCtx, ui: &UI) -> ScenarioManager {
let mut trips_from_bldg = MultiMap::new();
let mut trips_to_bldg = MultiMap::new();
let mut cars_needed_per_bldg = HashMap::new();
for b in ui.primary.map.all_buildings() {
cars_needed_per_bldg.insert(b.id, CarCount::new());
}
let mut total_cars_needed = CarCount::new();
let color = Color::BLUE;
let mut bldg_colors =
BuildingColorerBuilder::new("trips", vec![("building with trips from/to it", color)]);
for (idx, trip) in scenario.individ_trips.iter().enumerate() {
// trips_from_bldg
match trip {
SpawnTrip::CarAppearing { .. } => {}
SpawnTrip::MaybeUsingParkedCar(_, b, _) => {
trips_from_bldg.insert(*b, idx);
bldg_colors.add(*b, color);
}
SpawnTrip::UsingBike(_, ref spot, _)
| SpawnTrip::JustWalking(_, ref spot, _)
| SpawnTrip::UsingTransit(_, ref spot, _, _, _, _) => {
if let SidewalkPOI::Building(b) = spot.connection {
trips_from_bldg.insert(b, idx);
bldg_colors.add(b, color);
}
}
}
// trips_to_bldg
match trip {
SpawnTrip::CarAppearing { ref goal, .. }
| SpawnTrip::MaybeUsingParkedCar(_, _, ref goal)
| SpawnTrip::UsingBike(_, _, ref goal) => {
if let DrivingGoal::ParkNear(b) = goal {
trips_to_bldg.insert(*b, idx);
bldg_colors.add(*b, color);
}
}
SpawnTrip::JustWalking(_, _, ref spot)
| SpawnTrip::UsingTransit(_, _, ref spot, _, _, _) => {
if let SidewalkPOI::Building(b) = spot.connection {
trips_to_bldg.insert(b, idx);
bldg_colors.add(b, color);
}
}
}
// Parked cars
if let SpawnTrip::MaybeUsingParkedCar(_, start_bldg, ref goal) = trip {
let mut cnt = cars_needed_per_bldg.get_mut(start_bldg).unwrap();
cnt.naive += 1;
total_cars_needed.naive += 1;
if cnt.available > 0 {
cnt.available -= 1;
} else {
cnt.recycle += 1;
total_cars_needed.recycle += 1;
}
// Cars appearing at borders and driving in contribute parked cars.
if let DrivingGoal::ParkNear(b) = goal {
cars_needed_per_bldg.get_mut(b).unwrap().available += 1;
}
}
}
let (filled_spots, free_parking_spots) = ui.primary.sim.get_all_parking_spots();
assert!(filled_spots.is_empty());
ScenarioManager {
menu: ModalMenu::new(
"Scenario Editor",
vec![
vec![
(hotkey(Key::S), "save"),
(hotkey(Key::E), "edit"),
(hotkey(Key::I), "instantiate"),
],
vec![
(hotkey(Key::Escape), "quit"),
(hotkey(Key::J), "warp"),
(hotkey(Key::K), "navigate"),
(hotkey(Key::SingleQuote), "shortcuts"),
(hotkey(Key::F1), "take a screenshot"),
],
],
ctx,
),
common: CommonState::new(),
scenario,
trips_from_bldg,
trips_to_bldg,
cars_needed_per_bldg,
total_cars_needed,
total_parking_spots: free_parking_spots.len(),
bldg_colors: bldg_colors.build(ctx, &ui.primary.map),
}
}
}
impl State for ScenarioManager {
fn event(&mut self, ctx: &mut EventCtx, ui: &mut UI) -> Transition {
// TODO Calculate this once? Except when we modify it, nice to automatically pick up
// changes...
{
let mut txt = Text::prompt("Scenario Editor");
txt.add(Line(&self.scenario.scenario_name));
for line in self.scenario.describe() {
txt.add(Line(line));
}
txt.add(Line(format!(
"{} total parked cars needed, {} spots",
self.total_cars_needed,
prettyprint_usize(self.total_parking_spots),
)));
self.menu.handle_event(ctx, Some(txt));
}
ctx.canvas.handle_event(ctx.input);
if ctx.redo_mouseover() {
ui.recalculate_current_selection(ctx);
}
if let Some(t) = self.common.event(ctx, ui, &mut self.menu) {
return t;
}
if self.menu.action("quit") {
return Transition::Pop;
} else if self.menu.action("save") {
self.scenario.save();
} else if self.menu.action("edit") {
return Transition::Push(Box::new(ScenarioEditor {
scenario: self.scenario.clone(),
wizard: Wizard::new(),
}));
} else if self.menu.action("instantiate") {
ctx.loading_screen("instantiate scenario", |_, timer| {
self.scenario.instantiate(
&mut ui.primary.sim,
&ui.primary.map,
&mut ui.primary.current_flags.sim_flags.make_rng(),
timer,
);
ui.primary.sim.step(&ui.primary.map, Duration::seconds(0.1));
});
return Transition::Replace(Box::new(SandboxMode::new(ctx)));
}
if let Some(ID::Building(b)) = ui.primary.current_selection {
let from = self.trips_from_bldg.get(b);
let to = self.trips_to_bldg.get(b);
if (!from.is_empty() || !to.is_empty())
&& ctx.input.contextual_action(Key::T, "browse trips")
{
// TODO Avoid the clone? Just happens once though.
let mut all_trips = from.clone();
all_trips.extend(to);
return Transition::Push(make_trip_picker(self.scenario.clone(), all_trips, b));
}
}
Transition::Keep
}
fn draw_default_ui(&self) -> bool {
false
}
fn draw(&self, g: &mut GfxCtx, ui: &UI) {
// TODO Let common contribute draw_options...
self.bldg_colors.draw(g, ui);
self.menu.draw(g);
// TODO Weird to not draw common (turn cycler), but we want the custom OSD...
if let Some(ID::Building(b)) = ui.primary.current_selection {
let mut osd = Text::new();
let from = self.trips_from_bldg.get(b);
let to = self.trips_to_bldg.get(b);
osd.add_appended(vec![
Line(b.to_string()).fg(ui.cs.get("OSD ID color")),
Line(" is "),
Line(ui.primary.map.get_b(b).get_name()).fg(ui.cs.get("OSD name color")),
Line(format!(
". {} trips from here, {} trips to here, {} parked cars needed",
from.len(),
to.len(),
self.cars_needed_per_bldg[&b]
)),
]);
CommonState::draw_custom_osd(g, osd);
} else {
CommonState::draw_osd(g, ui, &ui.primary.current_selection);
}
}
}
struct ScenarioEditor {
scenario: Scenario,
wizard: Wizard,
}
impl State for ScenarioEditor {
fn event(&mut self, ctx: &mut EventCtx, ui: &mut UI) -> Transition {
if let Some(()) = edit_scenario(&ui.primary.map, &mut self.scenario, self.wizard.wrap(ctx))
{
// TODO autosave, or at least make it clear there are unsaved edits
let scenario = self.scenario.clone();
return Transition::PopWithData(Box::new(|state, _, _| {
let mut manager = state.downcast_mut::<ScenarioManager>().unwrap();
manager.scenario = scenario;
// Don't need to update trips_from_bldg or trips_to_bldg, since edit_scenario
// doesn't touch individ_trips.
}));
} else if self.wizard.aborted() {
return Transition::Pop;
}
Transition::Keep
}
fn draw(&self, g: &mut GfxCtx, ui: &UI) {
if let Some(neighborhood) = self.wizard.current_menu_choice::<Neighborhood>() {
g.draw_polygon(ui.cs.get("neighborhood polygon"), &neighborhood.polygon);
}
self.wizard.draw(g);
}
}
fn edit_scenario(map: &Map, scenario: &mut Scenario, mut wizard: WrappedWizard) -> Option<()> {
let seed_parked = "Seed parked cars";
let spawn = "Spawn agents";
let spawn_border = "Spawn agents from a border";
let randomize = "Randomly spawn stuff from/to every neighborhood";
match wizard
.choose_string("What kind of edit?", || {
vec![seed_parked, spawn, spawn_border, randomize]
})?
.as_str()
{
x if x == seed_parked => {
scenario.seed_parked_cars.push(SeedParkedCars {
neighborhood: choose_neighborhood(
map,
&mut wizard,
"Seed parked cars in what area?",
)?,
cars_per_building: input_weighted_usize(
&mut wizard,
"How many cars per building? (ex: 4,4,2)",
)?,
});
}
x if x == spawn => {
let (start_time, stop_time) =
pick_time_range(&mut wizard, "Start spawning when?", "Stop spawning when?")?;
scenario.spawn_over_time.push(SpawnOverTime {
num_agents: wizard.input_usize("Spawn how many agents?")?,
start_time,
stop_time,
start_from_neighborhood: choose_neighborhood(
map,
&mut wizard,
"Where should the agents start?",
)?,
goal: choose_origin_destination(map, &mut wizard, "Where should the agents go?")?,
percent_biking: wizard
.input_percent("What percent of the walking trips will bike instead?")?,
percent_use_transit: wizard.input_percent(
"What percent of the walking trips will consider taking transit?",
)?,
});
}
x if x == spawn_border => {
let (start_time, stop_time) =
pick_time_range(&mut wizard, "Start spawning when?", "Stop spawning when?")?;
scenario.border_spawn_over_time.push(BorderSpawnOverTime {
num_peds: wizard.input_usize("Spawn how many pedestrians?")?,
num_cars: wizard.input_usize("Spawn how many cars?")?,
num_bikes: wizard.input_usize("Spawn how many bikes?")?,
start_time,
stop_time,
// TODO validate it's a border!
start_from_border: choose_intersection(
&mut wizard,
"Which border should the agents spawn at?",
)?,
goal: choose_origin_destination(map, &mut wizard, "Where should the agents go?")?,
percent_use_transit: wizard.input_percent(
"What percent of the walking trips will consider taking transit?",
)?,
});
}
x if x == randomize => {
let neighborhoods = Neighborhood::load_all(map.get_name(), &map.get_gps_bounds());
for (src, _) in &neighborhoods {
for (dst, _) in &neighborhoods {
scenario.spawn_over_time.push(SpawnOverTime {
num_agents: 100,
start_time: Duration::ZERO,
stop_time: Duration::minutes(10),
start_from_neighborhood: src.to_string(),
goal: OriginDestination::Neighborhood(dst.to_string()),
percent_biking: 0.1,
percent_use_transit: 0.2,
});
}
}
}
_ => unreachable!(),
};
Some(())
}
fn choose_neighborhood(map: &Map, wizard: &mut WrappedWizard, query: &str) -> Option<String> {
// Load the full object, since we usually visualize the neighborhood when menuing over it
wizard
.choose(query, || {
Choice::from(Neighborhood::load_all(map.get_name(), map.get_gps_bounds()))
})
.map(|(n, _)| n)
}
fn input_weighted_usize(wizard: &mut WrappedWizard, query: &str) -> Option<WeightedUsizeChoice> {
wizard.input_something(
query,
None,
Box::new(|line| WeightedUsizeChoice::parse(&line)),
)
}
// TODO Validate the intersection exists? Let them pick it with the cursor?
fn choose_intersection(wizard: &mut WrappedWizard, query: &str) -> Option<IntersectionID> {
wizard.input_something(
query,
None,
Box::new(|line| usize::from_str_radix(&line, 10).ok().map(IntersectionID)),
)
}
fn choose_origin_destination(
map: &Map,
wizard: &mut WrappedWizard,
query: &str,
) -> Option<OriginDestination> {
let neighborhood = "Neighborhood";
let border = "Border intersection";
if wizard.choose_string(query, || vec![neighborhood, border])? == neighborhood {
choose_neighborhood(map, wizard, query).map(OriginDestination::Neighborhood)
} else {
choose_intersection(wizard, query).map(OriginDestination::Border)
}
}
fn make_trip_picker(
scenario: Scenario,
indices: BTreeSet<usize>,
home: BuildingID,
) -> Box<dyn State> {
WizardState::new(Box::new(move |wiz, ctx, ui| {
let warp_to = wiz
.wrap(ctx)
.choose("Trips from/to this building", || {
// TODO Panics if there are two duplicate trips (b1124 in montlake)
indices
.iter()
.map(|idx| {
let trip = &scenario.individ_trips[*idx];
Choice::new(describe(trip, home), other_endpt(trip, home))
})
.collect()
})?
.1;
Some(Transition::ReplaceWithMode(
Warping::new(
ctx,
warp_to.canonical_point(&ui.primary).unwrap(),
None,
Some(warp_to),
&mut ui.primary,
),
EventLoopMode::Animation,
))
}))
}
fn describe(trip: &SpawnTrip, home: BuildingID) -> String {
let driving_goal = |goal: &DrivingGoal| match goal {
DrivingGoal::ParkNear(b) => {
if *b == home {
"HERE".to_string()
} else {
b.to_string()
}
}
DrivingGoal::Border(i, _) => i.to_string(),
};
let sidewalk_spot = |spot: &SidewalkSpot| match &spot.connection {
SidewalkPOI::Building(b) => {
if *b == home {
"HERE".to_string()
} else {
b.to_string()
}
}
SidewalkPOI::Border(i) => i.to_string(),
x => format!("{:?}", x),
};
match trip {
SpawnTrip::CarAppearing {
depart,
start,
goal,
is_bike,
} => format!(
"{}: {} appears at {}, goes to {}",
depart,
if *is_bike { "bike" } else { "car" },
start.lane(),
driving_goal(goal)
),
SpawnTrip::MaybeUsingParkedCar(depart, start_bldg, goal) => format!(
"{}: try to drive from {} to {}",
depart,
if *start_bldg == home {
"HERE".to_string()
} else {
start_bldg.to_string()
},
driving_goal(goal),
),
SpawnTrip::UsingBike(depart, start, goal) => format!(
"{}: bike from {} to {}",
depart,
sidewalk_spot(start),
driving_goal(goal)
),
SpawnTrip::JustWalking(depart, start, goal) => format!(
"{}: walk from {} to {}",
depart,
sidewalk_spot(start),
sidewalk_spot(goal)
),
SpawnTrip::UsingTransit(depart, start, goal, route, _, _) => format!(
"{}: bus from {} to {} using {}",
depart,
sidewalk_spot(start),
sidewalk_spot(goal),
route
),
}
}
fn other_endpt(trip: &SpawnTrip, home: BuildingID) -> ID {
let driving_goal = |goal: &DrivingGoal| match goal {
DrivingGoal::ParkNear(b) => ID::Building(*b),
DrivingGoal::Border(i, _) => ID::Intersection(*i),
};
let sidewalk_spot = |spot: &SidewalkSpot| match &spot.connection {
SidewalkPOI::Building(b) => ID::Building(*b),
SidewalkPOI::Border(i) => ID::Intersection(*i),
x => panic!("other_endpt for {:?}?", x),
};
let (from, to) = match trip {
SpawnTrip::CarAppearing { start, goal, .. } => (ID::Lane(start.lane()), driving_goal(goal)),
SpawnTrip::MaybeUsingParkedCar(_, start_bldg, goal) => {
(ID::Building(*start_bldg), driving_goal(goal))
}
SpawnTrip::UsingBike(_, start, goal) => (sidewalk_spot(start), driving_goal(goal)),
SpawnTrip::JustWalking(_, start, goal) => (sidewalk_spot(start), sidewalk_spot(goal)),
SpawnTrip::UsingTransit(_, start, goal, _, _, _) => {
(sidewalk_spot(start), sidewalk_spot(goal))
}
};
if from == ID::Building(home) {
to
} else if to == ID::Building(home) {
from
} else {
panic!("other_endpt broke when homed at {} for {:?}", home, trip)
}
}
struct CarCount {
naive: usize,
recycle: usize,
// Intermediate state
available: usize,
}
impl CarCount {
fn new() -> CarCount {
CarCount {
naive: 0,
recycle: 0,
available: 0,
}
}
}
impl fmt::Display for CarCount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{} / {}",
prettyprint_usize(self.naive),
prettyprint_usize(self.recycle),
)
}
}
|
//! Error types used in this driver.
use core::str::Utf8Error;
/// A collection of errors that can occur.
#[derive(Debug, PartialEq, Eq)]
pub enum Error<S> {
/// Could not read from serial port.
SerialRead(S),
/// Could not write to serial port.
SerialWrite(S),
/// Read buffer is too small.
/// This is a bug, please report it on GitHub!
ReadBufferTooSmall,
/// Command or response contained invalid UTF-8.
EncodingError,
/// A response could not be parsed.
ParsingError,
/// A command failed.
CommandFailed,
/// A bad parameter was supplied.
BadParameter,
/// Device is in sleep mode.
SleepMode,
/// The module is in an invalid state.
InvalidState,
}
impl<S> From<Utf8Error> for Error<S> {
fn from(_: Utf8Error) -> Self {
Error::EncodingError
}
}
/// Errors that can occur during the join procedure.
#[derive(Debug, PartialEq, Eq)]
pub enum JoinError<S> {
/// Invalid join mode. This indicates a bug in the driver and should be
/// reported on GitHub.
BadParameter,
/// The keys corresponding to the join mode (OTAA or ABP) were not
/// configured.
KeysNotInit,
/// All channels are busy.
NoFreeChannel,
/// Device is in a Silent Immediately state.
Silent,
/// MAC state is not idle.
Busy,
/// MAC was paused and not resumed.
MacPaused,
/// Join procedure was unsuccessful: Device tried to join but was rejected
/// or did not receive a response.
JoinUnsuccessful,
/// Unknown response.
UnknownResponse,
/// Another error occurred.
Other(Error<S>),
}
impl<S> From<Error<S>> for JoinError<S> {
fn from(other: Error<S>) -> Self {
JoinError::Other(other)
}
}
impl<S> From<Utf8Error> for JoinError<S> {
fn from(_: Utf8Error) -> Self {
JoinError::Other(Error::EncodingError)
}
}
/// Errors that can occur during the transmit procedure.
#[derive(Debug, PartialEq, Eq)]
pub enum TxError<S> {
/// Invalid type, port or data.
BadParameter,
/// Network not joined.
NotJoined,
/// All channels are busy.
NoFreeChannel,
/// Device is in a Silent Immediately state.
Silent,
/// Frame counter rollover. Re-join needed.
FrameCounterRollover,
/// MAC state is not idle.
Busy,
/// MAC was paused and not resumed.
MacPaused,
/// Application payload length is greater than the maximum application
/// payload length corresponding to the current data rate.
InvalidDataLenth,
/// Transmission was not successful.
TxUnsuccessful,
/// Unknown response.
UnknownResponse,
/// Another error occurred.
Other(Error<S>),
}
impl<S> From<Error<S>> for TxError<S> {
fn from(other: Error<S>) -> Self {
TxError::Other(other)
}
}
impl<S> From<Utf8Error> for TxError<S> {
fn from(_: Utf8Error) -> Self {
TxError::Other(Error::EncodingError)
}
}
/// A `Result<T, Error>`.
pub type RnResult<T, S> = Result<T, Error<S>>;
|
use core::cmp::Ordering::{self, *};
use core::fmt::{self, Debug};
use core::ops::{Add, AddAssign, Div, Index, IndexMut, Mul, RangeBounds, Rem};
use core::ptr::NonNull;
use std::sync::{Arc, Weak};
use std::vec::Drain;
use hashbrown::HashMap;
use liblumen_core::locks::Mutex;
use liblumen_alloc::borrow::CloneToProcess;
use liblumen_alloc::erts::exception::AllocResult;
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::erts::Process;
use liblumen_alloc::time::{Milliseconds, Monotonic};
use crate::registry;
use crate::scheduler::{self, Scheduled, Scheduler};
use crate::time::monotonic;
pub fn cancel(timer_reference: &Reference) -> Option<Milliseconds> {
timer_reference.scheduler().and_then(|scheduler| {
scheduler
.hierarchy()
.write()
.cancel(timer_reference.number())
})
}
pub fn read(timer_reference: &Reference) -> Option<Milliseconds> {
timer_reference
.scheduler()
.and_then(|scheduler| scheduler.hierarchy().read().read(timer_reference.number()))
}
pub fn start(
monotonic: Monotonic,
event: SourceEvent,
arc_process: Arc<Process>,
) -> AllocResult<Term> {
let arc_scheduler = scheduler::current();
let result = arc_scheduler.hierarchy().write().start(
monotonic,
event,
arc_process,
arc_scheduler.clone(),
);
result
}
/// Times out the timers for the thread that have timed out since the last time `timeout` was
/// called.
pub fn timeout() {
scheduler::current().hierarchy().write().timeout();
}
#[derive(Debug)]
pub struct Message {
pub heap_fragment: NonNull<liblumen_alloc::erts::HeapFragment>,
pub term: Term,
}
#[derive(Debug)]
pub struct HeapFragment {
pub heap_fragment: NonNull<liblumen_alloc::erts::HeapFragment>,
pub term: Term,
}
#[derive(Clone, Debug)]
pub enum Destination {
Name(Atom),
Process(Weak<Process>),
}
pub struct Hierarchy {
at_once: Slot,
soon: Wheel,
later: Wheel,
long_term: Slot,
timer_by_reference_number: HashMap<ReferenceNumber, Weak<Timer>>,
}
impl Hierarchy {
const SOON_MILLISECONDS_PER_SLOT: MillisecondsPerSlot = MillisecondsPerSlot(1);
const SOON_TOTAL_MILLISECONDS: Milliseconds =
Self::SOON_MILLISECONDS_PER_SLOT.const_mul(Wheel::SLOTS);
const LATER_MILLISECONDS_PER_SLOT: MillisecondsPerSlot =
MillisecondsPerSlot(Self::SOON_TOTAL_MILLISECONDS.const_div(2).as_u64());
const LATER_TOTAL_MILLISECONDS: Milliseconds =
Self::LATER_MILLISECONDS_PER_SLOT.const_mul(Wheel::SLOTS);
pub fn cancel(&mut self, timer_reference_number: ReferenceNumber) -> Option<Milliseconds> {
self.timer_by_reference_number
.remove(&timer_reference_number)
.and_then(|weak_timer| weak_timer.upgrade())
.map(|arc_timer| {
use Position::*;
match *arc_timer.position.lock() {
// can't be found in O(1), mark as canceled for later cleanup
AtOnce => self.at_once.cancel(timer_reference_number),
Soon { slot_index } => self.soon.cancel(slot_index, timer_reference_number),
Later { slot_index } => self.later.cancel(slot_index, timer_reference_number),
LongTerm => self.long_term.cancel(timer_reference_number),
};
arc_timer.milliseconds_remaining()
})
}
fn position(&self, monotonic: Monotonic) -> Position {
if monotonic < self.soon.slot_monotonic {
Position::AtOnce
} else if monotonic < self.later.slot_monotonic {
Position::Soon {
slot_index: self.soon.slot_index(monotonic),
}
} else if monotonic < (self.later.slot_monotonic + Self::LATER_TOTAL_MILLISECONDS) {
Position::Later {
slot_index: self.later.slot_index(monotonic),
}
} else {
Position::LongTerm
}
}
pub fn read(&self, timer_reference_number: ReferenceNumber) -> Option<Milliseconds> {
self.timer_by_reference_number
.get(&timer_reference_number)
.and_then(|weak_timer| weak_timer.upgrade())
.map(|rc_timer| rc_timer.milliseconds_remaining())
}
pub fn start(
&mut self,
monotonic: Monotonic,
source_event: SourceEvent,
arc_process: Arc<Process>,
arc_scheduler: Arc<dyn Scheduler>,
) -> AllocResult<Term> {
let reference_number = arc_scheduler.next_reference_number();
let process_reference =
arc_process.reference_from_scheduler(arc_scheduler.id(), reference_number);
let destination_event = match source_event {
SourceEvent::Message {
destination,
format,
term,
} => {
let (heap_fragment_message, heap_fragment) = match format {
Format::Message => term.clone_to_fragment()?,
Format::TimeoutTuple => {
let tag = Atom::str_to_term("timeout");
let process_tuple =
arc_process.tuple_from_slice(&[tag, process_reference, term]);
process_tuple.clone_to_fragment()?
}
};
let heap_fragment = Mutex::new(HeapFragment {
heap_fragment,
term: heap_fragment_message,
});
DestinationEvent::Message {
destination,
heap_fragment,
}
}
SourceEvent::StopWaiting => DestinationEvent::StopWaiting {
process: Arc::downgrade(&arc_process),
},
};
let position = self.position(monotonic);
let timer = Timer {
reference_number,
monotonic,
event: destination_event,
position: Mutex::new(position),
};
let arc_timer = Arc::new(timer);
let timeoutable = Arc::clone(&arc_timer);
let cancellable = Arc::downgrade(&arc_timer);
match position {
Position::AtOnce => self.at_once.start(timeoutable),
Position::Soon { slot_index } => self.soon.start(slot_index, timeoutable),
Position::Later { slot_index } => self.later.start(slot_index, timeoutable),
Position::LongTerm => self.long_term.start(timeoutable),
}
self.timer_by_reference_number
.insert(reference_number, cancellable);
Ok(process_reference)
}
pub fn timeout(&mut self) {
self.timeout_at_once();
let monotonic = monotonic::time();
let milliseconds = monotonic - self.soon.slot_monotonic;
for _ in 0..milliseconds.into() {
self.timeout_soon_slot();
assert!(self.soon.is_empty());
self.soon.next_slot();
let soon_max_monotonic = self.soon.max_monotonic();
if self.later.slot_monotonic <= soon_max_monotonic {
self.transfer_later_to_soon(soon_max_monotonic);
let later_next_slot_monotonic = self.later.next_slot_monotonic();
if later_next_slot_monotonic <= soon_max_monotonic {
assert!(self.later.is_empty());
self.later.next_slot();
let later_max_monotonic = self.later.max_monotonic();
self.transfer_long_term_to_later(later_max_monotonic);
}
}
}
}
fn timeout_at_once(&mut self) {
for arc_timer in self.at_once.drain(..) {
self.timer_by_reference_number
.remove(&arc_timer.reference_number);
Self::timeout_arc_timer(arc_timer);
}
}
fn timeout_soon_slot(&mut self) {
for arc_timer in self.soon.drain(..) {
self.timer_by_reference_number
.remove(&arc_timer.reference_number);
Self::timeout_arc_timer(arc_timer);
}
}
fn timeout_arc_timer(arc_timer: Arc<Timer>) {
match Arc::try_unwrap(arc_timer) {
Ok(timer) => timer.timeout(),
Err(_) => panic!("Timer Dropped"),
}
}
fn transfer(&mut self, mut transferable_arc_timer: Arc<Timer>, wheel_name: WheelName) {
let wheel = match wheel_name {
WheelName::Soon => &mut self.soon,
WheelName::Later => &mut self.later,
};
let slot_index = wheel.slot_index(transferable_arc_timer.monotonic);
let position = match wheel_name {
WheelName::Soon => Position::Soon { slot_index },
WheelName::Later => Position::Later { slot_index },
};
// Remove weak reference to allow `get_mut`.
let reference_number = transferable_arc_timer.reference_number;
self.timer_by_reference_number.remove(&reference_number);
*Arc::get_mut(&mut transferable_arc_timer)
.unwrap()
.position
.lock() = position;
let timeoutable = Arc::clone(&transferable_arc_timer);
let cancellable = Arc::downgrade(&transferable_arc_timer);
wheel.start(slot_index, timeoutable);
self.timer_by_reference_number
.insert(reference_number, cancellable);
}
fn transfer_later_to_soon(&mut self, soon_max_monotonic: Monotonic) {
let transferable_arc_timers: Vec<Arc<Timer>> =
self.later.drain_before_or_at(soon_max_monotonic).collect();
for arc_timer in transferable_arc_timers {
self.transfer(arc_timer, WheelName::Soon)
}
}
fn transfer_long_term_to_later(&mut self, later_max_monotonic: Monotonic) {
let transferable_arc_timers: Vec<Arc<Timer>> = self
.long_term
.drain_before_or_at(later_max_monotonic)
.collect();
for arc_timer in transferable_arc_timers {
self.transfer(arc_timer, WheelName::Later);
}
}
}
impl Debug for Hierarchy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Timers\n")?;
write!(f, "At Once:\n{:?}\n", self.at_once)?;
write!(f, "Soon:\n{:?}", self.soon)?;
write!(f, "Later:\n{:?}", self.later)?;
write!(f, "Long Term:\n{:?}\n", self.long_term)
}
}
impl Default for Hierarchy {
fn default() -> Hierarchy {
let monotonic = monotonic::time();
let soon_slot_index = SlotIndex::from_monotonic(
monotonic,
Self::SOON_TOTAL_MILLISECONDS,
Self::SOON_MILLISECONDS_PER_SLOT,
);
// round down to nearest multiple
let soon_slot_monotonic = monotonic.round_down(Self::SOON_TOTAL_MILLISECONDS.into());
let soon = Wheel::new(
Self::SOON_MILLISECONDS_PER_SLOT,
soon_slot_index,
soon_slot_monotonic,
);
// > The later wheel contain timers that are further away from 'pos'
// > than the width of the soon timer wheel.
// -- https://github.com/erlang/otp/blob/759ec896d7f254db2996cbb503c1ef883e6714b0/erts/emulator/beam/time.c#L68-L69
let later_monotonic = soon_slot_monotonic + Self::SOON_TOTAL_MILLISECONDS;
let later_slot_index = SlotIndex::from_monotonic(
later_monotonic,
Self::LATER_TOTAL_MILLISECONDS,
Self::LATER_MILLISECONDS_PER_SLOT,
);
// round down to nearest multiple
let later_slot_monotonic =
later_monotonic.round_down(Self::LATER_MILLISECONDS_PER_SLOT.into());
let later = Wheel::new(
Self::LATER_MILLISECONDS_PER_SLOT,
later_slot_index,
later_slot_monotonic,
);
Hierarchy {
at_once: Default::default(),
soon,
later,
long_term: Default::default(),
timer_by_reference_number: Default::default(),
}
}
}
// Hierarchies belong to Schedulers and Schedulers will never change threads
unsafe impl Send for Hierarchy {}
unsafe impl Sync for Hierarchy {}
#[derive(Clone, Copy)]
pub struct MillisecondsPerSlot(u64);
impl MillisecondsPerSlot {
const fn const_mul(self, slots: Slots) -> Milliseconds {
Milliseconds(self.0 * (slots.0 as u64))
}
}
impl Add<MillisecondsPerSlot> for Monotonic {
type Output = Monotonic;
fn add(self, rhs: MillisecondsPerSlot) -> Monotonic {
Self(self.0 + rhs.0)
}
}
impl AddAssign<MillisecondsPerSlot> for Monotonic {
fn add_assign(&mut self, rhs: MillisecondsPerSlot) {
self.0 += rhs.0
}
}
impl Div<MillisecondsPerSlot> for Milliseconds {
type Output = Slots;
fn div(self, rhs: MillisecondsPerSlot) -> Slots {
Slots((self.0 / rhs.0) as u16)
}
}
impl From<MillisecondsPerSlot> for u64 {
fn from(milliseconds_per_slot: MillisecondsPerSlot) -> u64 {
milliseconds_per_slot.0
}
}
impl Mul<Slots> for MillisecondsPerSlot {
type Output = Milliseconds;
fn mul(self, slots: Slots) -> Milliseconds {
self.const_mul(slots)
}
}
/// Event coming from source
#[derive(Debug)]
pub enum SourceEvent {
Message {
destination: Destination,
format: Format,
term: Term,
},
StopWaiting,
}
/// Format of `SourceEvent` `Message`
#[derive(Debug)]
pub enum Format {
/// Sends only the `Timer` `message`
Message,
/// Sends `{:timeout, timer_reference, message}`
TimeoutTuple,
}
struct Timer {
// Can't be a `Boxed` `LocalReference` `Term` because those are boxed and the original Process
// could GC the unboxed `LocalReference` `Term`.
reference_number: ReferenceNumber,
monotonic: Monotonic,
event: DestinationEvent,
position: Mutex<Position>,
}
impl Timer {
fn milliseconds_remaining(&self) -> Milliseconds {
// The timer may be read when it is past its timeout, but it has not been timed-out
// by the scheduler. Without this, an underflow would occur.
// `0` is returned on underflow because that is what Erlang returns.
match self.monotonic.checked_sub(monotonic::time()) {
Some(difference) => difference,
None => Milliseconds(0),
}
}
fn timeout(self) {
match self.event {
DestinationEvent::Message {
destination,
heap_fragment,
} => {
let option_destination_arc_process = match &destination {
Destination::Name(ref name) => registry::atom_to_process(name),
Destination::Process(destination_process_weak) => {
destination_process_weak.upgrade()
}
};
if let Some(destination_arc_process) = option_destination_arc_process {
let HeapFragment {
heap_fragment,
term,
} = heap_fragment.into_inner();
destination_arc_process.send_heap_message(heap_fragment, term);
destination_arc_process
.scheduler()
.unwrap()
.stop_waiting(&destination_arc_process);
}
}
DestinationEvent::StopWaiting { process } => {
if let Some(destination_arc_process) = process.upgrade() {
// `__lumen_builtin_receive_wait` will notice it has timed out, so only need to
// stop waiting
destination_arc_process
.scheduler()
.unwrap()
.stop_waiting(&destination_arc_process);
}
}
}
}
}
impl Debug for Timer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, " {} ", self.monotonic)?;
match &self.event {
DestinationEvent::Message {
destination,
heap_fragment,
} => {
let HeapFragment { term, .. } = *heap_fragment.lock();
write!(f, "{} -> ", term)?;
match destination {
Destination::Process(weak_process) => fmt_weak_process(weak_process, f),
Destination::Name(name) => write!(f, "{}", name),
}?;
}
DestinationEvent::StopWaiting { process } => {
fmt_weak_process(process, f)?;
write!(f, " stop waiting")?;
}
}
if self.monotonic <= monotonic::time() {
write!(f, " (expired)")?;
}
Ok(())
}
}
fn fmt_weak_process(weak_process: &Weak<Process>, f: &mut fmt::Formatter) -> fmt::Result {
match weak_process.upgrade() {
Some(arc_process) => write!(f, "{}", arc_process),
None => write!(f, "Dead Process"),
}
}
impl Eq for Timer {}
impl PartialEq<Timer> for Timer {
fn eq(&self, other: &Timer) -> bool {
self.reference_number == other.reference_number
}
}
impl Ord for Timer {
fn cmp(&self, other: &Timer) -> Ordering {
// Timers are ordered in reverse order as `BinaryHeap` is a max heap, but we want sooner
// timers at the top
other
.monotonic
.cmp(&self.monotonic)
.then_with(|| other.reference_number.cmp(&self.reference_number))
}
}
impl PartialOrd for Timer {
fn partial_cmp(&self, other: &Timer) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// Event sent to destination
enum DestinationEvent {
/// Send message in `heap_fragment` to `destination`.
Message {
destination: Destination,
heap_fragment: Mutex<HeapFragment>,
},
/// Stop `process` from waiting
StopWaiting { process: Weak<Process> },
}
#[derive(Clone, Copy)]
#[cfg_attr(debug_assertions, derive(Debug))]
enum Position {
AtOnce,
Soon { slot_index: SlotIndex },
Later { slot_index: SlotIndex },
LongTerm,
}
/// A slot in the Hierarchy (for `at_once` and `long_term`) or a slot in a `Wheel` (for `soon` and
/// `later`).
#[derive(Clone, Default)]
struct Slot(Vec<Arc<Timer>>);
impl Slot {
fn cancel(&mut self, reference_number: ReferenceNumber) -> Option<Arc<Timer>> {
self.0
.iter()
.position(|timer_rc| timer_rc.reference_number == reference_number)
.map(|index| self.0.remove(index))
}
fn drain<R>(&mut self, range: R) -> Drain<Arc<Timer>>
where
R: RangeBounds<usize>,
{
self.0.drain(range)
}
fn drain_before_or_at(&mut self, max_monotonic: Monotonic) -> Drain<Arc<Timer>> {
let exclusive_end_bound = self
.0
.binary_search_by(|arc_timer| match arc_timer.monotonic.cmp(&max_monotonic) {
Equal => Less,
ordering => ordering,
})
.unwrap_err();
self.0.drain(0..exclusive_end_bound)
}
fn is_empty(&self) -> bool {
self.0.is_empty()
}
fn start(&mut self, arc_timer: Arc<Timer>) {
let index = self
.0
.binary_search_by_key(
&(arc_timer.monotonic, arc_timer.reference_number),
|existing_arc_timer| {
(
existing_arc_timer.monotonic,
existing_arc_timer.reference_number,
)
},
)
.unwrap_err();
self.0.insert(index, arc_timer)
}
}
impl Debug for Slot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.0.is_empty() {
write!(f, " No timers\n")?;
} else {
for arc_timer in &self.0 {
write!(f, " {:?}\n", arc_timer)?;
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
struct SlotIndex(u16);
impl SlotIndex {
fn from_monotonic(
monotonic: Monotonic,
total: Milliseconds,
milliseconds_per_slot: MillisecondsPerSlot,
) -> SlotIndex {
let remaining = monotonic % total;
SlotIndex((remaining.0 / milliseconds_per_slot.0) as u16)
}
}
impl Add<u16> for SlotIndex {
type Output = SlotIndex;
fn add(self, rhs: u16) -> SlotIndex {
Self(self.0 + rhs)
}
}
impl Add<Slots> for SlotIndex {
type Output = SlotIndex;
fn add(self, rhs: Slots) -> SlotIndex {
Self(self.0 + rhs.0)
}
}
impl Rem<Slots> for SlotIndex {
type Output = SlotIndex;
fn rem(self, rhs: Slots) -> SlotIndex {
Self(self.0 % rhs.0)
}
}
#[derive(Debug, Eq, PartialEq, PartialOrd)]
pub struct Slots(u16);
struct Wheel {
milliseconds_per_slot: MillisecondsPerSlot,
total_milliseconds: Milliseconds,
slots: Vec<Slot>,
slot_index: SlotIndex,
slot_monotonic: Monotonic,
}
impl Wheel {
// same as values used in BEAM
const SLOTS: Slots = Slots(1 << 14);
fn new(
milliseconds_per_slot: MillisecondsPerSlot,
slot_index: SlotIndex,
slot_monotonic: Monotonic,
) -> Wheel {
Wheel {
milliseconds_per_slot,
total_milliseconds: milliseconds_per_slot * Self::SLOTS,
slots: vec![Default::default(); Self::SLOTS.0 as usize],
slot_index,
slot_monotonic,
}
}
fn cancel(
&mut self,
slot_index: SlotIndex,
reference_number: ReferenceNumber,
) -> Option<Arc<Timer>> {
self.slots[slot_index.0 as usize].cancel(reference_number)
}
fn drain<R>(&mut self, range: R) -> Drain<Arc<Timer>>
where
R: RangeBounds<usize>,
{
self.slots[self.slot_index.0 as usize].drain(range)
}
fn drain_before_or_at(&mut self, max_monotonic: Monotonic) -> Drain<Arc<Timer>> {
self.slots[self.slot_index.0 as usize].drain_before_or_at(max_monotonic)
}
fn is_empty(&self) -> bool {
self.slots[self.slot_index.0 as usize].is_empty()
}
fn max_monotonic(&self) -> Monotonic {
self.slot_monotonic + self.total_milliseconds - Milliseconds(1)
}
fn next_slot(&mut self) {
self.slot_index = (self.slot_index + 1) % Self::SLOTS;
self.slot_monotonic += self.milliseconds_per_slot;
}
fn next_slot_monotonic(&self) -> Monotonic {
self.slot_monotonic + self.milliseconds_per_slot
}
fn slot_index(&self, monotonic: Monotonic) -> SlotIndex {
let milliseconds = monotonic - self.slot_monotonic;
let slots = milliseconds / self.milliseconds_per_slot;
assert!(slots < Wheel::SLOTS, "monotonic ({:?}) is {:?} milliseconds ({:?} slots) away from slot_monotonic {:?}, but wheel only has {:?} slots ", monotonic, milliseconds, slots, self.slot_monotonic, Wheel::SLOTS);
(self.slot_index + slots) % Wheel::SLOTS
}
fn start(&mut self, slot_index: SlotIndex, arc_timer: Arc<Timer>) {
self.slots[slot_index.0 as usize].start(arc_timer)
}
}
impl Debug for Wheel {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(
f,
" milliseconds per slot: {:?}",
self.milliseconds_per_slot.0
)?;
writeln!(f, " slots: {:?}", self.slots.len())?;
writeln!(f, " ____________")?;
writeln!(f, " total milliseconds: {:?}", self.total_milliseconds)?;
writeln!(f, "")?;
writeln!(f, " slot index: {}", self.slot_index.0)?;
write!(f, " slot time: {} ms", self.slot_monotonic)?;
if self.slot_monotonic <= monotonic::time() {
writeln!(f, " (expired)")?;
}
let mut has_timers = false;
for slot in &self.slots {
for arc_timer in &slot.0 {
has_timers = true;
writeln!(f, "{:?}", arc_timer)?;
}
}
if !has_timers {
writeln!(f, " No timers")?;
}
Ok(())
}
}
impl Index<u16> for Wheel {
type Output = Slot;
fn index(&self, slot_index: u16) -> &Slot {
self.slots.index(slot_index as usize)
}
}
impl IndexMut<u16> for Wheel {
fn index_mut(&mut self, slot_index: u16) -> &mut Slot {
self.slots.index_mut(slot_index as usize)
}
}
enum WheelName {
Soon,
Later,
}
pub fn at_once_milliseconds() -> Milliseconds {
Milliseconds(0)
}
pub fn soon_milliseconds() -> Milliseconds {
let milliseconds = Milliseconds(1);
assert!(milliseconds < Hierarchy::SOON_TOTAL_MILLISECONDS);
milliseconds
}
pub fn later_milliseconds() -> Milliseconds {
let milliseconds = Hierarchy::SOON_TOTAL_MILLISECONDS + Milliseconds(1);
assert!(Hierarchy::SOON_TOTAL_MILLISECONDS < milliseconds);
assert!(milliseconds < Hierarchy::LATER_TOTAL_MILLISECONDS);
milliseconds
}
pub fn long_term_milliseconds() -> Milliseconds {
let milliseconds =
Hierarchy::SOON_TOTAL_MILLISECONDS + Hierarchy::LATER_TOTAL_MILLISECONDS + Milliseconds(1);
assert!(Hierarchy::SOON_TOTAL_MILLISECONDS < milliseconds);
assert!(
(Hierarchy::SOON_TOTAL_MILLISECONDS + Hierarchy::LATER_TOTAL_MILLISECONDS) < milliseconds
);
milliseconds
}
|
use crate::sig::*;
use nom::{
bytes::complete::{tag, take},
IResult,
};
use std::fmt;
#[derive(Debug)]
pub struct BarpbresFe {
source: Vec<u8>,
}
impl HasWrite for BarpbresFe {
fn write(&self) -> Vec<u8> {
let mut out = self.name().as_bytes().to_vec();
out.extend(&self.source);
out
}
fn name(&self) -> &str {
"barpbres.fe"
}
}
impl fmt::Display for BarpbresFe {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} source.len: {}", &self.name(), &self.source.len())
}
}
pub fn read_barpbres_fe(i: &[u8]) -> IResult<&[u8], BarpbresFe> {
let (i, _) = tag("barpbres.fe")(i)?;
let (i, source) = take(10u8)(i)?;
Ok((
i,
BarpbresFe {
source: source.to_vec(),
},
))
}
|
use matches::matches;
use super::*;
use crate::key::Key;
use crate::{Batching, Datastore};
pub fn test_basic_put_get<D: Datastore>(ds: &D) {
let k = Key::new("foo");
let v = b"Hello Datastore!";
ds.put(k.clone(), v.to_vec()).unwrap();
let have = ds.has(&k).unwrap();
assert!(have);
let size = ds.get_size(&k).unwrap();
assert_eq!(size, v.len());
let out = ds.get(&k).unwrap();
assert_eq!(out.as_slice(), v.as_ref());
// again after get
let have = ds.has(&k).unwrap();
assert!(have);
let size = ds.get_size(&k).unwrap();
assert_eq!(size, v.len());
ds.delete(&k).unwrap();
let have = ds.has(&k).unwrap();
assert!(!have);
let r = ds.get_size(&k);
assert!(matches!(r, Err(DSError::NotFound(_))));
}
pub fn test_not_founds<D: Datastore>(ds: &D) {
let badk = Key::new("notreal");
let r = ds.get(&badk);
assert!(matches!(r, Err(DSError::NotFound(_))));
let has = ds.has(&badk).unwrap();
assert!(!has);
let r = ds.get_size(&badk);
assert!(matches!(r, Err(DSError::NotFound(_))));
}
// TODO query limit
// TODO query order
// TODO manykeysandquery
pub fn test_basic_sync<D: Datastore>(ds: &D) {
ds.sync(&Key::new("foo")).unwrap();
ds.put(Key::new("/foo"), b"foo".to_vec()).unwrap();
ds.sync(&Key::new("/foo")).unwrap();
ds.put(Key::new("/foo/bar"), b"bar".to_vec()).unwrap();
ds.sync(&Key::new("/foo")).unwrap();
ds.sync(&Key::new("/foo/bar")).unwrap();
ds.sync(&Key::new("")).unwrap();
}
// TODO query
pub fn test_batch<D: Batching>(ds: &D) {
let mut batch = ds.batch().unwrap();
let mut blocks = vec![];
let mut keys = vec![];
for _ in 0..20 {
let blk: [u8; 32] = random!();
let key = Key::new(String::from_utf8_lossy(&blk[..8]));
keys.push(key.clone());
blocks.push(blk);
batch.put(key, blk.to_vec()).unwrap();
}
for k in keys.iter() {
let r = ds.get(k);
assert!(matches!(r, Err(DSError::NotFound(_))));
}
ds.commit(batch).unwrap();
for (i, k) in keys.iter().enumerate() {
let r = ds.get(k).unwrap();
assert_eq!(r.as_slice(), blocks[i].as_ref())
}
}
pub fn test_batch_delete<D: Batching>(ds: &D) {
let mut keys = vec![];
for _ in 0..20 {
let blk: [u8; 16] = random!();
let key = Key::new(String::from_utf8_lossy(&blk[..8]));
keys.push(key.clone());
ds.put(key, blk.to_vec()).unwrap();
}
let mut batch = ds.batch().unwrap();
for k in keys.iter() {
batch.delete(k).unwrap();
}
ds.commit(batch).unwrap();
for k in keys.iter() {
let r = ds.get(k);
assert!(matches!(r, Err(DSError::NotFound(_))));
}
}
pub fn test_batch_put_and_delete<D: Batching>(ds: &D) {
let mut batch = ds.batch().unwrap();
let ka = Key::new("/a");
let kb = Key::new("/b");
batch.put(ka.clone(), [1_u8].to_vec()).unwrap();
batch.put(kb.clone(), [2_u8].to_vec()).unwrap();
batch.delete(&ka).unwrap();
batch.delete(&kb).unwrap();
batch.put(kb.clone(), [3_u8].to_vec()).unwrap();
ds.commit(batch).unwrap();
let out = ds.get(&kb).unwrap();
assert_eq!(out.as_slice(), [3_u8].as_ref());
}
|
// Copyright 2020-2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![doc(hidden)]
// We want to keep the names here
#![allow(clippy::module_name_repetitions)]
use crate::{
ast::{
base_expr, query, upable::Upable, ArrayPattern, ArrayPredicatePattern, AssignPattern,
BinExpr, BinOpKind, Bytes, BytesPart, ClauseGroup, Comprehension, ComprehensionCase,
Costly, DefaultCase, EmitExpr, EventPath, Expr, ExprPath, Expression, Field, FnDecl, FnDoc,
Helper, Ident, IfElse, ImutExpr, ImutExprInt, Invocable, Invoke, InvokeAggr, InvokeAggrFn,
List, Literal, LocalPath, Match, Merge, MetadataPath, ModDoc, NodeMetas, Patch,
PatchOperation, Path, Pattern, PredicateClause, PredicatePattern, Record, RecordPattern,
Recur, ReservedPath, Script, Segment, StatePath, StrLitElement, StringLit, TestExpr,
TuplePattern, UnaryExpr, UnaryOpKind,
},
errors::{
err_generic, error_generic, error_missing_effector, error_oops, Error, ErrorKind, Result,
},
impl_expr, impl_expr_exraw,
pos::{Location, Range},
prelude::*,
registry::CustomFn,
tilde::Extractor,
KnownKey, Value,
};
pub use base_expr::BaseExpr;
use beef::Cow;
use halfbrown::HashMap;
pub use query::*;
use serde::Serialize;
/// A raw script we got to put this here because of silly lalrpoop focing it to be public
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ScriptRaw<'script> {
exprs: ExprsRaw<'script>,
doc: Option<Vec<Cow<'script, str>>>,
}
impl<'script> ScriptRaw<'script> {
pub(crate) fn new(exprs: ExprsRaw<'script>, doc: Option<Vec<Cow<'script, str>>>) -> Self {
Self { exprs, doc }
}
pub(crate) fn up_script<'registry>(
self,
mut helper: &mut Helper<'script, 'registry>,
) -> Result<Script<'script>> {
let mut exprs = vec![];
let last_idx = self.exprs.len() - 1;
for (i, e) in self.exprs.into_iter().enumerate() {
match e {
ExprRaw::Module(m) => {
m.define(&mut helper)?;
}
ExprRaw::Const {
name,
expr,
start,
end,
comment,
} => {
let name_v = vec![name.to_string()];
let r = Range::from((start, end));
let expr = expr.up(&mut helper)?.try_reduce(helper)?;
let v = expr.try_into_value(helper)?;
let value_type = v.value_type();
let idx = helper.consts.insert(name_v, v).map_err(|_old| {
Error::from(ErrorKind::DoubleConst(
r.expand_lines(2),
r,
name.to_string(),
))
})?;
if i == last_idx {
exprs.push(Expr::Imut(ImutExprInt::Local {
is_const: true,
idx,
mid: helper.add_meta_w_name(start, end, &name),
}));
}
helper.add_const_doc(&name, comment, value_type);
}
ExprRaw::FnDecl(f) => {
helper.docs.fns.push(f.doc());
let f = f.up(&mut helper)?;
helper.register_fun(f.into())?;
}
other => exprs.push(other.up(&mut helper)?),
}
}
// We make sure the if we return `event` we turn it into `emit event`
// While this is not required logically it allows us to
// take advantage of the `emit event` optimisation
if let Some(e) = exprs.last_mut() {
if let Expr::Imut(ImutExprInt::Path(Path::Event(p))) = e {
if p.segments.is_empty() {
let expr = EmitExpr {
mid: p.mid(),
expr: ImutExprInt::Path(Path::Event(p.clone())),
port: None,
};
*e = Expr::Emit(Box::new(expr));
}
}
} else {
let expr = EmitExpr {
mid: 0,
expr: ImutExprInt::Path(Path::Event(EventPath {
mid: 0,
segments: vec![],
})),
port: None,
};
exprs.push(Expr::Emit(Box::new(expr)));
}
helper.docs.module = Some(ModDoc {
name: "self".into(),
doc: self
.doc
.map(|d| d.iter().map(|l| l.trim()).collect::<Vec<_>>().join("\n")),
});
Ok(Script {
imports: vec![], // Compiled out
exprs,
consts: helper.consts.clone(),
aggregates: helper.aggregates.clone(),
windows: helper.windows.clone(),
locals: helper.locals.len(),
node_meta: helper.meta.clone(),
functions: helper.func_vec.clone(),
docs: helper.docs.clone(),
})
}
}
#[derive(Debug, PartialEq, Serialize, Clone, Copy)]
pub enum BytesDataType {
SignedInteger,
UnsignedInteger,
Binary,
}
impl Default for BytesDataType {
fn default() -> Self {
BytesDataType::UnsignedInteger
}
}
#[derive(Debug, PartialEq, Serialize, Clone, Copy)]
pub enum Endian {
Little,
Big,
}
impl Default for Endian {
fn default() -> Self {
Endian::Big
}
}
#[derive(Debug, PartialEq, Serialize, Clone)]
pub struct BytesPartRaw<'script> {
pub start: Location,
pub end: Location,
pub data: ImutExprRaw<'script>,
pub data_type: IdentRaw<'script>,
pub bits: Option<i64>,
}
impl_expr!(BytesPartRaw);
impl<'script> Default for BytesPartRaw<'script> {
fn default() -> Self {
BytesPartRaw {
start: Location::default(),
end: Location::default(),
data: ImutExprRaw::Literal(LiteralRaw::default()),
data_type: IdentRaw::default(),
bits: None,
}
}
}
impl<'script> Upable<'script> for BytesPartRaw<'script> {
type Target = BytesPart<'script>;
// We allow this for casting the bits
#[allow(clippy::cast_sign_loss)]
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let data_type: Vec<&str> = self.data_type.id.split('-').collect();
let (data_type, endianess) = match data_type.as_slice() {
["binary"] => (BytesDataType::Binary, Endian::Big),
[]
| ["" | "integer" | "big" | "unsigned"]
| ["unsigned" | "big", "integer"]
| ["big", "unsigned", "integer"] => (BytesDataType::UnsignedInteger, Endian::Big),
["signed", "integer"] | ["big", "signed", "integer"] => {
(BytesDataType::SignedInteger, Endian::Big)
}
["little"] | ["little", "integer"] | ["little", "unsigned", "integer"] => {
(BytesDataType::UnsignedInteger, Endian::Little)
}
["little", "signed", "integer"] => (BytesDataType::SignedInteger, Endian::Little),
other => {
return Err(err_generic(
&self,
&self,
&format!("Not a valid data type: '{}'", other.join("-")),
&helper.meta,
))
}
};
let bits = if let Some(bits) = self.bits {
if bits <= 0 || bits > 64 {
return Err(err_generic(
&self,
&self,
&format!("negative bits or bits > 64 are are not allowed: {}", bits),
&helper.meta,
));
}
bits as u64
} else {
match data_type {
BytesDataType::SignedInteger | BytesDataType::UnsignedInteger => 8,
BytesDataType::Binary => 0,
}
};
Ok(BytesPart {
mid: helper.add_meta(self.start, self.end),
data: self.data.up(helper).map(ImutExpr)?,
data_type,
endianess,
bits,
})
}
}
#[derive(Debug, PartialEq, Serialize, Clone)]
pub struct BytesRaw<'script> {
pub start: Location,
pub end: Location,
pub bytes: Vec<BytesPartRaw<'script>>,
}
impl_expr!(BytesRaw);
impl<'script> Upable<'script> for BytesRaw<'script> {
type Target = Bytes<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(Bytes {
mid: helper.add_meta(self.start, self.end),
value: self
.bytes
.into_iter()
.map(|b| b.up(helper))
.collect::<Result<_>>()?,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Debug, PartialEq, Serialize, Clone)]
pub struct ModuleRaw<'script> {
pub start: Location,
pub end: Location,
pub name: IdentRaw<'script>,
pub exprs: ExprsRaw<'script>,
pub doc: Option<Vec<Cow<'script, str>>>,
}
impl_expr!(ModuleRaw);
impl<'script> ModuleRaw<'script> {
pub(crate) fn define<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<()> {
helper.module.push(self.name.to_string());
for e in self.exprs {
match e {
ExprRaw::Module(m) => {
m.define(helper)?;
}
ExprRaw::Const {
name,
expr,
start,
end,
..
} => {
let mut name_v = helper.module.clone();
name_v.push(name.to_string());
let expr = expr.up(helper)?;
let v = expr.try_into_value(helper)?;
helper.consts.insert(name_v, v).map_err(|_old| {
let r = Range::from((start, end));
ErrorKind::DoubleConst(r.expand_lines(2), r, name.to_string())
})?;
}
ExprRaw::FnDecl(f) => {
let f = f.up(helper)?;
let f = CustomFn {
name: f.name.id,
args: f.args.iter().map(ToString::to_string).collect(),
locals: f.locals,
body: f.body,
is_const: false, // TODO: we should find a way to examine this
open: f.open,
inline: f.inline,
};
helper.register_fun(f)?;
}
// ALLOW: the gramer doesn't allow this
_ => unreachable!("Can't have expressions inside of modules"),
}
}
helper.module.pop();
Ok(())
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Debug, PartialEq, Serialize, Clone, Default)]
pub struct IdentRaw<'script> {
pub start: Location,
pub end: Location,
pub id: beef::Cow<'script, str>,
}
impl_expr!(IdentRaw);
impl<'script> ToString for IdentRaw<'script> {
fn to_string(&self) -> String {
self.id.to_string()
}
}
impl<'script> Upable<'script> for IdentRaw<'script> {
type Target = Ident<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(Self::Target {
mid: helper.add_meta_w_name(self.start, self.end, &self.id),
id: self.id,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct FieldRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) name: StringLitRaw<'script>,
pub(crate) value: ImutExprRaw<'script>,
}
impl<'script> Upable<'script> for FieldRaw<'script> {
type Target = Field<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let name = self.name.up(helper)?;
Ok(Field {
mid: helper.add_meta(self.start, self.end),
name,
value: self.value.up(helper)?,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct RecordRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) fields: FieldsRaw<'script>,
}
impl_expr!(RecordRaw);
impl<'script> Upable<'script> for RecordRaw<'script> {
type Target = Record<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(Record {
base: crate::Object::new(),
mid: helper.add_meta(self.start, self.end),
fields: self.fields.up(helper)?,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ListRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) exprs: ImutExprsRaw<'script>,
}
impl_expr!(ListRaw);
impl<'script> Upable<'script> for ListRaw<'script> {
type Target = List<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(List {
mid: helper.add_meta(self.start, self.end),
exprs: self.exprs.up(helper)?.into_iter().map(ImutExpr).collect(),
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize, Default)]
pub struct LiteralRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) value: Value<'script>,
}
impl_expr!(LiteralRaw);
impl<'script> Upable<'script> for LiteralRaw<'script> {
type Target = Literal<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(Literal {
mid: helper.add_meta(self.start, self.end),
value: self.value,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StringLitRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) elements: StrLitElementsRaw<'script>,
}
#[cfg(not(feature = "erlang-float-testing"))]
fn to_strl_elem(l: &Literal) -> StrLitElement<'static> {
l.value.as_str().map_or_else(
|| StrLitElement::Lit(l.value.encode().into()),
|s| StrLitElement::Lit(s.to_string().into()),
)
}
// TODO: The float scenario is different in erlang and rust
// We knowingly excluded float correctness in string interpolation
// as we don't want to over engineer and write own format functions.
// any suggestions are welcome
#[cfg(feature = "erlang-float-testing")]
#[cfg(not(tarpaulin_include))]
fn to_strl_elem(l: &Literal) -> StrLitElement<'static> {
l.value.as_str().map_or_else(
|| {
if let Some(_f) = l.value.as_f64() {
StrLitElement::Lit("42".into())
} else {
StrLitElement::Lit(
crate::utils::sorted_serialize(&l.value)
.unwrap_or_default()
.into(),
)
}
},
|s| StrLitElement::Lit(s.to_string().into()),
)
}
impl<'script> Upable<'script> for StringLitRaw<'script> {
type Target = StringLit<'script>;
fn up<'registry>(mut self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let mid = helper.add_meta(self.start, self.end);
self.elements.reverse();
let mut new = Vec::with_capacity(self.elements.len());
for e in self.elements {
let next = match e {
StrLitElementRaw::Expr(e) => {
let i = e.up(helper)?;
let i = i.try_reduce(helper)?;
if let ImutExprInt::Literal(l) = i {
to_strl_elem(&l)
} else {
StrLitElement::Expr(i)
}
}
StrLitElementRaw::Lit(l) => StrLitElement::Lit(l),
};
if let StrLitElement::Lit(next_lit) = next {
if let Some(prev) = new.pop() {
match prev {
StrLitElement::Lit(l) => {
let mut o = l.into_owned();
o.push_str(&next_lit);
new.push(StrLitElement::Lit(o.into()));
}
prev @ StrLitElement::Expr(..) => {
new.push(prev);
new.push(StrLitElement::Lit(next_lit));
}
}
} else {
new.push(StrLitElement::Lit(next_lit));
}
} else {
new.push(next);
}
}
Ok(StringLit { mid, elements: new })
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum StrLitElementRaw<'script> {
Lit(Cow<'script, str>),
Expr(ImutExprRaw<'script>),
}
impl<'script> From<ImutExprRaw<'script>> for StrLitElementRaw<'script> {
fn from(e: ImutExprRaw<'script>) -> Self {
StrLitElementRaw::Expr(e)
}
}
impl<'script> From<Cow<'script, str>> for StrLitElementRaw<'script> {
fn from(e: Cow<'script, str>) -> Self {
StrLitElementRaw::Lit(e)
}
}
impl<'script> From<&'script str> for StrLitElementRaw<'script> {
fn from(e: &'script str) -> Self {
StrLitElementRaw::Lit(e.into())
}
}
/// we're forced to make this pub because of lalrpop
pub type StrLitElementsRaw<'script> = Vec<StrLitElementRaw<'script>>;
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum ExprRaw<'script> {
/// we're forced to make this pub because of lalrpop
Const {
/// we're forced to make this pub because of lalrpop
name: Cow<'script, str>,
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
/// we're forced to make this pub because of lalrpop
start: Location,
/// we're forced to make this pub because of lalrpop
end: Location,
/// we're forced to make this pub because of lalrpop
comment: Option<Vec<Cow<'script, str>>>,
},
/// we're forced to make this pub because of lalrpop
Module(ModuleRaw<'script>),
/// we're forced to make this pub because of lalrpop
MatchExpr(Box<MatchRaw<'script, Self>>),
/// we're forced to make this pub because of lalrpop
Assign(Box<AssignRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Comprehension(Box<ComprehensionRaw<'script, Self>>),
Drop {
/// we're forced to make this pub because of lalrpop
start: Location,
/// we're forced to make this pub because of lalrpop
end: Location,
},
/// we're forced to make this pub because of lalrpop
Emit(Box<EmitExprRaw<'script>>),
/// we're forced to make this pub because of lalrpop
FnDecl(AnyFnRaw<'script>),
/// we're forced to make this pub because of lalrpop
Imut(ImutExprRaw<'script>),
}
impl<'script> ExpressionRaw<'script> for ExprRaw<'script> {}
fn is_one_simple_group<'script>(patterns: &[ClauseGroup<'script, Expr<'script>>]) -> bool {
let is_one = patterns.len() == 1;
let is_simple = patterns
.first()
.map(|cg| {
if let ClauseGroup::Simple {
precondition: None,
patterns,
} = cg
{
patterns.len() == 1
} else {
false
}
})
.unwrap_or_default();
is_one && is_simple
}
impl<'script> Upable<'script> for ExprRaw<'script> {
type Target = Expr<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(match self {
ExprRaw::FnDecl(_) | ExprRaw::Const { .. } | ExprRaw::Module(ModuleRaw { .. }) => {
// ALLOW: There is no code path that leads here,
unreachable!()
}
ExprRaw::MatchExpr(m) => match m.up(helper)? {
Match {
mid,
target,
mut patterns,
default,
} if is_one_simple_group(&patterns) => {
if let Some(ClauseGroup::Simple {
precondition: None,
mut patterns,
}) = patterns.pop()
{
if let Some(if_clause) = patterns.pop() {
let ie = IfElse {
mid,
target,
if_clause,
else_clause: default,
};
Expr::IfElse(Box::new(ie))
} else {
return Err("Invalid group clause with 0 patterns".into());
}
} else {
// ALLOW: we check patterns.len() above
unreachable!()
}
}
m => Expr::Match(Box::new(m)),
},
ExprRaw::Assign(a) => {
let path = a.path.up(helper)?;
let mid = helper.add_meta(a.start, a.end);
match a.expr.up(helper)? {
Expr::Imut(ImutExprInt::Merge(m)) => Expr::Assign {
mid,
path,
expr: Box::new(ImutExprInt::Merge(m).into()),
},
Expr::Imut(ImutExprInt::Patch(m)) => Expr::Assign {
mid,
path,
expr: Box::new(ImutExprInt::Patch(m).into()),
},
expr => Expr::Assign {
mid,
path,
expr: Box::new(expr),
},
}
}
ExprRaw::Comprehension(c) => Expr::Comprehension(Box::new(c.up(helper)?)),
ExprRaw::Drop { start, end } => {
let mid = helper.add_meta(start, end);
if !helper.can_emit {
return Err(ErrorKind::InvalidDrop(
Range(start, end).expand_lines(2),
Range(start, end),
)
.into());
}
Expr::Drop { mid }
}
ExprRaw::Emit(e) => Expr::Emit(Box::new(e.up(helper)?)),
ExprRaw::Imut(i) => i.up(helper)?.into(),
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct FnDeclRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) name: IdentRaw<'script>,
pub(crate) args: Vec<IdentRaw<'script>>,
pub(crate) body: ExprsRaw<'script>,
pub(crate) doc: Option<Vec<Cow<'script, str>>>,
pub(crate) open: bool,
pub(crate) inline: bool,
}
impl_expr!(FnDeclRaw);
impl<'script> FnDeclRaw<'script> {
pub(crate) fn doc(&self) -> FnDoc {
FnDoc {
name: self.name.to_string(),
args: self.args.iter().map(|a| a.to_string()).collect(),
open: self.open,
doc: self
.doc
.clone()
.map(|d| d.iter().map(|l| l.trim()).collect::<Vec<_>>().join("\n")),
}
}
}
impl<'script> Upable<'script> for FnDeclRaw<'script> {
type Target = FnDecl<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let can_emit = helper.can_emit;
let mut aggrs = Vec::new();
let mut locals: HashMap<_, _> = self
.args
.iter()
.enumerate()
.map(|(i, a)| (a.to_string(), i))
.collect();
helper.can_emit = false;
helper.is_open = self.open;
helper.fn_argc = self.args.len();
helper.swap(&mut aggrs, &mut locals);
helper.possible_leaf = true;
let body = self.body.up(helper)?;
helper.possible_leaf = false;
helper.swap(&mut aggrs, &mut locals);
helper.can_emit = can_emit;
let name = self.name.up(helper)?;
Ok(FnDecl {
mid: helper.add_meta_w_name(self.start, self.end, &name.id),
name,
args: self.args.up(helper)?,
body,
locals: locals.len(),
open: self.open,
inline: self.inline,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum AnyFnRaw<'script> {
/// we're forced to make this pub because of lalrpop
Match(MatchFnDeclRaw<'script>),
/// we're forced to make this pub because of lalrpop
Normal(FnDeclRaw<'script>),
}
impl<'script> AnyFnRaw<'script> {
pub(crate) fn doc(&self) -> FnDoc {
match self {
AnyFnRaw::Match(f) => f.doc(),
AnyFnRaw::Normal(f) => f.doc(),
}
}
}
impl<'script> Upable<'script> for AnyFnRaw<'script> {
type Target = FnDecl<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
match self {
AnyFnRaw::Normal(f) => f.up(helper),
AnyFnRaw::Match(f) => f.up(helper),
}
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MatchFnDeclRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) name: IdentRaw<'script>,
pub(crate) args: Vec<IdentRaw<'script>>,
pub(crate) cases: Vec<PredicateClauseRaw<'script, ExprRaw<'script>>>,
pub(crate) doc: Option<Vec<Cow<'script, str>>>,
pub(crate) open: bool,
pub(crate) inline: bool,
}
impl_expr!(MatchFnDeclRaw);
impl<'script> MatchFnDeclRaw<'script> {
pub(crate) fn doc(&self) -> FnDoc {
FnDoc {
name: self.name.to_string(),
args: self.args.iter().map(|a| a.to_string()).collect(),
open: self.open,
doc: self
.doc
.clone()
.map(|d| d.iter().map(|l| l.trim()).collect::<Vec<_>>().join("\n")),
}
}
}
impl<'script> Upable<'script> for MatchFnDeclRaw<'script> {
type Target = FnDecl<'script>;
fn up<'registry>(mut self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let can_emit = helper.can_emit;
let mut aggrs = Vec::new();
let mut locals = HashMap::new();
for (i, a) in self.args.iter().enumerate() {
locals.insert(a.to_string(), i);
}
helper.is_open = self.open;
helper.fn_argc = self.args.len();
helper.can_emit = false;
helper.swap(&mut aggrs, &mut locals);
let target = self
.args
.iter()
.map(|a| {
ImutExprRaw::Path(PathRaw::Local(LocalPathRaw {
start: a.start,
end: a.end,
segments: vec![SegmentRaw::from_id(a.clone())],
}))
})
.collect();
let mut patterns = Vec::new();
std::mem::swap(&mut self.cases, &mut patterns);
let patterns = patterns
.into_iter()
.map(|mut c: PredicateClauseRaw<_>| {
if c.pattern != PatternRaw::Default {
let args = self.args.iter().enumerate();
let mut exprs: Vec<_> = args
.map(|(i, a)| {
ExprRaw::Assign(Box::new(AssignRaw {
start: c.start,
end: c.end,
path: PathRaw::Local(LocalPathRaw {
start: a.start,
end: a.end,
segments: vec![SegmentRaw::from_id(a.clone())],
}),
expr: ExprRaw::Imut(ImutExprRaw::Path(PathRaw::Local(
LocalPathRaw {
start: a.start,
end: a.end,
segments: vec![
SegmentRaw::from_str(FN_RES_NAME, a.start, a.end),
SegmentRaw::from_usize(i, a.start, a.end),
],
},
))),
}))
})
.collect();
exprs.append(&mut c.exprs);
c.exprs = exprs;
}
c
})
.collect();
let body = ExprRaw::MatchExpr(Box::new(MatchRaw {
start: self.start,
end: self.end,
target: ImutExprRaw::List(Box::new(ListRaw {
start: self.start,
end: self.end,
exprs: target,
})),
patterns,
}));
helper.possible_leaf = true;
let body = body.up(helper)?;
helper.possible_leaf = false;
let body = vec![body];
helper.swap(&mut aggrs, &mut locals);
helper.can_emit = can_emit;
let name = self.name.up(helper)?;
Ok(FnDecl {
mid: helper.add_meta_w_name(self.start, self.end, &name),
name,
args: self.args.up(helper)?,
body,
locals: locals.len(),
open: self.open,
inline: self.inline,
})
}
}
/// A raw expression
pub trait ExpressionRaw<'script>:
Clone + std::fmt::Debug + PartialEq + Serialize + Upable<'script>
where
<Self as Upable<'script>>::Target: Expression + 'script,
{
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum ImutExprRaw<'script> {
/// we're forced to make this pub because of lalrpop
Record(Box<RecordRaw<'script>>),
/// we're forced to make this pub because of lalrpop
List(Box<ListRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Patch(Box<PatchRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Merge(Box<MergeRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Match(Box<MatchRaw<'script, Self>>),
/// we're forced to make this pub because of lalrpop
Comprehension(Box<ComprehensionRaw<'script, Self>>),
/// we're forced to make this pub because of lalrpop
Path(PathRaw<'script>),
/// we're forced to make this pub because of lalrpop
Binary(Box<BinExprRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Unary(Box<UnaryExprRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Literal(LiteralRaw<'script>),
/// we're forced to make this pub because of lalrpop
Invoke(InvokeRaw<'script>),
/// we're forced to make this pub because of lalrpop
Present {
/// we're forced to make this pub because of lalrpop
path: PathRaw<'script>,
/// we're forced to make this pub because of lalrpop
start: Location,
/// we're forced to make this pub because of lalrpop
end: Location,
},
/// we're forced to make this pub because of lalrpop
String(StringLitRaw<'script>),
/// we're forced to make this pub because of lalrpop
Recur(RecurRaw<'script>),
/// bytes
Bytes(BytesRaw<'script>),
}
impl<'script> ExpressionRaw<'script> for ImutExprRaw<'script> {}
impl<'script> Upable<'script> for ImutExprRaw<'script> {
type Target = ImutExprInt<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let was_leaf = helper.possible_leaf;
helper.possible_leaf = false;
let r = match self {
ImutExprRaw::Recur(r) => {
helper.possible_leaf = was_leaf;
ImutExprInt::Recur(r.up(helper)?)
}
ImutExprRaw::Binary(b) => {
ImutExprInt::Binary(Box::new(b.up(helper)?)).try_reduce(helper)?
}
ImutExprRaw::Unary(u) => {
ImutExprInt::Unary(Box::new(u.up(helper)?)).try_reduce(helper)?
}
ImutExprRaw::String(s) => ImutExprInt::String(s.up(helper)?).try_reduce(helper)?,
ImutExprRaw::Record(r) => ImutExprInt::Record(r.up(helper)?).try_reduce(helper)?,
ImutExprRaw::List(l) => ImutExprInt::List(l.up(helper)?).try_reduce(helper)?,
ImutExprRaw::Patch(p) => {
ImutExprInt::Patch(Box::new(p.up(helper)?)).try_reduce(helper)?
}
ImutExprRaw::Merge(m) => {
ImutExprInt::Merge(Box::new(m.up(helper)?)).try_reduce(helper)?
}
ImutExprRaw::Present { path, start, end } => ImutExprInt::Present {
path: path.up(helper)?,
mid: helper.add_meta(start, end),
}
.try_reduce(helper)?,
ImutExprRaw::Path(p) => match p.up(helper)? {
Path::Local(LocalPath {
is_const,
mid,
idx,
ref segments,
}) if segments.is_empty() => ImutExprInt::Local { mid, idx, is_const },
p => ImutExprInt::Path(p),
}
.try_reduce(helper)?,
ImutExprRaw::Literal(l) => ImutExprInt::Literal(l.up(helper)?).try_reduce(helper)?,
ImutExprRaw::Invoke(i) => {
if i.is_aggregate(helper) {
ImutExprInt::InvokeAggr(i.into_aggregate().up(helper)?)
} else {
let i = i.up(helper)?;
let i = if i.can_inline() {
i.inline()?
} else {
match i.args.len() {
1 => ImutExprInt::Invoke1(i),
2 => ImutExprInt::Invoke2(i),
3 => ImutExprInt::Invoke3(i),
_ => ImutExprInt::Invoke(i),
}
};
i.try_reduce(helper)?
}
}
ImutExprRaw::Match(m) => {
helper.possible_leaf = was_leaf;
ImutExprInt::Match(Box::new(m.up(helper)?))
}
ImutExprRaw::Comprehension(c) => ImutExprInt::Comprehension(Box::new(c.up(helper)?)),
ImutExprRaw::Bytes(b) => ImutExprInt::Bytes(b.up(helper)?).try_reduce(helper)?,
};
helper.possible_leaf = was_leaf;
Ok(r)
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct RecurRaw<'script> {
pub start: Location,
pub end: Location,
pub exprs: ImutExprsRaw<'script>,
}
impl_expr!(RecurRaw);
impl<'script> Upable<'script> for RecurRaw<'script> {
type Target = Recur<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let was_leaf = helper.possible_leaf;
helper.possible_leaf = false;
if !was_leaf {
return Err(ErrorKind::InvalidRecur(
self.extent(&helper.meta).expand_lines(2),
self.extent(&helper.meta),
)
.into());
};
if (helper.is_open && helper.fn_argc < self.exprs.len())
|| (!helper.is_open && helper.fn_argc != self.exprs.len())
{
return error_generic(
&self,
&self,
&format!(
"Wrong number of arguments expected {} but got {}",
helper.fn_argc,
self.exprs.len()
),
&helper.meta,
);
}
let exprs = self.exprs.up(helper)?.into_iter().map(ImutExpr).collect();
helper.possible_leaf = was_leaf;
Ok(Recur {
mid: helper.add_meta(self.start, self.end),
argc: helper.fn_argc,
open: helper.is_open,
exprs,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct EmitExprRaw<'script> {
pub start: Location,
pub end: Location,
pub expr: ImutExprRaw<'script>,
pub port: Option<ImutExprRaw<'script>>,
}
impl_expr!(EmitExprRaw);
impl<'script> Upable<'script> for EmitExprRaw<'script> {
type Target = EmitExpr<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
if !helper.can_emit {
return Err(ErrorKind::InvalidEmit(
self.extent(&helper.meta).expand_lines(2),
self.extent(&helper.meta),
)
.into());
}
Ok(EmitExpr {
mid: helper.add_meta(self.start, self.end),
expr: self.expr.up(helper)?,
port: self.port.up(helper)?,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct AssignRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) path: PathRaw<'script>,
pub(crate) expr: ExprRaw<'script>,
}
impl_expr!(AssignRaw);
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PredicateClauseRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) pattern: PatternRaw<'script>,
pub(crate) guard: Option<ImutExprRaw<'script>>,
pub(crate) exprs: Vec<Ex>,
}
impl<'script, Ex> Upable<'script> for PredicateClauseRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
type Target = PredicateClause<'script, <Ex as Upable<'script>>::Target>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let was_leaf = helper.possible_leaf;
helper.possible_leaf = false;
// We run the pattern first as this might reserve a local shadow
let pattern = self.pattern.up(helper)?;
let guard = self.guard.up(helper)?;
helper.possible_leaf = was_leaf;
let mut exprs = self.exprs.up(helper)?;
// If we are in an assign pattern we'd have created
// a shadow variable, this needs to be undoine at the end
if pattern.is_assign() {
helper.end_shadow_var();
}
if let Pattern::Assign(AssignPattern { idx, .. }) = &pattern {
if let Some(expr) = exprs.last_mut() {
expr.replace_last_shadow_use(*idx);
};
}
let span = Range::from((self.start, self.end));
let last_expr = exprs
.pop()
.ok_or_else(|| error_missing_effector(&span, &span, &helper.meta))?;
Ok(PredicateClause {
mid: helper.add_meta(self.start, self.end),
pattern,
guard,
exprs,
last_expr,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PatchRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) target: ImutExprRaw<'script>,
pub(crate) operations: PatchOperationsRaw<'script>,
}
impl<'script> Upable<'script> for PatchRaw<'script> {
type Target = Patch<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let operations = self.operations.up(helper)?;
Ok(Patch {
mid: helper.add_meta(self.start, self.end),
target: self.target.up(helper)?,
operations,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum PatchOperationRaw<'script> {
/// we're forced to make this pub because of lalrpop
Insert {
/// we're forced to make this pub because of lalrpop
ident: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Upsert {
/// we're forced to make this pub because of lalrpop
ident: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Update {
/// we're forced to make this pub because of lalrpop
ident: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Erase {
/// we're forced to make this pub because of lalrpop
ident: StringLitRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Copy {
/// we're forced to make this pub because of lalrpop
from: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
to: StringLitRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Move {
/// we're forced to make this pub because of lalrpop
from: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
to: StringLitRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Merge {
/// we're forced to make this pub because of lalrpop
ident: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
MergeRecord {
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
Default {
/// we're forced to make this pub because of lalrpop
ident: StringLitRaw<'script>,
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
DefaultRecord {
/// we're forced to make this pub because of lalrpop
expr: ImutExprRaw<'script>,
},
}
impl<'script> Upable<'script> for PatchOperationRaw<'script> {
type Target = PatchOperation<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
use PatchOperationRaw::{Copy, Erase, Insert, Merge, MergeRecord, Move, Update, Upsert};
Ok(match self {
Insert { ident, expr } => PatchOperation::Insert {
ident: ident.up(helper)?,
expr: expr.up(helper)?,
},
Upsert { ident, expr } => PatchOperation::Upsert {
ident: ident.up(helper)?,
expr: expr.up(helper)?,
},
Update { ident, expr } => PatchOperation::Update {
ident: ident.up(helper)?,
expr: expr.up(helper)?,
},
Erase { ident } => PatchOperation::Erase {
ident: ident.up(helper)?,
},
Copy { from, to } => PatchOperation::Copy {
from: from.up(helper)?,
to: to.up(helper)?,
},
Move { from, to } => PatchOperation::Move {
from: from.up(helper)?,
to: to.up(helper)?,
},
Merge { expr, ident, .. } => PatchOperation::Merge {
ident: ident.up(helper)?,
expr: expr.up(helper)?,
},
MergeRecord { expr } => PatchOperation::MergeRecord {
expr: expr.up(helper)?,
},
PatchOperationRaw::Default { ident, expr } => PatchOperation::Default {
ident: ident.up(helper)?,
expr: expr.up(helper)?,
},
PatchOperationRaw::DefaultRecord { expr } => PatchOperation::DefaultRecord {
expr: expr.up(helper)?,
},
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MergeRaw<'script> {
pub start: Location,
pub end: Location,
pub target: ImutExprRaw<'script>,
pub expr: ImutExprRaw<'script>,
}
impl<'script> Upable<'script> for MergeRaw<'script> {
type Target = Merge<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(Merge {
mid: helper.add_meta(self.start, self.end),
target: self.target.up(helper)?,
expr: self.expr.up(helper)?,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ComprehensionRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
pub start: Location,
pub end: Location,
pub target: ImutExprRaw<'script>,
pub cases: ComprehensionCasesRaw<'script, Ex>,
}
impl_expr_exraw!(ComprehensionRaw);
impl<'script, Ex> Upable<'script> for ComprehensionRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
type Target = Comprehension<'script, Ex::Target>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
// We compute the target before shadowing the key and value
let target = self.target.up(helper)?;
// We know that each case will have a key and a value as a shadowed
// variable so we reserve two ahead of time so we know what id's those
// will be.
let (key_id, val_id) = helper.reserve_2_shadow();
let cases = self.cases.up(helper)?;
Ok(Comprehension {
mid: helper.add_meta(self.start, self.end),
target,
cases,
key_id,
val_id,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ImutComprehensionRaw<'script> {
pub start: Location,
pub end: Location,
pub target: ImutExprRaw<'script>,
pub cases: ImutComprehensionCasesRaw<'script>,
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ComprehensionCaseRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) key_name: Cow<'script, str>,
pub(crate) value_name: Cow<'script, str>,
pub(crate) guard: Option<ImutExprRaw<'script>>,
pub(crate) exprs: Vec<Ex>,
}
impl<'script, Ex> Upable<'script> for ComprehensionCaseRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
type Target = ComprehensionCase<'script, Ex::Target>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
// regiter key and value as shadowed variables
let key_idx = helper.register_shadow_var(&self.key_name);
let val_idx = helper.register_shadow_var(&self.value_name);
let guard = self.guard.up(helper)?;
let mut exprs = self.exprs.up(helper)?;
if let Some(expr) = exprs.last_mut() {
expr.replace_last_shadow_use(key_idx);
expr.replace_last_shadow_use(val_idx);
};
// unregister them again
helper.end_shadow_var();
helper.end_shadow_var();
let span = Range::from((self.start, self.end));
let last_expr = exprs
.pop()
.ok_or_else(|| error_missing_effector(&span, &span, &helper.meta))?;
Ok(ComprehensionCase {
mid: helper.add_meta(self.start, self.end),
key_name: self.key_name,
value_name: self.value_name,
guard,
exprs,
last_expr,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ImutComprehensionCaseRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) key_name: Cow<'script, str>,
pub(crate) value_name: Cow<'script, str>,
pub(crate) guard: Option<ImutExprRaw<'script>>,
pub(crate) exprs: ImutExprsRaw<'script>,
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum PatternRaw<'script> {
/// we're forced to make this pub because of lalrpop
Record(RecordPatternRaw<'script>),
/// we're forced to make this pub because of lalrpop
Array(ArrayPatternRaw<'script>),
/// we're forced to make this pub because of lalrpop
Tuple(TuplePatternRaw<'script>),
/// we're forced to make this pub because of lalrpop
Expr(ImutExprRaw<'script>),
/// we're forced to make this pub because of lalrpop
Assign(AssignPatternRaw<'script>),
/// a test expression
Extract(TestExprRaw),
/// we're forced to make this pub because of lalrpop
DoNotCare,
/// we're forced to make this pub because of lalrpop
Default,
}
impl<'script> Upable<'script> for PatternRaw<'script> {
type Target = Pattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
use PatternRaw::{Array, Assign, Default, DoNotCare, Expr, Extract, Record, Tuple};
Ok(match self {
//Predicate(pp) => Pattern::Predicate(pp.up(helper)?),
Record(rp) => Pattern::Record(rp.up(helper)?),
Array(ap) => Pattern::Array(ap.up(helper)?),
Tuple(tp) => Pattern::Tuple(tp.up(helper)?),
Expr(expr) => Pattern::Expr(expr.up(helper)?),
Assign(ap) => Pattern::Assign(ap.up(helper)?),
Extract(e) => Pattern::Extract(Box::new(e.up(helper)?)),
DoNotCare => Pattern::DoNotCare,
Default => Pattern::Default,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum PredicatePatternRaw<'script> {
/// we're forced to make this pub because of lalrpop
TildeEq {
/// we're forced to make this pub because of lalrpop
assign: Cow<'script, str>,
/// we're forced to make this pub because of lalrpop
lhs: Cow<'script, str>,
/// we're forced to make this pub because of lalrpop
test: TestExprRaw,
},
/// we're forced to make this pub because of lalrpop
Bin {
/// we're forced to make this pub because of lalrpop
lhs: Cow<'script, str>,
/// we're forced to make this pub because of lalrpop
rhs: ImutExprRaw<'script>,
/// we're forced to make this pub because of lalrpop
kind: BinOpKind,
},
/// we're forced to make this pub because of lalrpop
RecordPatternEq {
/// we're forced to make this pub because of lalrpop
lhs: Cow<'script, str>,
/// we're forced to make this pub because of lalrpop
pattern: RecordPatternRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
ArrayPatternEq {
/// we're forced to make this pub because of lalrpop
lhs: Cow<'script, str>,
/// we're forced to make this pub because of lalrpop
pattern: ArrayPatternRaw<'script>,
},
/// we're forced to make this pub because of lalrpop
FieldPresent {
/// we're forced to make this pub because of lalrpop
lhs: Cow<'script, str>,
},
/// we're forced to make this pub because of lalrpop
FieldAbsent {
/// we're forced to make this pub because of lalrpop
lhs: Cow<'script, str>,
},
}
impl<'script> Upable<'script> for PredicatePatternRaw<'script> {
type Target = PredicatePattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
use PredicatePatternRaw::{
ArrayPatternEq, Bin, FieldAbsent, FieldPresent, RecordPatternEq, TildeEq,
};
Ok(match self {
TildeEq { assign, lhs, test } => PredicatePattern::TildeEq {
assign,
key: KnownKey::from(lhs.clone()),
lhs,
test: Box::new(test.up(helper)?),
},
Bin { lhs, rhs, kind } => PredicatePattern::Bin {
key: KnownKey::from(lhs.clone()),
lhs,
rhs: rhs.up(helper)?,
kind,
},
RecordPatternEq { lhs, pattern } => PredicatePattern::RecordPatternEq {
key: KnownKey::from(lhs.clone()),
lhs,
pattern: pattern.up(helper)?,
},
ArrayPatternEq { lhs, pattern } => PredicatePattern::ArrayPatternEq {
key: KnownKey::from(lhs.clone()),
lhs,
pattern: pattern.up(helper)?,
},
FieldPresent { lhs } => PredicatePattern::FieldPresent {
key: KnownKey::from(lhs.clone()),
lhs,
},
FieldAbsent { lhs } => PredicatePattern::FieldAbsent {
key: KnownKey::from(lhs.clone()),
lhs,
},
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct RecordPatternRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) fields: PatternFieldsRaw<'script>,
}
impl<'script> Upable<'script> for RecordPatternRaw<'script> {
type Target = RecordPattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let fields = self.fields.up(helper)?;
let present_fields: Vec<Cow<str>> = fields
.iter()
.filter_map(|f| {
if let PredicatePattern::FieldPresent { lhs, .. } = f {
Some(lhs.clone())
} else {
None
}
})
.collect();
let absent_fields: Vec<Cow<str>> = fields
.iter()
.filter_map(|f| {
if let PredicatePattern::FieldAbsent { lhs, .. } = f {
Some(lhs.clone())
} else {
None
}
})
.collect();
for present in &present_fields {
let duplicated = fields.iter().any(|f| {
if let PredicatePattern::FieldPresent { .. } = f {
false
} else {
f.lhs() == present
}
});
if duplicated {
let extent = (self.start, self.end).into();
helper.warn(
extent,
extent.expand_lines(2),
&format!("The field {} is checked with both present and another extractor, this is redundant as extractors imply presence. It may also overwrite the result of the extractor.", present),
);
}
}
for absent in &absent_fields {
let duplicated = fields.iter().any(|f| {
if let PredicatePattern::FieldAbsent { .. } = f {
false
} else {
f.lhs() == absent
}
});
if duplicated {
let extent = (self.start, self.end).into();
helper.warn(
extent,
extent.expand_lines(2),
&format!("The field {} is checked with both absence and another extractor, this test can never be true.", absent),
);
}
}
Ok(RecordPattern {
mid: helper.add_meta(self.start, self.end),
fields,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum ArrayPredicatePatternRaw<'script> {
/// we're forced to make this pub because of lalrpop
Expr(ImutExprRaw<'script>),
/// we're forced to make this pub because of lalrpop
Tilde(TestExprRaw),
/// we're forced to make this pub because of lalrpop
Record(RecordPatternRaw<'script>),
/// Ignore
Ignore,
}
impl<'script> Upable<'script> for ArrayPredicatePatternRaw<'script> {
type Target = ArrayPredicatePattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
use ArrayPredicatePatternRaw::{Expr, Ignore, Record, Tilde};
Ok(match self {
Expr(expr) => ArrayPredicatePattern::Expr(expr.up(helper)?),
Tilde(te) => ArrayPredicatePattern::Tilde(Box::new(te.up(helper)?)),
Record(rp) => ArrayPredicatePattern::Record(rp.up(helper)?),
Ignore => ArrayPredicatePattern::Ignore,
//Array(ap) => ArrayPredicatePattern::Array(ap),
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ArrayPatternRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) exprs: ArrayPredicatePatternsRaw<'script>,
}
impl<'script> Upable<'script> for ArrayPatternRaw<'script> {
type Target = ArrayPattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let exprs = self.exprs.up(helper)?;
Ok(ArrayPattern {
mid: helper.add_meta(self.start, self.end),
exprs,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct TuplePatternRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) exprs: ArrayPredicatePatternsRaw<'script>,
pub(crate) open: bool,
}
impl<'script> Upable<'script> for TuplePatternRaw<'script> {
type Target = TuplePattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let exprs = self.exprs.up(helper)?;
Ok(TuplePattern {
mid: helper.add_meta(self.start, self.end),
exprs,
open: self.open,
})
}
}
pub(crate) const FN_RES_NAME: &str = "__fn_assign_this_is_ugly";
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct AssignPatternRaw<'script> {
pub(crate) id: Cow<'script, str>,
pub(crate) pattern: Box<PatternRaw<'script>>,
}
impl<'script> Upable<'script> for AssignPatternRaw<'script> {
type Target = AssignPattern<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(AssignPattern {
idx: helper.register_shadow_var(&self.id),
id: self.id,
pattern: Box::new(self.pattern.up(helper)?),
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum PathRaw<'script> {
/// we're forced to make this pub because of lalrpop
Local(LocalPathRaw<'script>),
/// we're forced to make this pub because of lalrpop
Event(EventPathRaw<'script>),
/// we're forced to make this pub because of lalrpop
State(StatePathRaw<'script>),
/// we're forced to make this pub because of lalrpop
Meta(MetadataPathRaw<'script>),
/// we're forced to make this pub because of lalrpop
Const(ConstPathRaw<'script>),
/// Special reserved path
Reserved(ReservedPathRaw<'script>),
/// Special reserved path an expression path
Expr(ExprPathRaw<'script>),
}
impl<'script> Upable<'script> for PathRaw<'script> {
type Target = Path<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
use PathRaw::{Const, Event, Expr, Local, Meta, Reserved, State};
Ok(match self {
Local(p) => {
let p = p.up(helper)?;
if p.is_const {
Path::Const(p)
} else {
Path::Local(p)
}
}
Const(p) => Path::Const(p.up(helper)?),
Event(p) => Path::Event(p.up(helper)?),
State(p) => Path::State(p.up(helper)?),
Meta(p) => Path::Meta(p.up(helper)?),
Expr(p) => Path::Expr(p.up(helper)?),
Reserved(p) => Path::Reserved(p.up(helper)?),
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
/// we're forced to make this pub because of lalrpop
pub struct SegmentRangeRaw<'script> {
pub(crate) start_lower: Location,
pub(crate) range_start: ImutExprRaw<'script>,
pub(crate) end_lower: Location,
pub(crate) start_upper: Location,
pub(crate) range_end: ImutExprRaw<'script>,
pub(crate) end_upper: Location,
}
impl<'script> Upable<'script> for SegmentRangeRaw<'script> {
type Target = Segment<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let SegmentRangeRaw {
start_lower,
range_start,
end_lower,
start_upper,
range_end,
end_upper,
} = self;
let lower_mid = helper.add_meta(start_lower, end_lower);
let upper_mid = helper.add_meta(start_upper, end_upper);
let mid = helper.add_meta(start_lower, end_upper);
Ok(Segment::Range {
lower_mid,
upper_mid,
range_start: Box::new(range_start.up(helper)?),
range_end: Box::new(range_end.up(helper)?),
mid,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SegmentElementRaw<'script> {
pub(crate) expr: ImutExprRaw<'script>,
pub(crate) start: Location,
pub(crate) end: Location,
}
impl<'script> Upable<'script> for SegmentElementRaw<'script> {
type Target = Segment<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let SegmentElementRaw { expr, start, end } = self;
let expr = expr.up(helper)?;
let r = expr.extent(&helper.meta);
match expr {
ImutExprInt::Literal(l) => match ImutExprInt::Literal(l).try_into_value(helper)? {
Value::String(id) => {
let mid = helper.add_meta_w_name(start, end, &id);
Ok(Segment::Id {
key: KnownKey::from(id.clone()),
mid,
})
}
other => {
if let Some(idx) = other.as_usize() {
let mid = helper.add_meta(start, end);
Ok(Segment::Idx { idx, mid })
} else {
Err(ErrorKind::TypeConflict(
r.expand_lines(2),
r,
other.value_type(),
vec![ValueType::I64, ValueType::String],
)
.into())
}
}
},
expr => Ok(Segment::Element {
mid: helper.add_meta(start, end),
expr,
}),
}
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum SegmentRaw<'script> {
/// we're forced to make this pub because of lalrpop
Element(Box<SegmentElementRaw<'script>>),
/// we're forced to make this pub because of lalrpop
Range(Box<SegmentRangeRaw<'script>>),
}
impl<'script> Upable<'script> for SegmentRaw<'script> {
type Target = Segment<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
match self {
SegmentRaw::Element(e) => e.up(helper),
SegmentRaw::Range(r) => r.up(helper),
}
}
}
impl<'script> SegmentRaw<'script> {
pub fn from_id(id: IdentRaw<'script>) -> Self {
SegmentRaw::Element(Box::new(SegmentElementRaw {
start: id.start,
end: id.end,
expr: ImutExprRaw::Literal(LiteralRaw {
start: id.start,
end: id.end,
value: Value::from(id.id),
}),
}))
}
pub fn from_str(id: &'script str, start: Location, end: Location) -> Self {
SegmentRaw::Element(Box::new(SegmentElementRaw {
start,
end,
expr: ImutExprRaw::Literal(LiteralRaw {
start,
end,
value: Value::from(id),
}),
}))
}
pub fn from_usize(id: usize, start: Location, end: Location) -> Self {
SegmentRaw::Element(Box::new(SegmentElementRaw {
start,
end,
expr: ImutExprRaw::Literal(LiteralRaw {
start,
end,
value: Value::from(id),
}),
}))
}
}
impl<'script> From<ImutExprRaw<'script>> for ExprRaw<'script> {
fn from(imut: ImutExprRaw<'script>) -> ExprRaw<'script> {
ExprRaw::Imut(imut)
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ConstPathRaw<'script> {
pub(crate) module: Vec<IdentRaw<'script>>,
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) segments: SegmentsRaw<'script>,
}
impl_expr!(ConstPathRaw);
impl<'script> Upable<'script> for ConstPathRaw<'script> {
type Target = LocalPath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let segments = self.segments.up(helper)?;
let mut segments = segments.into_iter();
if let Some(Segment::Id { mid, .. }) = segments.next() {
let segments = segments.collect();
let id = helper.meta.name_dflt(mid).to_string();
let mid = helper.add_meta_w_name(self.start, self.end, &id);
let mut module_direct: Vec<String> =
self.module.iter().map(|m| m.to_string()).collect();
let mut module = helper.module.clone();
module.append(&mut module_direct);
module.push(id);
if let Some(idx) = helper.is_const(&module) {
Ok(LocalPath {
is_const: true,
idx: *idx,
mid,
segments,
})
} else {
error_generic(
&(self.start, self.end),
&(self.start, self.end),
&format!(
"The constant {} (absolute path) is not defined.",
module.join("::")
),
&helper.meta,
)
}
} else {
// We should never encounter this
error_oops(
&(self.start, self.end),
0xdead_0007,
"Empty local path",
&helper.meta,
)
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ExprPathRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) expr: Box<ImutExprRaw<'script>>,
pub(crate) segments: SegmentsRaw<'script>,
}
impl<'script> Upable<'script> for ExprPathRaw<'script> {
type Target = ExprPath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let var = helper.reserve_shadow();
let segments = self.segments.up(helper)?;
let expr = Box::new(self.expr.up(helper)?);
helper.end_shadow_var();
Ok(ExprPath {
var,
segments,
expr,
mid: helper.add_meta(self.start, self.end),
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum ReservedPathRaw<'script> {
Args {
start: Location,
end: Location,
segments: SegmentsRaw<'script>,
},
Window {
start: Location,
end: Location,
segments: SegmentsRaw<'script>,
},
Group {
start: Location,
end: Location,
segments: SegmentsRaw<'script>,
},
}
impl<'script> Upable<'script> for ReservedPathRaw<'script> {
type Target = ReservedPath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let r = match self {
ReservedPathRaw::Args {
start,
end,
segments,
} => ReservedPath::Args {
mid: helper.add_meta_w_name(start, end, &"args"),
segments: segments.up(helper)?,
},
ReservedPathRaw::Window {
start,
end,
segments,
} => ReservedPath::Window {
mid: helper.add_meta_w_name(start, end, &"window"),
segments: segments.up(helper)?,
},
ReservedPathRaw::Group {
start,
end,
segments,
} => ReservedPath::Group {
mid: helper.add_meta_w_name(start, end, &"group"),
segments: segments.up(helper)?,
},
};
Ok(r)
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct LocalPathRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) segments: SegmentsRaw<'script>,
}
impl_expr!(LocalPathRaw);
impl<'script> Upable<'script> for LocalPathRaw<'script> {
type Target = LocalPath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let segments = self.segments.up(helper)?;
let mut segments = segments.into_iter();
if let Some(Segment::Id { mid, .. }) = segments.next() {
let segments = segments.collect();
let id = helper.meta.name_dflt(mid).to_string();
let mid = helper.add_meta_w_name(self.start, self.end, &id);
let mut rel_path = helper.module.clone();
rel_path.push(id.to_string());
let (idx, is_const) = helper
.is_const(&rel_path)
.copied()
.map_or_else(|| (helper.var_id(&id), false), |idx| (idx, true));
Ok(LocalPath {
idx,
is_const,
mid,
segments,
})
} else {
// We should never encounter this
error_oops(
&(self.start, self.end),
0xdead_0008,
"Empty local path",
&helper.meta,
)
}
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MetadataPathRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) segments: SegmentsRaw<'script>,
}
impl<'script> Upable<'script> for MetadataPathRaw<'script> {
type Target = MetadataPath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let segments = self.segments.up(helper)?;
Ok(MetadataPath {
mid: helper.add_meta(self.start, self.end),
segments,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct EventPathRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) segments: SegmentsRaw<'script>,
}
impl<'script> Upable<'script> for EventPathRaw<'script> {
type Target = EventPath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let segments = self.segments.up(helper)?;
Ok(EventPath {
mid: helper.add_meta(self.start, self.end),
segments,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StatePathRaw<'script> {
pub start: Location,
pub end: Location,
pub segments: SegmentsRaw<'script>,
}
impl<'script> Upable<'script> for StatePathRaw<'script> {
type Target = StatePath<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let segments = self.segments.up(helper)?;
Ok(StatePath {
mid: helper.add_meta(self.start, self.end),
segments,
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct BinExprRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) kind: BinOpKind,
pub(crate) lhs: ImutExprRaw<'script>,
pub(crate) rhs: ImutExprRaw<'script>,
// query_stream_not_defined(stmt: &Box<S>, inner: &I, name: String)
}
impl<'script> Upable<'script> for BinExprRaw<'script> {
type Target = BinExpr<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(BinExpr {
mid: helper.add_meta(self.start, self.end),
kind: self.kind,
lhs: self.lhs.up(helper)?,
rhs: self.rhs.up(helper)?,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct UnaryExprRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) kind: UnaryOpKind,
pub(crate) expr: ImutExprRaw<'script>,
}
impl<'script> Upable<'script> for UnaryExprRaw<'script> {
type Target = UnaryExpr<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
Ok(UnaryExpr {
mid: helper.add_meta(self.start, self.end),
kind: self.kind,
expr: self.expr.up(helper)?,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MatchRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) target: ImutExprRaw<'script>,
pub(crate) patterns: PredicatesRaw<'script, Ex>,
}
impl_expr_exraw!(MatchRaw);
// Sort clauses, move up cheaper clauses as long as they're exclusive
fn sort_clauses<Ex: Expression>(patterns: &mut [PredicateClause<Ex>]) {
for i in (0..patterns.len()).rev() {
for j in (1..=i).rev() {
#[allow(
// No clippy, we really mean j.exclusive(k) || k.exclusive(j)...
clippy::suspicious_operation_groupings,
// also what is wrong with you clippy ...
clippy::blocks_in_if_conditions
)]
if patterns
.get(j)
.and_then(|jv| Some((jv, patterns.get(j - 1)?)))
.map(|(j, k)| {
j.cost() <= k.cost() && (j.is_exclusive_to(k) || k.is_exclusive_to(j))
})
.unwrap_or_default()
{
patterns.swap(j, j - 1);
}
}
}
}
const NO_DFLT: &str = "This match expression has no default clause, if the other clauses do not cover all possibilities this will lead to events being discarded with runtime errors.";
const MULT_DFLT: &str = "A match statement with more then one default clause will never reach any but the first default clause.";
impl<'script, Ex> Upable<'script> for MatchRaw<'script, Ex>
where
<Ex as Upable<'script>>::Target: Expression + 'script,
Ex: ExpressionRaw<'script> + 'script,
{
type Target = Match<'script, Ex::Target>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let mut patterns: Vec<PredicateClause<_>> = self
.patterns
.into_iter()
.map(|v| v.up(helper))
.collect::<Result<_>>()?;
let defaults = patterns
.iter()
.filter(|p| p.pattern.is_default() && p.guard.is_none())
.count();
match defaults {
0 => helper.warn_with_scope(Range(self.start, self.end), &NO_DFLT),
x if x > 1 => helper.warn_with_scope(Range(self.start, self.end), &MULT_DFLT),
_ => (),
};
// If the last statement is a global default we can simply remove it
let default = if let Some(PredicateClause {
pattern: Pattern::Default,
guard: None,
exprs,
last_expr,
..
}) = patterns.last_mut()
{
let mut es = Vec::new();
let mut last = Ex::Target::null_lit();
std::mem::swap(exprs, &mut es);
std::mem::swap(last_expr, &mut last);
if es.is_empty() {
if last.is_null_lit() {
DefaultCase::Null
} else {
DefaultCase::One(last)
}
} else {
DefaultCase::Many {
exprs: es,
last_expr: Box::new(last),
}
}
} else {
DefaultCase::None
};
if default != DefaultCase::None {
patterns.pop();
}
// This shortcuts for if / else style matches
if patterns.len() == 1 {
let patterns = patterns.into_iter().map(ClauseGroup::simple).collect();
return Ok(Match {
mid: helper.add_meta(self.start, self.end),
target: self.target.up(helper)?,
patterns,
default,
});
}
sort_clauses(&mut patterns);
let mut groups = Vec::new();
let mut group: Vec<PredicateClause<_>> = Vec::new();
for p in patterns {
if group
.iter()
.all(|g| p.is_exclusive_to(g) || g.is_exclusive_to(&p))
{
group.push(p);
} else {
group.sort_by_key(Costly::cost);
let mut g = ClauseGroup::Simple {
patterns: group,
precondition: None,
};
g.optimize(0);
groups.push(g);
group = vec![p];
}
}
group.sort_by_key(Costly::cost);
let mut g = ClauseGroup::Simple {
patterns: group,
precondition: None,
};
g.optimize(0);
groups.push(g);
let mut patterns: Vec<ClauseGroup<_>> = Vec::new();
for g in groups {
#[allow(clippy::option_if_let_else)]
if let Some(last) = patterns.last_mut() {
if last.combinable(&g) {
last.combine(g);
} else {
patterns.push(g);
}
} else {
patterns.push(g);
}
}
Ok(Match {
mid: helper.add_meta(self.start, self.end),
target: self.target.up(helper)?,
patterns,
default,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct InvokeRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) module: Vec<String>,
pub(crate) fun: String,
pub(crate) args: ImutExprsRaw<'script>,
}
impl_expr!(InvokeRaw);
impl<'script> Upable<'script> for InvokeRaw<'script> {
type Target = Invoke<'script>;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
if self.module.first() == Some(&String::from("core")) && self.module.len() == 2 {
// we know a second module exists
let module = self.module.get(1).cloned().unwrap_or_default();
let invocable = helper
.reg
.find(&module, &self.fun)
.map_err(|e| e.into_err(&self, &self, Some(helper.reg), &helper.meta))?;
let args = self.args.up(helper)?.into_iter().map(ImutExpr).collect();
let mf = format!("{}::{}", self.module.join("::"), self.fun);
Ok(Invoke {
mid: helper.add_meta_w_name(self.start, self.end, &mf),
module: self.module,
fun: self.fun,
invocable: Invocable::Intrinsic(invocable.clone()),
args,
})
} else {
// Absolute locability from without a set of nested modules
let mut abs_module = helper.module.clone();
abs_module.extend_from_slice(&self.module);
abs_module.push(self.fun.clone());
// of the form: [mod, mod1, name] - where the list of idents is effectively a fully qualified resource name
if let Some(f) = helper.functions.get(&abs_module) {
if let Some(f) = helper.func_vec.get(*f) {
let invocable = Invocable::Tremor(f.clone());
let args = self.args.up(helper)?.into_iter().map(ImutExpr).collect();
let mf = abs_module.join("::");
Ok(Invoke {
mid: helper.add_meta_w_name(self.start, self.end, &mf),
module: self.module,
fun: self.fun,
invocable,
args,
})
} else {
let inner: Range = (self.start, self.end).into();
let outer: Range = inner.expand_lines(3);
Err(
ErrorKind::MissingFunction(outer, inner, self.module, self.fun, None)
.into(),
)
}
} else {
let inner: Range = (self.start, self.end).into();
let outer: Range = inner.expand_lines(3);
Err(ErrorKind::MissingFunction(outer, inner, self.module, self.fun, None).into())
}
}
}
}
impl<'script> InvokeRaw<'script> {
fn is_aggregate<'registry>(&self, helper: &mut Helper<'script, 'registry>) -> bool {
if self.module.first() == Some(&String::from("aggr")) && self.module.len() == 2 {
let module = self.module.get(1).cloned().unwrap_or_default();
helper.aggr_reg.find(&module, &self.fun).is_ok()
} else {
false
}
}
fn into_aggregate(self) -> InvokeAggrRaw<'script> {
let module = self.module.get(1).cloned().unwrap_or_default();
InvokeAggrRaw {
start: self.start,
end: self.end,
module,
fun: self.fun,
args: self.args,
}
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct InvokeAggrRaw<'script> {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) module: String,
pub(crate) fun: String,
pub(crate) args: ImutExprsRaw<'script>,
}
impl_expr!(InvokeAggrRaw);
impl<'script> Upable<'script> for InvokeAggrRaw<'script> {
type Target = InvokeAggr;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
if helper.is_in_aggr {
return Err(ErrorKind::AggrInAggr(
self.extent(&helper.meta),
self.extent(&helper.meta).expand_lines(2),
)
.into());
};
helper.is_in_aggr = true;
let invocable = helper
.aggr_reg
.find(&self.module, &self.fun)
.map_err(|e| e.into_err(&self, &self, Some(helper.reg), &helper.meta))?
.clone();
if !invocable.valid_arity(self.args.len()) {
return Err(ErrorKind::BadArity(
self.extent(&helper.meta),
self.extent(&helper.meta).expand_lines(2),
self.module.clone(),
self.fun.clone(),
invocable.arity(),
self.args.len(),
)
.into());
}
if let Some(warning) = invocable.warning() {
helper.warn_with_scope(self.extent(&helper.meta), &warning);
}
let aggr_id = helper.aggregates.len();
let args = self.args.up(helper)?.into_iter().map(ImutExpr).collect();
let mf = format!("{}::{}", self.module, self.fun);
let invoke_meta_id = helper.add_meta_w_name(self.start, self.end, &mf);
helper.aggregates.push(InvokeAggrFn {
mid: invoke_meta_id,
invocable,
args,
module: self.module.clone(),
fun: self.fun.clone(),
});
helper.is_in_aggr = false;
let aggr_meta_id = helper.add_meta_w_name(self.start, self.end, &mf);
Ok(InvokeAggr {
mid: aggr_meta_id,
module: self.module,
fun: self.fun,
aggr_id,
})
}
}
/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct TestExprRaw {
pub(crate) start: Location,
pub(crate) end: Location,
pub(crate) id: String,
pub(crate) test: String,
}
impl<'script> Upable<'script> for TestExprRaw {
type Target = TestExpr;
fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> {
let mid = helper.add_meta(self.start, self.end);
match Extractor::new(&self.id, &self.test) {
Ok(ex) => Ok(TestExpr {
id: self.id,
test: self.test,
extractor: ex,
mid,
}),
Err(e) => Err(ErrorKind::InvalidExtractor(
self.extent(&helper.meta).expand_lines(2),
self.extent(&helper.meta),
self.id,
self.test,
e.msg,
)
.into()),
}
}
}
pub type ExprsRaw<'script> = Vec<ExprRaw<'script>>;
pub type ImutExprsRaw<'script> = Vec<ImutExprRaw<'script>>;
pub type FieldsRaw<'script> = Vec<FieldRaw<'script>>;
pub type SegmentsRaw<'script> = Vec<SegmentRaw<'script>>;
pub type PatternFieldsRaw<'script> = Vec<PredicatePatternRaw<'script>>;
pub type PredicatesRaw<'script, Ex> = Vec<PredicateClauseRaw<'script, Ex>>;
pub type PatchOperationsRaw<'script> = Vec<PatchOperationRaw<'script>>;
pub type ComprehensionCasesRaw<'script, Ex> = Vec<ComprehensionCaseRaw<'script, Ex>>;
pub type ImutComprehensionCasesRaw<'script> = Vec<ImutComprehensionCaseRaw<'script>>;
pub type ArrayPredicatePatternsRaw<'script> = Vec<ArrayPredicatePatternRaw<'script>>;
pub type WithExprsRaw<'script> = Vec<(IdentRaw<'script>, ImutExprRaw<'script>)>;
#[cfg(test)]
mod test {
use super::*;
#[test]
fn default() {
assert_eq!(Endian::default(), Endian::Big);
assert_eq!(BytesDataType::default(), BytesDataType::UnsignedInteger);
}
}
|
use std::fmt;
use firefly_diagnostics::SourceIndex;
use firefly_intern::Symbol;
use firefly_number::{Float, Integer};
use firefly_syntax_erl::LexicalError;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LexicalToken(pub SourceIndex, pub Token, pub SourceIndex);
impl LexicalToken {
#[inline]
pub fn token(&self) -> Token {
self.1.clone()
}
#[inline]
pub fn span(&self) -> SourceSpan {
SourceSpan::new(self.0, self.2)
}
}
impl fmt::Display for LexicalToken {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.token())
}
}
impl Into<(SourceIndex, Token, SourceIndex)> for LexicalToken {
fn into(self) -> (SourceIndex, Token, SourceIndex) {
(self.0, self.1, self.2)
}
}
impl From<(SourceIndex, Token, SourceIndex)> for LexicalToken {
fn from(triple: (SourceIndex, Token, SourceIndex)) -> LexicalToken {
LexicalToken(triple.0, triple.1, triple.2)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Token {
EOF,
Error(LexicalError),
// Puncutation
Comma,
Dot,
Pipe,
SquareOpen,
SquareClose,
CurlyOpen,
CurlyClose,
// Literals
AtomLiteral(Symbol),
StringLiteral(Symbol),
IntegerLiteral(Integer),
FloatLiteral(Float),
// Keywords
Atom,
Attribute,
Bin,
BinElement,
BitComprehension, // bc
BitGenerator, // bc_generate
Call,
Callback,
Case,
Catch,
Char,
Clauses,
Clause,
Cons,
Error,
Export,
ExportType,
File,
Function,
Fun,
If,
Import,
Integer,
ListGenerator, // generate
ListComprehension, // lc
Match,
Map,
MapFieldAssoc,
MapFieldExact,
Module,
Nil,
Op,
Opaque,
OptionalCallbacks,
Receive,
Record,
RecordField,
Spec,
String,
Try,
Tuple,
Type,
Var,
Warning,
}
impl Token {
pub fn from_bare_atom(atom: &str) -> Self {
match atom {
"atom" => Token::Atom,
"attribute" => Token::Attribute,
"bin" => Token::Bin,
"bin_element" => Token::BinElement,
"bc" => Token::BitComprehension,
"bc_generate" => Token::BitGenerator,
"call" => Token::Call,
"callback" => Token::Callback,
"case" => Token::Case,
"catch" => Token::Catch,
"char" => Token::Char,
"clauses" => Token::Clauses,
"clause" => Token::Clause,
"cons" => Token::Cons,
"error" => Token::Error,
"export" => Token::Export,
"export_type" => Token::ExportType,
"file" => Token::File,
"function" => Token::Function,
"fun" => Token::Fun,
"if" => Token::If,
"import" => Token::Import,
"integer" => Token::Integer,
"generate" => Token::ListGenerator,
"lc" => Token::ListComprehension,
"match" => Token::Match,
"map" => Token::Map,
"map_field_assoc" => Token::MapFieldAssoc,
"map_field_exact" => Token::MapFieldExact,
"module" => Token::Module,
"nil" => Token::Nil,
"op" => Token::Op,
"opaque" => Token::Opaque,
"optional_callbacks" => Token::OptionalCallbacks,
"receive" => Token::Receive,
"record" => Token::Record,
"record_field" => Token::RecordField,
"spec" => Token::Spec,
"string" => Token::String,
"try" => Token::Try,
"tuple" => Token::Tuple,
"type" => Token::Type,
"var" => Token::Var,
"warning" => Token::Warning,
_ => Token::AtomLiteral(Symbol::intern(atom)),
}
}
}
|
use glob::glob;
use std::process::Command;
fn main() -> anyhow::Result<()> {
let dir_out = std::env::var("OUT_DIR")?;
let dir_ocaml = "../../ocaml";
let dir_dune = "../../_build/default";
// Install OCaml dependencies.
let mut cmd = Command::new("opam");
cmd.args(&["pin", "add", "-y", "rust-ocaml-dyn", "."]);
cmd.current_dir(dir_ocaml);
cmd.status()?;
// Build the OCaml extension host and extensions with Dune.
let mut cmd = Command::new("opam");
cmd.args(&["exec", "--", "dune", "build"]);
cmd.current_dir(dir_ocaml);
cmd.status()?;
// Remove the old archive file.
let mut cmd = Command::new("rm");
cmd.args(&["-f", &format!("{}/libhost.a", dir_out)]);
cmd.status()?;
// Create the archive file from the object file.
let mut cmd = Command::new("ar");
cmd.args(&[
"qs",
&format!("{}/libhost.a", dir_out),
&format!("{}/ocaml/host/host.bc.o", dir_dune),
]);
cmd.status()?;
// Re-run if `dune-project` changes.
println!("cargo:rerun-if-changed={}/dune-project", dir_ocaml);
// Re-run if `**/dune` files change.
for path in glob(&format!("{}/**/dune", dir_ocaml))? {
if let Some(path) = path?.to_str() {
println!("cargo:rerun-if-changed={}", path);
}
}
// Re-run if `**/*.mli?` files change.
for path in glob(&format!("{}/**/*.ml", dir_ocaml))? {
if let Some(path) = path?.to_str() {
println!("cargo:rerun-if-changed={}", path);
}
}
// Re-run if `**/*.mli?` files change.
for path in glob(&format!("{}/**/*.mli", dir_ocaml))? {
if let Some(path) = path?.to_str() {
println!("cargo:rerun-if-changed={}", path);
}
}
// Configure linking for the extension host object file.
println!("cargo:rustc-link-search={}", dir_out);
println!("cargo:rustc-link-lib=static=host");
Ok(())
}
|
/*
Project Euler Problem 9:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
*/
fn main() {
for a in 1..1000 {
for b in 1..1000 {
let c = ((a*a + b*b) as f32).sqrt();
if (a as f32)+(b as f32)+c == 1000.0 {
println!("{:?}", a*b*(c as i32));
return;
}
}
}
} |
#[macro_use]
pub mod utils;
mod core;
pub use self::core::{
default_filter, AllRulesValidator, Filter, SourceCode, ValidationError, Validator,
};
mod iter;
pub use self::iter::NodeIterator;
mod grammar;
mod hint;
mod rule;
pub use self::rule::{Rule, RuleCode, RULES};
pub mod filters;
pub mod validators;
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
breakpoints_capability::*,
component_manager_lib::{
model::{
self, hooks::*, testing::breakpoints::*, testing::test_helpers, AbsoluteMoniker, Hub,
Model,
},
startup,
},
failure::{self, Error},
fidl::endpoints::ClientEnd,
fidl_fidl_examples_routing_echo as fecho,
fidl_fuchsia_io::{
DirectoryMarker, DirectoryProxy, MODE_TYPE_SERVICE, OPEN_RIGHT_READABLE,
OPEN_RIGHT_WRITABLE,
},
fidl_fuchsia_test_hub as fhub, fuchsia_zircon as zx,
hub_test_hook::*,
std::{path::PathBuf, sync::Arc, vec::Vec},
};
struct TestRunner {
pub model: Model,
pub hub: Hub,
hub_test_hook: Arc<HubTestHook>,
_breakpoint_hook: BreakpointHook,
_breakpoint_capability_hook: BreakpointCapabilityHook,
breakpoint_receiver: BreakpointInvocationReceiver,
hub_proxy: DirectoryProxy,
}
async fn create_model(root_component_url: &str) -> Result<Model, Error> {
let root_component_url = root_component_url.to_string();
// TODO(xbhatnag): Explain this in more detail. Setting use_builtin_process_launcher to false is non-obvious.
let args = startup::Arguments {
use_builtin_process_launcher: false,
use_builtin_vmex: false,
root_component_url,
};
let model = startup::model_setup(&args, vec![]).await?;
Ok(model)
}
async fn install_hub(model: &Model) -> Result<(Hub, DirectoryProxy), Error> {
let (client_chan, server_chan) = zx::Channel::create()?;
let root_component_url = model.root_realm.component_url.clone();
let hub = Hub::new(root_component_url)?;
// TODO(xbhatnag): Investigate why test() fails when OPEN_RIGHT_WRITABLE is removed
hub.open_root(OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE, server_chan.into()).await?;
model.root_realm.hooks.install(hub.hooks()).await;
let hub_proxy = ClientEnd::<DirectoryMarker>::new(client_chan).into_proxy()?;
Ok((hub, hub_proxy))
}
async fn install_hub_test_hook(model: &Model) -> Arc<HubTestHook> {
let hub_test_hook = Arc::new(HubTestHook::new());
model
.root_realm
.hooks
.install(vec![HookRegistration {
event_type: EventType::RouteFrameworkCapability,
callback: hub_test_hook.clone(),
}])
.await;
hub_test_hook
}
async fn register_breakpoints(
model: &Model,
event_types: Vec<EventType>,
) -> (BreakpointHook, BreakpointCapabilityHook, BreakpointInvocationReceiver) {
let breakpoint_registry = Arc::new(BreakpointRegistry::new());
let breakpoint_receiver = breakpoint_registry.register(event_types).await;
let breakpoint_hook = BreakpointHook::new(breakpoint_registry.clone());
let breakpoint_capability_hook = BreakpointCapabilityHook::new(breakpoint_registry.clone());
model.root_realm.hooks.install(breakpoint_hook.hooks()).await;
model.root_realm.hooks.install(breakpoint_capability_hook.hooks()).await;
(breakpoint_hook, breakpoint_capability_hook, breakpoint_receiver)
}
impl TestRunner {
async fn new(root_component_url: &str) -> Result<Self, Error> {
TestRunner::new_with_breakpoints(root_component_url, vec![]).await
}
async fn new_with_breakpoints(
root_component_url: &str,
event_types: Vec<EventType>,
) -> Result<Self, Error> {
let model = create_model(root_component_url).await?;
let (hub, hub_proxy) = install_hub(&model).await?;
let hub_test_hook = install_hub_test_hook(&model).await;
let (breakpoint_hook, breakpoint_capability_hook, breakpoint_receiver) =
register_breakpoints(&model, event_types).await;
let res = model.look_up_and_bind_instance(model::AbsoluteMoniker::root()).await;
let expected_res: Result<(), model::ModelError> = Ok(());
assert_eq!(format!("{:?}", res), format!("{:?}", expected_res));
Ok(Self {
model,
hub,
hub_proxy,
hub_test_hook,
_breakpoint_hook: breakpoint_hook,
_breakpoint_capability_hook: breakpoint_capability_hook,
breakpoint_receiver,
})
}
async fn expect_invocation(
&self,
expected_event: EventType,
components: Vec<&str>,
) -> BreakpointInvocation {
let breakpoint = self.breakpoint_receiver.receive().await;
let expected_moniker = AbsoluteMoniker::from(components);
assert_eq!(breakpoint.event.type_(), expected_event);
let moniker = match &breakpoint.event {
Event::PreDestroyInstance { realm } => realm.abs_moniker.clone(),
Event::StopInstance { realm } => realm.abs_moniker.clone(),
Event::PostDestroyInstance { realm } => realm.abs_moniker.clone(),
_ => AbsoluteMoniker::root(),
};
assert_eq!(moniker, expected_moniker);
breakpoint
}
async fn connect_to_echo_service(&self, echo_service_path: String) -> Result<(), Error> {
let node_proxy = io_util::open_node(
&self.hub_proxy,
&PathBuf::from(echo_service_path),
io_util::OPEN_RIGHT_READABLE,
MODE_TYPE_SERVICE,
)?;
let echo_proxy = fecho::EchoProxy::new(node_proxy.into_channel().unwrap());
let res = echo_proxy.echo_string(Some("hippos")).await?;
assert_eq!(res, Some("hippos".to_string()));
Ok(())
}
async fn verify_global_directory_listing(
&self,
relative_path: &str,
expected_listing: Vec<&str>,
) {
let dir_proxy = io_util::open_directory(
&self.hub_proxy,
&PathBuf::from(relative_path),
OPEN_RIGHT_READABLE,
)
.expect("Could not open directory from global view");
assert_eq!(expected_listing, test_helpers::list_directory(&dir_proxy).await);
}
async fn verify_local_directory_listing(
&self,
path: &str,
expected_listing: Vec<&str>,
) -> fhub::HubReportListDirectoryResponder {
let event = self.hub_test_hook.observe(path).await;
let expected_listing: Vec<String> =
expected_listing.iter().map(|s| s.to_string()).collect();
match event {
HubReportEvent::DirectoryListing { listing, responder } => {
assert_eq!(expected_listing, listing);
responder
}
_ => {
panic!("Unexpected event type!");
}
}
}
async fn verify_directory_listing(&self, hub_relative_path: &str, expected_listing: Vec<&str>) {
let local_path = format!("/hub/{}", hub_relative_path);
let responder = self
.verify_local_directory_listing(local_path.as_str(), expected_listing.clone())
.await;
self.verify_global_directory_listing(hub_relative_path, expected_listing).await;
responder.send().expect("Unable to respond");
}
async fn verify_local_file_content(&self, path: &str, expected_content: &str) {
let event = self.hub_test_hook.observe(path).await;
match event {
HubReportEvent::FileContent { content, responder } => {
let expected_content = expected_content.to_string();
assert_eq!(expected_content, content);
responder.send().expect("failed to respond");
}
_ => {
panic!("Unexpected event type!");
}
};
}
async fn verify_global_file_content(&self, relative_path: &str, expected_content: &str) {
assert_eq!(expected_content, test_helpers::read_file(&self.hub_proxy, relative_path).await);
}
async fn wait_for_component_stop(&self) {
self.hub_test_hook.wait_for_component_stop().await;
}
}
#[fuchsia_async::run_singlethreaded(test)]
async fn advanced_routing_test() -> Result<(), Error> {
let root_component_url = "fuchsia-pkg://fuchsia.com/hub_integration_test#meta/echo_realm.cm";
let test_runner = TestRunner::new(root_component_url).await?;
// Verify that echo_realm has two children.
test_runner
.verify_global_directory_listing("children", vec!["echo_server", "hub_client"])
.await;
// Verify hub_client's instance id.
test_runner.verify_global_file_content("children/hub_client/id", "0").await;
// Verify echo_server's instance id.
test_runner.verify_global_file_content("children/echo_server/id", "0").await;
// Verify the args from hub_client.cml.
test_runner
.verify_global_file_content("children/hub_client/exec/runtime/args/0", "Hippos")
.await;
test_runner
.verify_global_file_content("children/hub_client/exec/runtime/args/1", "rule!")
.await;
let echo_service_name = "fidl.examples.routing.echo.Echo";
let hub_report_service_name = "fuchsia.test.hub.HubReport";
let expose_svc_dir = "children/echo_server/exec/expose/svc";
// Verify that the Echo service is exposed by echo_server
test_runner.verify_global_directory_listing(expose_svc_dir, vec![echo_service_name]).await;
// Verify that hub_client is using HubReport and Echo services
let in_dir = "children/hub_client/exec/in";
let svc_dir = format!("{}/{}", in_dir, "svc");
test_runner
.verify_global_directory_listing(
svc_dir.as_str(),
vec![echo_service_name, hub_report_service_name],
)
.await;
// Verify that the 'pkg' directory is available.
let pkg_dir = format!("{}/{}", in_dir, "pkg");
test_runner
.verify_global_directory_listing(pkg_dir.as_str(), vec!["bin", "lib", "meta", "test"])
.await;
// Verify that we can connect to the echo service from the in/svc directory.
let in_echo_service_path = format!("{}/{}", svc_dir, echo_service_name);
test_runner.connect_to_echo_service(in_echo_service_path).await?;
// Verify that we can connect to the echo service from the expose/svc directory.
let expose_echo_service_path = format!("{}/{}", expose_svc_dir, echo_service_name);
test_runner.connect_to_echo_service(expose_echo_service_path).await?;
// Verify that the 'hub' directory is available. The 'hub' mapped to 'hub_client''s
// namespace is actually mapped to the 'exec' directory of 'hub_client'.
let scoped_hub_dir = format!("{}/{}", in_dir, "hub");
test_runner
.verify_global_directory_listing(
scoped_hub_dir.as_str(),
vec!["expose", "in", "out", "resolved_url", "runtime"],
)
.await;
let responder = test_runner
.verify_local_directory_listing(
"/hub",
vec!["expose", "in", "out", "resolved_url", "runtime"],
)
.await;
responder.send().expect("Could not respond");
// Verify that hub_client's view is able to correctly read the names of the
// children of the parent echo_realm.
let responder = test_runner
.verify_local_directory_listing("/parent_hub/children", vec!["echo_server", "hub_client"])
.await;
responder.send().expect("Could not respond");
// Verify that hub_client is able to see its sibling's hub correctly.
test_runner
.verify_local_file_content(
"/sibling_hub/exec/resolved_url",
"fuchsia-pkg://fuchsia.com/hub_integration_test#meta/echo_server.cm",
)
.await;
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn dynamic_child_test() -> Result<(), Error> {
let root_component_url =
"fuchsia-pkg://fuchsia.com/hub_integration_test#meta/dynamic_child_reporter.cm";
let test_runner = TestRunner::new_with_breakpoints(
root_component_url,
vec![
EventType::PreDestroyInstance,
EventType::StopInstance,
EventType::PostDestroyInstance,
],
)
.await?;
// Verify that the dynamic child exists in the parent's hub
test_runner.verify_directory_listing("children", vec!["coll:simple_instance"]).await;
// Before binding, verify that the dynamic child's hub has the directories we expect
// i.e. "children" and "url" but no "exec" because the child has not been bound.
test_runner
.verify_directory_listing(
"children/coll:simple_instance",
vec!["children", "deleting", "id", "url"],
)
.await;
// Verify that the dynamic child has the correct instance id.
test_runner.verify_local_file_content("/hub/children/coll:simple_instance/id", "1").await;
// Before binding, verify that the dynamic child's static children are invisible
test_runner.verify_directory_listing("children/coll:simple_instance/children", vec![]).await;
// After binding, verify that the dynamic child's hub has the directories we expect
test_runner
.verify_directory_listing(
"children/coll:simple_instance",
vec!["children", "deleting", "exec", "id", "url"],
)
.await;
// After binding, verify that the dynamic child's static child is visible
test_runner
.verify_directory_listing("children/coll:simple_instance/children", vec!["child"])
.await;
// Verify that the dynamic child's static child has the correct instance id.
test_runner
.verify_local_file_content("/hub/children/coll:simple_instance/children/child/id", "0")
.await;
// Wait for the dynamic child to begin deletion
let breakpoint = test_runner
.expect_invocation(EventType::PreDestroyInstance, vec!["coll:simple_instance:1"])
.await;
// When deletion begins, the dynamic child should be moved to the deleting directory
test_runner.verify_directory_listing("children", vec![]).await;
test_runner.verify_directory_listing("deleting", vec!["coll:simple_instance:1"]).await;
test_runner
.verify_directory_listing(
"deleting/coll:simple_instance:1",
vec!["children", "deleting", "exec", "id", "url"],
)
.await;
// Unblock the ComponentManager
breakpoint.resume();
// Wait for the dynamic child to stop
let breakpoint = test_runner
.expect_invocation(EventType::StopInstance, vec!["coll:simple_instance:1"])
.await;
// After stopping, the dynamic child should not have an exec directory
test_runner
.verify_directory_listing(
"deleting/coll:simple_instance:1",
vec!["children", "deleting", "id", "url"],
)
.await;
// Unblock the Component Manager
breakpoint.resume();
// Wait for the dynamic child's static child to begin deletion
let breakpoint = test_runner
.expect_invocation(EventType::PreDestroyInstance, vec!["coll:simple_instance:1", "child:0"])
.await;
// When deletion begins, the dynamic child's static child should be moved to the deleting directory
test_runner.verify_directory_listing("deleting/coll:simple_instance:1/children", vec![]).await;
test_runner
.verify_directory_listing("deleting/coll:simple_instance:1/deleting", vec!["child:0"])
.await;
test_runner
.verify_directory_listing(
"deleting/coll:simple_instance:1/deleting/child:0",
vec!["children", "deleting", "id", "url"],
)
.await;
// Unblock the Component Manager
breakpoint.resume();
// Wait for the dynamic child's static child to be destroyed
let breakpoint = test_runner
.expect_invocation(
EventType::PostDestroyInstance,
vec!["coll:simple_instance:1", "child:0"],
)
.await;
// The dynamic child's static child should not be visible in the hub anymore
test_runner.verify_directory_listing("deleting/coll:simple_instance:1/deleting", vec![]).await;
// Unblock the Component Manager
breakpoint.resume();
// Wait for the dynamic child to be destroyed
let breakpoint = test_runner
.expect_invocation(EventType::PostDestroyInstance, vec!["coll:simple_instance:1"])
.await;
// After deletion, verify that parent can no longer see the dynamic child in the Hub
test_runner.verify_directory_listing("deleting", vec![]).await;
// Unblock the Component Manager
breakpoint.resume();
// Wait for the component to stop
test_runner.wait_for_component_stop().await;
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn visibility_test() -> Result<(), Error> {
let root_component_url =
"fuchsia-pkg://fuchsia.com/hub_integration_test#meta/visibility_reporter.cm";
let test_runner = TestRunner::new(root_component_url).await?;
// Verify that the child exists in the parent's hub
test_runner.verify_directory_listing("children", vec!["child"]).await;
// Verify that the child's hub has the directories we expect
// i.e. no "exec" because the child has not been bound.
test_runner
.verify_directory_listing("children/child", vec!["children", "deleting", "id", "url"])
.await;
// Verify that the grandchild is not shown because the child is lazy
test_runner.verify_directory_listing("children/child/children", vec![]).await;
Ok(())
}
|
mod mem_regions;
use gba_mem::mem_regions::{SystemRom, ExternRam, InternRam,
PalettRam, VisualRam, OAM, PakRom,
MemRead, MemWrite, MemoryRegion};
use std::io;
pub type Address = usize;
#[derive(Debug)]
pub struct Memory {
sys_rom: SystemRom,
ext_ram: ExternRam,
int_ram: InternRam,
pal_ram: PalettRam,
vis_ram: VisualRam,
oam: OAM,
pak_rom: PakRom,
}
impl Memory {
pub fn new(pak_filename: &str) -> io::Result<Memory> {
println!("WARNING: BIOS emulation not implemented. Please emulate bios rather than use a ROM.");
Ok(Memory {
sys_rom: SystemRom::create_from_array(include_bytes!("../../roms/gba.bin")),
ext_ram: ExternRam::default(),
int_ram: InternRam::default(),
pal_ram: PalettRam::default(),
vis_ram: VisualRam::default(),
oam: OAM::default(),
pak_rom: try!(PakRom::create_from_file(pak_filename)),
})
}
pub fn read<T>(&self, addr: Address) -> T
where SystemRom: MemRead<T>,
ExternRam: MemRead<T>,
InternRam: MemRead<T>,
PalettRam: MemRead<T>,
VisualRam: MemRead<T>,
OAM: MemRead<T>,
PakRom: MemRead<T> {
match addr {
_ if addr >= SystemRom::lo() && addr <= SystemRom::hi() =>
<SystemRom as MemRead<T>>::read(&self.sys_rom, addr),
_ if addr >= ExternRam::lo() && addr <= ExternRam::hi() =>
<ExternRam as MemRead<T>>::read(&self.ext_ram, addr),
_ if addr >= InternRam::lo() && addr <= InternRam::hi() =>
<InternRam as MemRead<T>>::read(&self.int_ram, addr),
_ if addr >= PalettRam::lo() && addr <= PalettRam::hi() =>
<PalettRam as MemRead<T>>::read(&self.pal_ram, addr),
_ if addr >= VisualRam::lo() && addr <= VisualRam::hi() =>
<VisualRam as MemRead<T>>::read(&self.vis_ram, addr),
_ if addr >= OAM::lo() && addr <= OAM::hi() =>
<OAM as MemRead<T>>::read(&self.oam, addr),
_ if addr >= PakRom::lo() && addr <= PakRom::hi() =>
<PakRom as MemRead<T>>::read(&self.pak_rom, addr),
_ => unreachable!(),
}
}
pub fn write8<T>(&mut self, addr: Address, val: T)
where ExternRam: MemWrite<T>,
InternRam: MemWrite<T>,
PakRom: MemWrite<T> {
match addr {
_ if addr >= ExternRam::lo() && addr <= ExternRam::hi() =>
<ExternRam as MemWrite<T>>::write(&mut self.ext_ram, addr, val),
_ if addr >= InternRam::lo() && addr <= InternRam::hi() =>
<InternRam as MemWrite<T>>::write(&mut self.int_ram, addr, val),
_ if addr >= PakRom::lo() && addr <= PakRom::hi() =>
<PakRom as MemWrite<T>>::write(&mut self.pak_rom, addr, val),
_ => unreachable!(),
}
}
pub fn write16<T>(&mut self, addr: Address, val: T)
where ExternRam: MemWrite<T>,
InternRam: MemWrite<T>,
PalettRam: MemWrite<T>,
VisualRam: MemWrite<T>,
OAM: MemWrite<T>,
PakRom: MemWrite<T> {
match addr {
_ if addr >= ExternRam::lo() && addr <= ExternRam::hi() =>
<ExternRam as MemWrite<T>>::write(&mut self.ext_ram, addr, val),
_ if addr >= InternRam::lo() && addr <= InternRam::hi() =>
<InternRam as MemWrite<T>>::write(&mut self.int_ram, addr, val),
_ if addr >= PalettRam::lo() && addr <= PalettRam::hi() =>
<PalettRam as MemWrite<T>>::write(&mut self.pal_ram, addr, val),
_ if addr >= VisualRam::lo() && addr <= VisualRam::hi() =>
<VisualRam as MemWrite<T>>::write(&mut self.vis_ram, addr, val),
_ if addr >= OAM::lo() && addr <= OAM::hi() =>
<OAM as MemWrite<T>>::write(&mut self.oam, addr, val),
_ if addr >= PakRom::lo() && addr <= PakRom::hi() =>
<PakRom as MemWrite<T>>::write(&mut self.pak_rom, addr, val),
_ => unreachable!(),
}
}
pub fn write32<T>(&mut self, addr: Address, val: T)
where ExternRam: MemWrite<T>,
InternRam: MemWrite<T>,
PalettRam: MemWrite<T>,
VisualRam: MemWrite<T>,
OAM: MemWrite<T>,
PakRom: MemWrite<T> {
self.write16::<T>(addr, val);
}
}
// impl Mem {
// fn new(pak_filename: String) -> Mem {
// let mut pak_rom_file = File::open(pak_filename).expect("Failed to open PAK ROM file");
// let mut pak_rom = Vec::<u8>::new();
// pak_rom_file.read_to_end(&mut pak_rom).expect("Failed to read PAK ROM");
// //let mut pak_rom = u8_slice_to_u16_slice(&pak_rom);
// Mem {
// system_rom: [0;SYSTEM_ROM_SIZE as usize],
// extern_ram: [0;EXTERN_RAM_SIZE as usize],
// intern_ram: [0;INTERN_RAM_SIZE as usize],
// palett_ram: [0;PALETT_RAM_SIZE as usize],
// vram: [0;VRAM_SIZE as usize],
// oam: [0;OAM_SIZE as usize],
// pak_rom: pak_rom.into_boxed_slice(),
// }
// }
// }
|
mod jwt;
use std::cmp::{Eq, PartialEq};
pub mod pwd;
pub mod service;
use serde::{Deserialize, Serialize};
#[derive(juniper::GraphQLObject)]
pub struct Session {
jwt: String,
}
#[derive(juniper::GraphQLInputObject)]
pub struct AuthenticationData {
email: String,
password: String,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct Claims {
pub exp: usize,
pub id: String,
pub email: String,
pub first_name: String,
pub last_name: String,
pub phone: String,
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use itertools::Itertools;
use nom::branch::alt;
use nom::combinator::consumed;
use nom::combinator::map;
use nom::combinator::value;
use nom::error::context;
use pratt::Affix;
use pratt::Associativity;
use pratt::PrattParser;
use pratt::Precedence;
use crate::ast::*;
use crate::input::Input;
use crate::input::WithSpan;
use crate::match_token;
use crate::parser::query::*;
use crate::parser::token::*;
use crate::parser::unescape::unescape;
use crate::rule;
use crate::util::*;
use crate::Error;
use crate::ErrorKind;
pub const BETWEEN_PREC: u32 = 20;
pub const NOT_PREC: u32 = 15;
pub fn expr(i: Input) -> IResult<Expr> {
context("expression", subexpr(0))(i)
}
fn expr_or_placeholder(i: Input) -> IResult<Option<Expr>> {
alt((map(rule! { "?" }, |_| None), map(subexpr(0), Some)))(i)
}
pub fn values_with_placeholder(i: Input) -> IResult<Vec<Option<Expr>>> {
let values = comma_separated_list0(expr_or_placeholder);
map(rule! { ( "(" ~ #values ~ ")" ) }, |(_, v, _)| v)(i)
}
pub fn subexpr(min_precedence: u32) -> impl FnMut(Input) -> IResult<Expr> {
move |i| {
let higher_prec_expr_element =
|i| {
expr_element(i).and_then(|(rest, elem)| {
match PrattParser::<std::iter::Once<_>>::query(&mut ExprParser, &elem).unwrap()
{
Affix::Infix(prec, _) | Affix::Prefix(prec) | Affix::Postfix(prec)
if prec <= Precedence(min_precedence) =>
{
Err(nom::Err::Error(Error::from_error_kind(
i,
ErrorKind::Other("expected more tokens for expression"),
)))
}
_ => Ok((rest, elem)),
}
})
};
let (rest, mut expr_elements) = rule! { #higher_prec_expr_element+ }(i)?;
for (prev, curr) in (-1..(expr_elements.len() as isize)).tuple_windows() {
// Replace binary Plus and Minus to the unary one, if it's following another op
// or it's the first element.
if prev == -1
|| matches!(
expr_elements[prev as usize].elem,
ExprElement::UnaryOp { .. } | ExprElement::BinaryOp { .. }
)
{
match &mut expr_elements[curr as usize].elem {
elem @ ExprElement::BinaryOp {
op: BinaryOperator::Plus,
} => {
*elem = ExprElement::UnaryOp {
op: UnaryOperator::Plus,
};
}
elem @ ExprElement::BinaryOp {
op: BinaryOperator::Minus,
} => {
*elem = ExprElement::UnaryOp {
op: UnaryOperator::Minus,
};
}
_ => {}
}
}
// If it's following a prefix or infix element or it's the first element, ...
if prev == -1
|| matches!(
PrattParser::<std::iter::Once<_>>::query(
&mut ExprParser,
&expr_elements[prev as usize]
)
.unwrap(),
Affix::Prefix(_) | Affix::Infix(_, _)
)
{
// replace bracket map access to an array, ...
if let ExprElement::MapAccess {
accessor: MapAccessor::Bracket { key },
} = &expr_elements[curr as usize].elem
{
let span = expr_elements[curr as usize].span;
expr_elements[curr as usize] = WithSpan {
span,
elem: ExprElement::Array {
exprs: vec![(**key).clone()],
},
};
}
// and replace `.<number>` map access to floating point literal.
if let ExprElement::MapAccess {
accessor: MapAccessor::PeriodNumber { .. },
} = &expr_elements[curr as usize].elem
{
let span = expr_elements[curr as usize].span;
expr_elements[curr as usize] = WithSpan {
span,
elem: ExprElement::Literal {
lit: literal(span)?.1,
},
};
}
}
if prev != -1 {
if let (
ExprElement::UnaryOp {
op: UnaryOperator::Minus,
},
ExprElement::Literal { lit },
) = (
&expr_elements[prev as usize].elem,
&expr_elements[curr as usize].elem,
) {
if matches!(
lit,
Literal::Float(_)
| Literal::UInt64(_)
| Literal::Decimal128 { .. }
| Literal::Decimal256 { .. }
) {
let span = expr_elements[curr as usize].span;
expr_elements[curr as usize] = WithSpan {
span,
elem: ExprElement::Literal { lit: lit.neg() },
};
let span = expr_elements[prev as usize].span;
expr_elements[prev as usize] = WithSpan {
span,
elem: ExprElement::Skip,
};
}
}
}
}
let iter = &mut expr_elements
.into_iter()
.filter(|x| x.elem != ExprElement::Skip)
.collect::<Vec<_>>()
.into_iter();
run_pratt_parser(ExprParser, iter, rest, i)
}
}
/// A 'flattened' AST of expressions.
///
/// This is used to parse expressions in Pratt parser.
/// The Pratt parser is not able to parse expressions by grammar. So we need to extract
/// the expression operands and operators to be the input of Pratt parser, by running a
/// nom parser in advance.
///
/// For example, `a + b AND c is null` is parsed as `[col(a), PLUS, col(b), AND, col(c), ISNULL]` by nom parsers.
/// Then the Pratt parser is able to parse the expression into `AND(PLUS(col(a), col(b)), ISNULL(col(c)))`.
#[derive(Debug, Clone, PartialEq)]
pub enum ExprElement {
/// Column reference, with indirection like `table.column`
ColumnRef {
database: Option<Identifier>,
table: Option<Identifier>,
column: Identifier,
},
/// `IS [NOT] NULL` expression
IsNull {
not: bool,
},
/// `IS [NOT] DISTINCT FROM` expression
IsDistinctFrom {
not: bool,
},
/// `[ NOT ] IN (list, ...)`
InList {
list: Vec<Expr>,
not: bool,
},
/// `[ NOT ] IN (SELECT ...)`
InSubquery {
subquery: Box<Query>,
not: bool,
},
/// `BETWEEN ... AND ...`
Between {
low: Box<Expr>,
high: Box<Expr>,
not: bool,
},
/// Binary operation
BinaryOp {
op: BinaryOperator,
},
/// Unary operation
UnaryOp {
op: UnaryOperator,
},
/// `CAST` expression, like `CAST(expr AS target_type)`
Cast {
expr: Box<Expr>,
target_type: TypeName,
},
/// `TRY_CAST` expression`
TryCast {
expr: Box<Expr>,
target_type: TypeName,
},
/// `::<type_name>` expression
PgCast {
target_type: TypeName,
},
/// EXTRACT(IntervalKind FROM <expr>)
Extract {
field: IntervalKind,
expr: Box<Expr>,
},
/// POSITION(<expr> IN <expr>)
Position {
substr_expr: Box<Expr>,
str_expr: Box<Expr>,
},
/// SUBSTRING(<expr> [FROM <expr>] [FOR <expr>])
SubString {
expr: Box<Expr>,
substring_from: Box<Expr>,
substring_for: Option<Box<Expr>>,
},
/// TRIM([[BOTH | LEADING | TRAILING] <expr> FROM] <expr>)
/// Or
/// TRIM(<expr>)
Trim {
expr: Box<Expr>,
// ([BOTH | LEADING | TRAILING], <expr>)
trim_where: Option<(TrimWhere, Box<Expr>)>,
},
/// A literal value, such as string, number, date or NULL
Literal {
lit: Literal,
},
/// `Count(*)` expression
CountAll,
/// `(foo, bar)`
Tuple {
exprs: Vec<Expr>,
},
/// Scalar function call
FunctionCall {
/// Set to true if the function is aggregate function with `DISTINCT`, like `COUNT(DISTINCT a)`
distinct: bool,
name: Identifier,
args: Vec<Expr>,
window: Option<WindowSpec>,
params: Vec<Literal>,
},
/// `CASE ... WHEN ... ELSE ...` expression
Case {
operand: Option<Box<Expr>>,
conditions: Vec<Expr>,
results: Vec<Expr>,
else_result: Option<Box<Expr>>,
},
/// `EXISTS` expression
Exists {
subquery: Query,
not: bool,
},
/// Scalar/ANY/ALL/SOME subquery
Subquery {
modifier: Option<SubqueryModifier>,
subquery: Query,
},
/// Access elements of `Array`, `Object` and `Variant` by index or key, like `arr[0]`, or `obj:k1`
MapAccess {
accessor: MapAccessor,
},
/// An expression between parentheses
Group(Expr),
/// `[1, 2, 3]`
Array {
exprs: Vec<Expr>,
},
/// ARRAY_SORT([1,2,3], ASC|DESC, NULLS FIRST|LAST)
ArraySort {
expr: Box<Expr>,
// Optional `ASC` or `DESC`
asc: Option<String>,
// Optional `NULLS FIRST` or `NULLS LAST`
nulls_first: Option<String>,
},
/// `{'k1':'v1','k2':'v2'}`
Map {
kvs: Vec<(Expr, Expr)>,
},
Interval {
expr: Expr,
unit: IntervalKind,
},
DateAdd {
unit: IntervalKind,
interval: Expr,
date: Expr,
},
DateSub {
unit: IntervalKind,
interval: Expr,
date: Expr,
},
DateTrunc {
unit: IntervalKind,
date: Expr,
},
Skip,
}
struct ExprParser;
impl<'a, I: Iterator<Item = WithSpan<'a, ExprElement>>> PrattParser<I> for ExprParser {
type Error = &'static str;
type Input = WithSpan<'a, ExprElement>;
type Output = Expr;
fn query(&mut self, elem: &WithSpan<ExprElement>) -> Result<Affix, &'static str> {
let affix = match &elem.elem {
ExprElement::MapAccess { .. } => Affix::Postfix(Precedence(25)),
ExprElement::IsNull { .. } => Affix::Postfix(Precedence(17)),
ExprElement::Between { .. } => Affix::Postfix(Precedence(BETWEEN_PREC)),
ExprElement::IsDistinctFrom { .. } => {
Affix::Infix(Precedence(BETWEEN_PREC), Associativity::Left)
}
ExprElement::InList { .. } => Affix::Postfix(Precedence(BETWEEN_PREC)),
ExprElement::InSubquery { .. } => Affix::Postfix(Precedence(BETWEEN_PREC)),
ExprElement::UnaryOp { op } => match op {
UnaryOperator::Not => Affix::Prefix(Precedence(NOT_PREC)),
UnaryOperator::Plus => Affix::Prefix(Precedence(50)),
UnaryOperator::Minus => Affix::Prefix(Precedence(50)),
UnaryOperator::BitwiseNot => Affix::Prefix(Precedence(50)),
UnaryOperator::SquareRoot => Affix::Prefix(Precedence(60)),
UnaryOperator::CubeRoot => Affix::Prefix(Precedence(60)),
UnaryOperator::Abs => Affix::Prefix(Precedence(60)),
UnaryOperator::Factorial => Affix::Postfix(Precedence(60)),
},
ExprElement::BinaryOp { op } => match op {
BinaryOperator::Or => Affix::Infix(Precedence(5), Associativity::Left),
BinaryOperator::And => Affix::Infix(Precedence(10), Associativity::Left),
BinaryOperator::Eq => Affix::Infix(Precedence(20), Associativity::Right),
BinaryOperator::NotEq => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::Gt => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::Lt => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::Gte => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::Lte => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::Like => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::NotLike => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::Regexp => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::NotRegexp => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::RLike => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::NotRLike => Affix::Infix(Precedence(20), Associativity::Left),
BinaryOperator::BitwiseOr => Affix::Infix(Precedence(22), Associativity::Left),
BinaryOperator::BitwiseAnd => Affix::Infix(Precedence(22), Associativity::Left),
BinaryOperator::BitwiseXor => Affix::Infix(Precedence(22), Associativity::Left),
BinaryOperator::BitwiseShiftLeft => {
Affix::Infix(Precedence(23), Associativity::Left)
}
BinaryOperator::BitwiseShiftRight => {
Affix::Infix(Precedence(23), Associativity::Left)
}
BinaryOperator::Xor => Affix::Infix(Precedence(24), Associativity::Left),
BinaryOperator::Plus => Affix::Infix(Precedence(30), Associativity::Left),
BinaryOperator::Minus => Affix::Infix(Precedence(30), Associativity::Left),
BinaryOperator::Multiply => Affix::Infix(Precedence(40), Associativity::Left),
BinaryOperator::Div => Affix::Infix(Precedence(40), Associativity::Left),
BinaryOperator::Divide => Affix::Infix(Precedence(40), Associativity::Left),
BinaryOperator::Modulo => Affix::Infix(Precedence(40), Associativity::Left),
BinaryOperator::StringConcat => Affix::Infix(Precedence(40), Associativity::Left),
BinaryOperator::Caret => Affix::Infix(Precedence(40), Associativity::Left),
},
ExprElement::PgCast { .. } => Affix::Postfix(Precedence(60)),
_ => Affix::Nilfix,
};
Ok(affix)
}
fn primary(&mut self, elem: WithSpan<'a, ExprElement>) -> Result<Expr, &'static str> {
let expr = match elem.elem {
ExprElement::ColumnRef {
database,
table,
column,
} => Expr::ColumnRef {
span: transform_span(elem.span.0),
database,
table,
column,
},
ExprElement::Cast { expr, target_type } => Expr::Cast {
span: transform_span(elem.span.0),
expr,
target_type,
pg_style: false,
},
ExprElement::TryCast { expr, target_type } => Expr::TryCast {
span: transform_span(elem.span.0),
expr,
target_type,
},
ExprElement::Extract { field, expr } => Expr::Extract {
span: transform_span(elem.span.0),
kind: field,
expr,
},
ExprElement::Position {
substr_expr,
str_expr,
} => Expr::Position {
span: transform_span(elem.span.0),
substr_expr,
str_expr,
},
ExprElement::SubString {
expr,
substring_from,
substring_for,
} => Expr::Substring {
span: transform_span(elem.span.0),
expr,
substring_from,
substring_for,
},
ExprElement::Trim { expr, trim_where } => Expr::Trim {
span: transform_span(elem.span.0),
expr,
trim_where,
},
ExprElement::Literal { lit } => Expr::Literal {
span: transform_span(elem.span.0),
lit,
},
ExprElement::CountAll => Expr::CountAll {
span: transform_span(elem.span.0),
},
ExprElement::Tuple { exprs } => Expr::Tuple {
span: transform_span(elem.span.0),
exprs,
},
ExprElement::FunctionCall {
distinct,
name,
args,
params,
window,
} => Expr::FunctionCall {
span: transform_span(elem.span.0),
distinct,
name,
args,
params,
window,
},
ExprElement::Case {
operand,
conditions,
results,
else_result,
} => Expr::Case {
span: transform_span(elem.span.0),
operand,
conditions,
results,
else_result,
},
ExprElement::Exists { subquery, not } => Expr::Exists {
span: transform_span(elem.span.0),
not,
subquery: Box::new(subquery),
},
ExprElement::Subquery { subquery, modifier } => Expr::Subquery {
span: transform_span(elem.span.0),
modifier,
subquery: Box::new(subquery),
},
ExprElement::Group(expr) => expr,
ExprElement::Array { exprs } => Expr::Array {
span: transform_span(elem.span.0),
exprs,
},
ExprElement::ArraySort {
expr,
asc,
nulls_first,
} => {
let asc = if let Some(asc) = asc {
if asc.to_lowercase() == "asc" {
true
} else if asc.to_lowercase() == "desc" {
false
} else {
return Err("Sorting order must be either ASC or DESC");
}
} else {
true
};
let null_first = if let Some(nulls_first) = nulls_first {
let null_first = nulls_first.trim().to_lowercase();
if null_first == "nulls first" {
true
} else if null_first == "nulls last" {
false
} else {
return Err("Null sorting order must be either NULLS FIRST or NULLS LAST");
}
} else {
true
};
Expr::ArraySort {
span: transform_span(elem.span.0),
expr,
asc,
null_first,
}
}
ExprElement::Map { kvs } => Expr::Map {
span: transform_span(elem.span.0),
kvs,
},
ExprElement::Interval { expr, unit } => Expr::Interval {
span: transform_span(elem.span.0),
expr: Box::new(expr),
unit,
},
ExprElement::DateAdd {
unit,
interval,
date,
} => Expr::DateAdd {
span: transform_span(elem.span.0),
unit,
interval: Box::new(interval),
date: Box::new(date),
},
ExprElement::DateSub {
unit,
interval,
date,
} => Expr::DateSub {
span: transform_span(elem.span.0),
unit,
interval: Box::new(interval),
date: Box::new(date),
},
ExprElement::DateTrunc { unit, date } => Expr::DateTrunc {
span: transform_span(elem.span.0),
unit,
date: Box::new(date),
},
_ => unreachable!(),
};
Ok(expr)
}
fn infix(
&mut self,
lhs: Expr,
elem: WithSpan<'a, ExprElement>,
rhs: Expr,
) -> Result<Expr, &'static str> {
let expr = match elem.elem {
ExprElement::BinaryOp { op } => Expr::BinaryOp {
span: transform_span(elem.span.0),
left: Box::new(lhs),
right: Box::new(rhs),
op,
},
ExprElement::IsDistinctFrom { not } => Expr::IsDistinctFrom {
span: transform_span(elem.span.0),
left: Box::new(lhs),
right: Box::new(rhs),
not,
},
_ => unreachable!(),
};
Ok(expr)
}
fn prefix(&mut self, elem: WithSpan<'a, ExprElement>, rhs: Expr) -> Result<Expr, &'static str> {
let expr = match elem.elem {
ExprElement::UnaryOp { op } => Expr::UnaryOp {
span: transform_span(elem.span.0),
op,
expr: Box::new(rhs),
},
_ => unreachable!(),
};
Ok(expr)
}
fn postfix(
&mut self,
lhs: Expr,
elem: WithSpan<'a, ExprElement>,
) -> Result<Expr, &'static str> {
let expr = match elem.elem {
ExprElement::MapAccess { accessor } => Expr::MapAccess {
span: transform_span(elem.span.0),
expr: Box::new(lhs),
accessor,
},
ExprElement::IsNull { not } => Expr::IsNull {
span: transform_span(elem.span.0),
expr: Box::new(lhs),
not,
},
ExprElement::InList { list, not } => Expr::InList {
span: transform_span(elem.span.0),
expr: Box::new(lhs),
list,
not,
},
ExprElement::InSubquery { subquery, not } => Expr::InSubquery {
span: transform_span(elem.span.0),
expr: Box::new(lhs),
subquery,
not,
},
ExprElement::Between { low, high, not } => Expr::Between {
span: transform_span(elem.span.0),
expr: Box::new(lhs),
low,
high,
not,
},
ExprElement::PgCast { target_type } => Expr::Cast {
span: transform_span(elem.span.0),
expr: Box::new(lhs),
target_type,
pg_style: true,
},
ExprElement::UnaryOp { op } => Expr::UnaryOp {
span: transform_span(elem.span.0),
op,
expr: Box::new(lhs),
},
_ => unreachable!(),
};
Ok(expr)
}
}
pub fn expr_element(i: Input) -> IResult<WithSpan<ExprElement>> {
let column_ref = map(
period_separated_idents_1_to_3,
|(database, table, column)| ExprElement::ColumnRef {
database,
table,
column,
},
);
let is_null = map(
rule! {
IS ~ NOT? ~ NULL
},
|(_, opt_not, _)| ExprElement::IsNull {
not: opt_not.is_some(),
},
);
let in_list = map(
rule! {
NOT? ~ IN ~ "(" ~ #comma_separated_list1(subexpr(0)) ~ ^")"
},
|(opt_not, _, _, list, _)| ExprElement::InList {
list,
not: opt_not.is_some(),
},
);
let in_subquery = map(
rule! {
NOT? ~ IN ~ "(" ~ #query ~ ^")"
},
|(opt_not, _, _, subquery, _)| ExprElement::InSubquery {
subquery: Box::new(subquery),
not: opt_not.is_some(),
},
);
let between = map(
rule! {
NOT? ~ BETWEEN ~ ^#subexpr(BETWEEN_PREC) ~ ^AND ~ ^#subexpr(BETWEEN_PREC)
},
|(opt_not, _, low, _, high)| ExprElement::Between {
low: Box::new(low),
high: Box::new(high),
not: opt_not.is_some(),
},
);
let cast = map(
rule! {
( CAST | TRY_CAST )
~ "("
~ ^#subexpr(0)
~ ^( AS | "," )
~ ^#type_name
~ ^")"
},
|(cast, _, expr, _, target_type, _)| {
if cast.kind == CAST {
ExprElement::Cast {
expr: Box::new(expr),
target_type,
}
} else {
ExprElement::TryCast {
expr: Box::new(expr),
target_type,
}
}
},
);
let pg_cast = map(
rule! {
"::" ~ ^#type_name
},
|(_, target_type)| ExprElement::PgCast { target_type },
);
let extract = map(
rule! {
EXTRACT ~ "(" ~ ^#interval_kind ~ ^FROM ~ ^#subexpr(0) ~ ^")"
},
|(_, _, field, _, expr, _)| ExprElement::Extract {
field,
expr: Box::new(expr),
},
);
let position = map(
rule! {
POSITION
~ "("
~ ^#subexpr(BETWEEN_PREC)
~ ^IN
~ ^#subexpr(0)
~ ^")"
},
|(_, _, substr_expr, _, str_expr, _)| ExprElement::Position {
substr_expr: Box::new(substr_expr),
str_expr: Box::new(str_expr),
},
);
let substring = map(
rule! {
( SUBSTRING | SUBSTR )
~ "("
~ ^#subexpr(0)
~ ( FROM | "," )
~ ^#subexpr(0)
~ ( ( FOR | "," ) ~ ^#subexpr(0) )?
~ ^")"
},
|(_, _, expr, _, substring_from, opt_substring_for, _)| ExprElement::SubString {
expr: Box::new(expr),
substring_from: Box::new(substring_from),
substring_for: opt_substring_for.map(|(_, expr)| Box::new(expr)),
},
);
let trim_where = alt((
value(TrimWhere::Both, rule! { BOTH }),
value(TrimWhere::Leading, rule! { LEADING }),
value(TrimWhere::Trailing, rule! { TRAILING }),
));
let trim = map(
rule! {
TRIM
~ "("
~ #subexpr(0)
~ ^")"
},
|(_, _, expr, _)| ExprElement::Trim {
expr: Box::new(expr),
trim_where: None,
},
);
let trim_from = map(
rule! {
TRIM
~ "("
~ #trim_where
~ ^#subexpr(0)
~ ^FROM
~ ^#subexpr(0)
~ ^")"
},
|(_, _, trim_where, trim_str, _, expr, _)| ExprElement::Trim {
expr: Box::new(expr),
trim_where: Some((trim_where, Box::new(trim_str))),
},
);
let count_all = value(ExprElement::CountAll, rule! {
COUNT ~ "(" ~ "*" ~ ^")"
});
let tuple = map(
rule! {
"(" ~ #comma_separated_list0_ignore_trailing(subexpr(0)) ~ ","? ~ ^")"
},
|(_, mut exprs, opt_trail, _)| {
if exprs.len() == 1 && opt_trail.is_none() {
ExprElement::Group(exprs.remove(0))
} else {
ExprElement::Tuple { exprs }
}
},
);
let window_frame_between = alt((
map(
rule! { BETWEEN ~ #window_frame_bound ~ AND ~ #window_frame_bound },
|(_, s, _, e)| (s, e),
),
map(rule! {#window_frame_bound}, |s| {
(s, WindowFrameBound::Following(None))
}),
));
let window_spec = map(
rule! {
(PARTITION ~ ^BY ~ #comma_separated_list1(subexpr(0)))?
~ ( ORDER ~ ^BY ~ ^#comma_separated_list1(order_by_expr) )?
~ ((ROWS | RANGE) ~ #window_frame_between)?
},
|(opt_partition, opt_order, between)| WindowSpec {
partition_by: opt_partition.map(|x| x.2).unwrap_or_default(),
order_by: opt_order.map(|x| x.2).unwrap_or_default(),
window_frame: between.map(|x| {
let unit = match x.0.kind {
ROWS => WindowFrameUnits::Rows,
RANGE => WindowFrameUnits::Range,
_ => unreachable!(),
};
let bw = x.1;
WindowFrame {
units: unit,
start_bound: bw.0,
end_bound: bw.1,
}
}),
},
);
let function_call = map(
rule! {
#function_name
~ "(" ~ DISTINCT? ~ #comma_separated_list0(subexpr(0))? ~ ")"
},
|(name, _, opt_distinct, opt_args, _)| ExprElement::FunctionCall {
distinct: opt_distinct.is_some(),
name,
args: opt_args.unwrap_or_default(),
params: vec![],
window: None,
},
);
let function_call_with_window = map(
rule! {
#function_name
~ "(" ~ DISTINCT? ~ #comma_separated_list0(subexpr(0))? ~ ")"
~ (OVER ~ "(" ~ #window_spec ~ ")")
},
|(name, _, opt_distinct, opt_args, _, window)| ExprElement::FunctionCall {
distinct: opt_distinct.is_some(),
name,
args: opt_args.unwrap_or_default(),
params: vec![],
window: Some(window.2),
},
);
let function_call_with_params = map(
rule! {
#function_name
~ ("(" ~ #comma_separated_list1(literal) ~ ")")?
~ "(" ~ DISTINCT? ~ #comma_separated_list0(subexpr(0))? ~ ")"
},
|(name, params, _, opt_distinct, opt_args, _)| ExprElement::FunctionCall {
distinct: opt_distinct.is_some(),
name,
args: opt_args.unwrap_or_default(),
params: params.map(|x| x.1).unwrap_or_default(),
window: None,
},
);
let case = map(
rule! {
CASE ~ #subexpr(0)?
~ ( WHEN ~ ^#subexpr(0) ~ ^THEN ~ ^#subexpr(0) )+
~ ( ELSE ~ ^#subexpr(0) )? ~ ^END
},
|(_, operand, branches, else_result, _)| {
let (conditions, results) = branches
.into_iter()
.map(|(_, cond, _, result)| (cond, result))
.unzip();
let else_result = else_result.map(|(_, result)| result);
ExprElement::Case {
operand: operand.map(Box::new),
conditions,
results,
else_result: else_result.map(Box::new),
}
},
);
let exists = map(
rule! { NOT? ~ EXISTS ~ "(" ~ ^#query ~ ^")" },
|(opt_not, _, _, subquery, _)| ExprElement::Exists {
subquery,
not: opt_not.is_some(),
},
);
let subquery = map(
rule! {
(ANY | SOME | ALL)? ~
"("
~ #query
~ ^")"
},
|(modifier, _, subquery, _)| {
let modifier = modifier.map(|m| match m.kind {
TokenKind::ALL => SubqueryModifier::All,
TokenKind::ANY => SubqueryModifier::Any,
TokenKind::SOME => SubqueryModifier::Some,
_ => unreachable!(),
});
ExprElement::Subquery { modifier, subquery }
},
);
let binary_op = map(binary_op, |op| ExprElement::BinaryOp { op });
let unary_op = map(unary_op, |op| ExprElement::UnaryOp { op });
let map_access = map(map_access, |accessor| ExprElement::MapAccess { accessor });
// Floating point literal with leading dot will be parsed as a period map access,
// and then will be converted back to a floating point literal if the map access
// is not following a primary element nor a postfix element.
let literal = map(literal, |lit| ExprElement::Literal { lit });
let array = map(
// Array that contains a single literal item will be parsed as a bracket map access,
// and then will be converted back to an array if the map access is not following
// a primary element nor a postfix element.
rule! {
"[" ~ #comma_separated_list0_ignore_trailing(subexpr(0))? ~ ","? ~ ^"]"
},
|(_, opt_args, _, _)| {
let exprs = opt_args.unwrap_or_default();
ExprElement::Array { exprs }
},
);
// ARRAY_SORT([...], ASC | DESC, NULLS FIRST | LAST)
let array_sort = map(
rule! {
( ARRAY_SORT )
~ "("
~ #subexpr(0)
~ ( "," ~ #literal_string )?
~ ( "," ~ #literal_string )?
~ ")"
},
|(_, _, expr, opt_asc, opt_null_first, _)| ExprElement::ArraySort {
expr: Box::new(expr),
asc: opt_asc.map(|(_, asc)| asc),
nulls_first: opt_null_first.map(|(_, first_last)| first_last),
},
);
let map_expr = map(
rule! { "{" ~ #comma_separated_list0(map_element) ~ "}" },
|(_, kvs, _)| ExprElement::Map { kvs },
);
let date_add = map(
rule! {
DATE_ADD ~ "(" ~ #interval_kind ~ "," ~ #subexpr(0) ~ "," ~ #subexpr(0) ~ ")"
},
|(_, _, unit, _, interval, _, date, _)| ExprElement::DateAdd {
unit,
interval,
date,
},
);
let date_sub = map(
rule! {
DATE_SUB ~ "(" ~ #interval_kind ~ "," ~ #subexpr(0) ~ "," ~ #subexpr(0) ~ ")"
},
|(_, _, unit, _, interval, _, date, _)| ExprElement::DateSub {
unit,
interval,
date,
},
);
let interval = map(
rule! {
INTERVAL ~ #subexpr(0) ~ #interval_kind
},
|(_, operand, unit)| ExprElement::Interval {
expr: operand,
unit,
},
);
let date_trunc = map(
rule! {
DATE_TRUNC ~ "(" ~ #interval_kind ~ "," ~ #subexpr(0) ~ ")"
},
|(_, _, unit, _, date, _)| ExprElement::DateTrunc { unit, date },
);
let date_expr = map(
rule! {
DATE ~ #consumed(literal_string)
},
|(_, (span, date))| ExprElement::Cast {
expr: Box::new(Expr::Literal {
span: transform_span(span.0),
lit: Literal::String(date),
}),
target_type: TypeName::Date,
},
);
let timestamp_expr = map(
rule! {
TIMESTAMP ~ #consumed(literal_string)
},
|(_, (span, date))| ExprElement::Cast {
expr: Box::new(Expr::Literal {
span: transform_span(span.0),
lit: Literal::String(date),
}),
target_type: TypeName::Timestamp,
},
);
let is_distinct_from = map(
rule! {
IS ~ NOT? ~ DISTINCT ~ FROM
},
|(_, not, _, _)| ExprElement::IsDistinctFrom { not: not.is_some() },
);
let (rest, (span, elem)) = consumed(alt((
// Note: each `alt` call supports maximum of 21 parsers
rule!(
#is_null : "`... IS [NOT] NULL`"
| #in_list : "`[NOT] IN (<expr>, ...)`"
| #in_subquery : "`[NOT] IN (SELECT ...)`"
| #exists : "`[NOT] EXISTS (SELECT ...)`"
| #between : "`[NOT] BETWEEN ... AND ...`"
| #binary_op : "<operator>"
| #unary_op : "<operator>"
| #cast : "`CAST(... AS ...)`"
| #date_add: "`DATE_ADD(..., ..., (YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | SECOND | DOY | DOW))`"
| #date_sub: "`DATE_SUB(..., ..., (YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | SECOND | DOY | DOW))`"
| #date_trunc: "`DATE_TRUNC((YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | SECOND), ...)`"
| #date_expr: "`DATE <str_literal>`"
| #timestamp_expr: "`TIMESTAMP <str_literal>`"
| #interval: "`INTERVAL ... (YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | SECOND | DOY | DOW)`"
| #pg_cast : "`::<type_name>`"
| #extract : "`EXTRACT((YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | SECOND) FROM ...)`"
),
rule!(
#position : "`POSITION(... IN ...)`"
| #substring : "`SUBSTRING(... [FROM ...] [FOR ...])`"
| #array_sort : "`ARRAY_SORT([...], 'ASC' | 'DESC', 'NULLS FIRST' | 'NULLS LAST')`"
| #trim : "`TRIM(...)`"
| #trim_from : "`TRIM([(BOTH | LEADEING | TRAILING) ... FROM ...)`"
| #is_distinct_from: "`... IS [NOT] DISTINCT FROM ...`"
| #count_all : "COUNT(*)"
| #function_call_with_window : "<function>"
| #function_call_with_params : "<function>"
| #function_call : "<function>"
| #case : "`CASE ... END`"
| #subquery : "`(SELECT ...)`"
| #tuple : "`(<expr> [, ...])`"
| #column_ref : "<column>"
| #map_access : "[<key>] | .<key> | :<key>"
| #literal : "<literal>"
| #array : "`[...]`"
| #map_expr : "`{...}`"
),
)))(i)?;
Ok((rest, WithSpan { span, elem }))
}
pub fn window_frame_bound(i: Input) -> IResult<WindowFrameBound> {
alt((
value(WindowFrameBound::CurrentRow, rule! { CURRENT ~ ROW }),
map(rule! { #subexpr(0) ~ PRECEDING }, |(expr, _)| {
WindowFrameBound::Preceding(Some(Box::new(expr)))
}),
value(
WindowFrameBound::Preceding(None),
rule! { UNBOUNDED ~ PRECEDING },
),
map(rule! { #subexpr(0) ~ FOLLOWING }, |(expr, _)| {
WindowFrameBound::Following(Some(Box::new(expr)))
}),
value(
WindowFrameBound::Following(None),
rule! { UNBOUNDED ~ FOLLOWING },
),
))(i)
}
pub fn unary_op(i: Input) -> IResult<UnaryOperator> {
// Plus and Minus are parsed as binary op at first.
alt((
value(UnaryOperator::Not, rule! { NOT }),
value(UnaryOperator::Factorial, rule! { Factorial}),
value(UnaryOperator::SquareRoot, rule! { SquareRoot}),
value(UnaryOperator::BitwiseNot, rule! {BitWiseNot}),
value(UnaryOperator::CubeRoot, rule! { CubeRoot}),
value(UnaryOperator::Abs, rule! { Abs}),
))(i)
}
pub fn binary_op(i: Input) -> IResult<BinaryOperator> {
alt((
alt((
value(BinaryOperator::Plus, rule! { "+" }),
value(BinaryOperator::Minus, rule! { "-" }),
value(BinaryOperator::Multiply, rule! { "*" }),
value(BinaryOperator::Divide, rule! { "/" }),
value(BinaryOperator::Div, rule! { DIV }),
value(BinaryOperator::Modulo, rule! { "%" }),
value(BinaryOperator::StringConcat, rule! { "||" }),
value(BinaryOperator::Gt, rule! { ">" }),
value(BinaryOperator::Lt, rule! { "<" }),
value(BinaryOperator::Gte, rule! { ">=" }),
value(BinaryOperator::Lte, rule! { "<=" }),
value(BinaryOperator::Eq, rule! { "=" }),
value(BinaryOperator::NotEq, rule! { "<>" | "!=" }),
value(BinaryOperator::Caret, rule! { "^" }),
)),
alt((
value(BinaryOperator::And, rule! { AND }),
value(BinaryOperator::Or, rule! { OR }),
value(BinaryOperator::Xor, rule! { XOR }),
value(BinaryOperator::Like, rule! { LIKE }),
value(BinaryOperator::NotLike, rule! { NOT ~ LIKE }),
value(BinaryOperator::Regexp, rule! { REGEXP }),
value(BinaryOperator::NotRegexp, rule! { NOT ~ REGEXP }),
value(BinaryOperator::RLike, rule! { RLIKE }),
value(BinaryOperator::NotRLike, rule! { NOT ~ RLIKE }),
value(BinaryOperator::BitwiseOr, rule! { BitWiseOr }),
value(BinaryOperator::BitwiseAnd, rule! { BitWiseAnd }),
value(BinaryOperator::BitwiseXor, rule! { BitWiseXor }),
value(BinaryOperator::BitwiseShiftLeft, rule! { ShiftLeft }),
value(BinaryOperator::BitwiseShiftRight, rule! { ShiftRight }),
)),
))(i)
}
pub fn literal(i: Input) -> IResult<Literal> {
let string = map(literal_string, Literal::String);
let boolean = alt((
value(Literal::Boolean(true), rule! { TRUE }),
value(Literal::Boolean(false), rule! { FALSE }),
));
let current_timestamp = value(Literal::CurrentTimestamp, rule! { CURRENT_TIMESTAMP });
let null = value(Literal::Null, rule! { NULL });
rule!(
#string
| #literal_decimal
| #literal_hex
| #boolean
| #current_timestamp
| #null
)(i)
}
pub fn literal_hex_str(i: Input) -> IResult<&str> {
// 0XFFFF
let mysql_hex = map(
rule! {
MySQLLiteralHex
},
|token| &token.text()[2..],
);
// x'FFFF'
let pg_hex = map(
rule! {
PGLiteralHex
},
|token| &token.text()[2..token.text().len() - 1],
);
rule!(
#mysql_hex
| #pg_hex
)(i)
}
#[allow(clippy::from_str_radix_10)]
pub fn literal_u64(i: Input) -> IResult<u64> {
let decimal = map_res(
rule! {
LiteralInteger
},
|token| Ok(u64::from_str_radix(token.text(), 10)?),
);
let hex = map_res(literal_hex_str, |lit| Ok(u64::from_str_radix(lit, 16)?));
rule!(
#decimal
| #hex
)(i)
}
pub fn literal_f64(i: Input) -> IResult<f64> {
map_res(
rule! {
LiteralFloat
},
|token| Ok(fast_float::parse(token.text())?),
)(i)
}
pub fn literal_decimal(i: Input) -> IResult<Literal> {
let decimal_unit = map_res(
rule! {
LiteralInteger
},
|token| Literal::parse_decimal_uint(token.text()),
);
let decimal = map_res(
rule! {
LiteralFloat
},
|token| Literal::parse_decimal(token.text()),
);
rule!(
#decimal_unit
| #decimal
)(i)
}
pub fn literal_hex(i: Input) -> IResult<Literal> {
let hex_u64 = map_res(literal_hex_str, |lit| {
Ok(Literal::UInt64(u64::from_str_radix(lit, 16)?))
});
// todo(youngsofun): more accurate precision
let hex_u128 = map_res(literal_hex_str, |lit| {
Ok(Literal::Decimal128 {
value: i128::from_str_radix(lit, 16)?,
precision: 38,
scale: 0,
})
});
rule!(
#hex_u64
| #hex_u128
)(i)
}
pub fn literal_bool(i: Input) -> IResult<bool> {
alt((value(true, rule! { TRUE }), value(false, rule! { FALSE })))(i)
}
pub fn literal_string(i: Input) -> IResult<String> {
map_res(
rule! {
QuotedString
},
|token| {
if token
.text()
.chars()
.next()
.filter(|c| i.1.is_string_quote(*c))
.is_some()
{
let str = &token.text()[1..token.text().len() - 1];
let unescaped =
unescape(str, '\'').ok_or(ErrorKind::Other("invalid escape or unicode"))?;
Ok(unescaped)
} else {
Err(ErrorKind::ExpectToken(QuotedString))
}
},
)(i)
}
pub fn literal_string_eq_ignore_case(s: &str) -> impl FnMut(Input) -> IResult<()> + '_ {
move |i| {
map_res(rule! { QuotedString }, |token| {
if token.text()[1..token.text().len() - 1].eq_ignore_ascii_case(s) {
Ok(())
} else {
Err(ErrorKind::ExpectToken(QuotedString))
}
})(i)
}
}
pub fn at_string(i: Input) -> IResult<String> {
match_token(AtString)(i)
.map(|(i2, token)| (i2, token.text()[1..token.text().len()].to_string()))
}
pub fn type_name(i: Input) -> IResult<TypeName> {
let ty_boolean = value(TypeName::Boolean, rule! { BOOLEAN | BOOL });
let ty_uint8 = value(
TypeName::UInt8,
rule! { ( UINT8 | #map(rule! { TINYINT ~ UNSIGNED }, |(t, _)| t) ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_uint16 = value(
TypeName::UInt16,
rule! { ( UINT16 | #map(rule! { SMALLINT ~ UNSIGNED }, |(t, _)| t) ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_uint32 = value(
TypeName::UInt32,
rule! { ( UINT32 | #map(rule! { ( INT | INTEGER ) ~ UNSIGNED }, |(t, _)| t) ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_uint64 = value(
TypeName::UInt64,
rule! { ( UINT64 | UNSIGNED | #map(rule! { BIGINT ~ UNSIGNED }, |(t, _)| t) ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_int8 = value(
TypeName::Int8,
rule! { ( INT8 | TINYINT ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_int16 = value(
TypeName::Int16,
rule! { ( INT16 | SMALLINT ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_int32 = value(
TypeName::Int32,
rule! { ( INT32 | INT | INTEGER ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_int64 = value(
TypeName::Int64,
rule! { ( INT64 | SIGNED | BIGINT ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_float32 = value(TypeName::Float32, rule! { FLOAT32 | FLOAT });
let ty_float64 = value(
TypeName::Float64,
rule! { (FLOAT64 | DOUBLE) ~ ( PRECISION )? },
);
let ty_decimal = map_res(
rule! { DECIMAL ~ "(" ~ #literal_u64 ~ "," ~ #literal_u64 ~ ")" },
|(_, _, precision, _, scale, _)| {
Ok(TypeName::Decimal {
precision: precision
.try_into()
.map_err(|_| ErrorKind::Other("precision is too large"))?,
scale: scale
.try_into()
.map_err(|_| ErrorKind::Other("scale is too large"))?,
})
},
);
let ty_array = map(
rule! { ARRAY ~ "(" ~ #type_name ~ ")" },
|(_, _, item_type, _)| TypeName::Array(Box::new(item_type)),
);
let ty_map = map(
rule! { MAP ~ "(" ~ #type_name ~ "," ~ #type_name ~ ")" },
|(_, _, key_type, _, val_type, _)| TypeName::Map {
key_type: Box::new(key_type),
val_type: Box::new(val_type),
},
);
let ty_nullable = map(
rule! { NULLABLE ~ ( "(" ~ #type_name ~ ")" ) },
|(_, item_type)| TypeName::Nullable(Box::new(item_type.1)),
);
let ty_tuple = map(
rule! { TUPLE ~ "(" ~ #comma_separated_list1(type_name) ~ ")" },
|(_, _, fields_type, _)| TypeName::Tuple {
fields_name: None,
fields_type,
},
);
let ty_named_tuple = map(
rule! { TUPLE ~ "(" ~ #comma_separated_list1(rule! { #ident ~ #type_name }) ~ ")" },
|(_, _, fields, _)| {
let (fields_name, fields_type) =
fields.into_iter().map(|(name, ty)| (name.name, ty)).unzip();
TypeName::Tuple {
fields_name: Some(fields_name),
fields_type,
}
},
);
let ty_date = value(TypeName::Date, rule! { DATE });
let ty_datetime = map(
rule! { (DATETIME | TIMESTAMP) ~ ( "(" ~ #literal_u64 ~ ")" )? },
|(_, _)| TypeName::Timestamp,
);
let ty_string = value(
TypeName::String,
rule! { ( STRING | VARCHAR | CHAR | CHARACTER | TEXT ) ~ ( "(" ~ #literal_u64 ~ ")" )? },
);
let ty_variant = value(TypeName::Variant, rule! { VARIANT | JSON });
map(
rule! {
( #ty_boolean
| #ty_uint8
| #ty_uint16
| #ty_uint32
| #ty_uint64
| #ty_int8
| #ty_int16
| #ty_int32
| #ty_int64
| #ty_float32
| #ty_float64
| #ty_decimal
| #ty_array
| #ty_map
| #ty_tuple : "TUPLE(<type>, ...)"
| #ty_named_tuple : "TUPLE(<name> <type>, ...)"
| #ty_date
| #ty_datetime
| #ty_string
| #ty_variant
| #ty_nullable
) ~ NULL? : "type name"
},
|(ty, null_opt)| {
if null_opt.is_some() && !matches!(ty, TypeName::Nullable(_)) {
TypeName::Nullable(Box::new(ty))
} else {
ty
}
},
)(i)
}
pub fn interval_kind(i: Input) -> IResult<IntervalKind> {
alt((
value(IntervalKind::Year, rule! { YEAR }),
value(IntervalKind::Quarter, rule! { QUARTER }),
value(IntervalKind::Month, rule! { MONTH }),
value(IntervalKind::Day, rule! { DAY }),
value(IntervalKind::Hour, rule! { HOUR }),
value(IntervalKind::Minute, rule! { MINUTE }),
value(IntervalKind::Second, rule! { SECOND }),
value(IntervalKind::Doy, rule! { DOY }),
value(IntervalKind::Dow, rule! { DOW }),
value(
IntervalKind::Year,
rule! { #literal_string_eq_ignore_case("YEAR") },
),
value(
IntervalKind::Quarter,
rule! { #literal_string_eq_ignore_case("QUARTER") },
),
value(
IntervalKind::Month,
rule! { #literal_string_eq_ignore_case("MONTH") },
),
value(
IntervalKind::Day,
rule! { #literal_string_eq_ignore_case("DAY") },
),
value(
IntervalKind::Hour,
rule! { #literal_string_eq_ignore_case("HOUR") },
),
value(
IntervalKind::Minute,
rule! { #literal_string_eq_ignore_case("MINUTE") },
),
value(
IntervalKind::Second,
rule! { #literal_string_eq_ignore_case("SECOND") },
),
value(
IntervalKind::Doy,
rule! { #literal_string_eq_ignore_case("DOY") },
),
value(
IntervalKind::Dow,
rule! { #literal_string_eq_ignore_case("DOW") },
),
))(i)
}
pub fn map_access(i: Input) -> IResult<MapAccessor> {
let bracket = map(
rule! {
"[" ~ #subexpr(0) ~ "]"
},
|(_, key, _)| MapAccessor::Bracket { key: Box::new(key) },
);
let period = map(
rule! {
"." ~ #ident
},
|(_, key)| MapAccessor::Period { key },
);
let period_number = map_res(
rule! {
LiteralFloat
},
|key| {
if key.text().starts_with('.') {
if let Ok(key) = (key.text()[1..]).parse::<u64>() {
return Ok(MapAccessor::PeriodNumber { key });
}
}
Err(ErrorKind::ExpectText("."))
},
);
let colon = map(
rule! {
":" ~ #ident
},
|(_, key)| MapAccessor::Colon { key },
);
rule!(
#bracket
| #period
| #period_number
| #colon
)(i)
}
pub fn map_element(i: Input) -> IResult<(Expr, Expr)> {
map(
rule! {
#subexpr(0) ~ ":" ~ #subexpr(0)
},
|(key, _, value)| (key, value),
)(i)
}
|
//------------------------------------------------
// command line syntax:
// dnaabox -flag < data_file_test_path
/*
possible flags are:
-pc => pattern_count() ......CHALLENGE 1A
-fw => most_frequent_words() ......CHALLENGE 1B
-rc => reverse_complement() ......CHALLENGE 1C
-pm => pattern_matching() ......CHALLENGE 1D
-clf => clump_finding() ......CHALLENGE 1E
-ms => minimum_skew() ......CHALLENGE 1F
-hd => hamming_distance() ......CHALLENGE 1G
-apm => approx_pattern_matching() ......CHALLENGE 1H
-fm => freq_word_miss() ......CHALLENGE 1I
-fmr => freq_word_miss_rev() ......CHALLENGE 1J
-cf => computing_frequences() ......CHALLENGE 1K
-ptn => pattern_to_number() ......CHALLENGE 1L
-ntp => number_to_pattern() ......CHALLENGE 1M
-n => neighbors() ......CHALLENGE 1N
*/
//------------------------------------------------
mod dnabox;
use std::env;
fn main(){
let args: Vec<String> = env::args().collect();
if args.len() == 1 || args.len() > 2 {
println!("this version requires exactly one command line argument.");
return;
}
match &args[1] as &str {
"-pc" => dnabox::pattern_count(),
"-ptn" => dnabox::pattern_to_number(),
"-ntp" => dnabox::number_to_pattern(),
"-fw" => dnabox::most_frequent_words(),
"-fwm" => dnabox::freq_word_miss(),
"-fm" => dnabox::freq_word_miss(),
"-fmr" => dnabox::freq_word_miss_rev(),
"-rc" => dnabox::reverse_complement(),
"-pm" => dnabox::pattern_matching(),
"-apm" => dnabox::approx_pattern_matching(),
"-clf" => dnabox::clump_finding(),
"-ms" => dnabox::minimum_skew(),
"-hd" => dnabox::hamming_distance(),
"-cf" => dnabox::computing_frequences(),
"-n" => dnabox::neighbors(),
&_ => println!("command {} not recognized.",&args[1])
}
} |
use async_channel::Sender;
use std::collections::HashMap;
use std::io::Result;
use std::net::SocketAddr;
use tdn_types::group::{GroupId, Peer};
use tdn_types::message::{GroupSendMessage, SendMessage};
use tdn_types::primitive::PeerAddr;
#[derive(Default, Debug)]
pub struct CAPermissionedGroup<P: Peer> {
id: GroupId,
my_pk: P::PublicKey,
my_prove: P::Signature,
ca: P::PublicKey,
peers: HashMap<PeerAddr, (P::PublicKey, P::Signature, SocketAddr)>,
peers_name: HashMap<P::PublicKey, PeerAddr>, // Peer Symbol Name
}
impl<P: Peer> CAPermissionedGroup<P> {
pub fn new(id: GroupId, my_pk: P::PublicKey, my_prove: P::Signature, ca: P::PublicKey) -> Self {
Self {
id,
my_pk: my_pk,
my_prove: my_prove,
ca: ca,
peers: HashMap::new(),
peers_name: HashMap::new(),
}
}
pub fn peers(&self) -> Vec<&PeerAddr> {
self.peers.keys().collect()
}
pub fn get_peer_addr(&self, name: &P::PublicKey) -> Option<&PeerAddr> {
self.peers_name.get(name)
}
/// directly add a peer to group.
pub fn add(
&mut self,
peer_addr: PeerAddr,
pk: P::PublicKey,
sign: P::Signature,
addr: SocketAddr,
) {
self.peers.insert(peer_addr, (pk, sign, addr));
}
pub fn join_bytes(&self) -> Vec<u8> {
postcard::to_allocvec(&(&self.my_pk, &self.my_prove)).unwrap_or(vec![])
}
pub fn sign_prove(sk: &P::SecretKey, pk: &P::PublicKey) -> Result<P::Signature> {
let pk_bytes = postcard::to_allocvec(pk).unwrap_or(vec![]);
P::sign(sk, &pk_bytes)
}
/// join: when peer join will call
pub async fn join(
&mut self,
peer_addr: PeerAddr,
addr: SocketAddr,
join_bytes: Vec<u8>,
return_sender: Sender<SendMessage>,
) {
let is_ok = self.peers.contains_key(&peer_addr);
if is_ok {
return_sender
.send(SendMessage::Group(GroupSendMessage::StableResult(
peer_addr,
true,
false,
self.join_bytes(),
)))
.await
.expect("CAPermissionedGroup to TDN channel closed");
}
let join_data = postcard::from_bytes::<(P::PublicKey, P::Signature)>(&join_bytes);
if join_data.is_err() {
return return_sender
.send(SendMessage::Group(GroupSendMessage::StableResult(
peer_addr,
false,
true,
vec![2],
)))
.await
.expect("CAPermissionedGroup to TDN channel closed");
}
let (pk, sign) = join_data.unwrap();
let pk_bytes = postcard::to_allocvec(&pk).unwrap_or(vec![]);
if P::verify(&self.ca, &pk_bytes, &sign) {
return_sender
.send(SendMessage::Group(GroupSendMessage::StableResult(
peer_addr,
true,
false,
self.join_bytes(),
)))
.await
.expect("CAPermissionedGroup to TDN channel closed");
self.peers.insert(peer_addr, (pk.clone(), sign, addr));
self.peers_name.insert(pk, peer_addr);
} else {
return_sender
.send(SendMessage::Group(GroupSendMessage::StableResult(
peer_addr,
false,
true,
vec![3],
)))
.await
.expect("CAPermissionedGroup to TDN channel closed");
}
}
pub fn join_result(&mut self, peer_addr: PeerAddr, is_ok: bool, _join_result: Vec<u8>) {
if !is_ok {
self.peers.remove(&peer_addr);
}
}
/// leave: when peer leave will call
pub fn leave(&mut self, peer_addr: &PeerAddr) {
self.peers.remove(&peer_addr);
let mut delete_name = vec![];
for (name, addr) in self.peers_name.iter() {
if addr == peer_addr {
delete_name.push(name.clone());
}
}
for name in delete_name {
self.peers_name.remove(&name);
}
}
}
|
mod anti_replay;
mod constants;
mod device;
mod inbound;
mod ip;
mod messages;
mod outbound;
mod peer;
mod pool;
mod route;
mod runq;
mod types;
#[cfg(test)]
mod tests;
use messages::TransportHeader;
use std::mem;
use super::constants::REJECT_AFTER_MESSAGES;
use super::queue::ParallelQueue;
use super::types::*;
use super::{tun, udp, Endpoint};
pub const SIZE_TAG: usize = 16;
pub const SIZE_MESSAGE_PREFIX: usize = mem::size_of::<TransportHeader>();
pub const CAPACITY_MESSAGE_POSTFIX: usize = SIZE_TAG;
pub const fn message_data_len(payload: usize) -> usize {
payload + mem::size_of::<TransportHeader>() + SIZE_TAG
}
pub use device::DeviceHandle as Device;
pub use messages::TYPE_TRANSPORT;
pub use peer::PeerHandle;
pub use types::Callbacks;
|
use conrod;
use conrod::Color;
use conrod::render::Text;
use conrod::text::rt;
use conrod::text;
use gfx;
use gfx::texture;
use gfx::traits::FactoryExt;
pub type ColorFormat = gfx::format::Srgba8;
type SurfaceFormat = gfx::format::R8_G8_B8_A8;
type FullFormat = (SurfaceFormat, gfx::format::Unorm);
const FRAGMENT_SHADER: &'static [u8] = b"
#version 140
uniform sampler2D t_Color;
in vec2 v_Uv;
in vec4 v_Color;
out vec4 f_Color;
void main() {
vec4 tex = texture(t_Color, v_Uv);
f_Color = vec4(v_Color.rgb, tex.a);
}
";
const VERTEX_SHADER: &'static [u8] = b"
#version 140
in vec2 a_Pos;
in vec2 a_Uv;
in vec4 a_Color;
out vec2 v_Uv;
out vec4 v_Color;
void main() {
v_Uv = a_Uv;
v_Color = a_Color;
gl_Position = vec4(a_Pos, 0.0, 1.0);
}
";
gfx_defines! {
vertex TextVertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
color: [f32; 4] = "a_Color",
}
pipeline pipe {
vbuf: gfx::VertexBuffer<TextVertex> = (),
color: gfx::TextureSampler<[f32; 4]> = "t_Color",
out: gfx::BlendTarget<ColorFormat> = ("f_Color", ::gfx::state::MASK_ALL, ::gfx::preset::blend::ALPHA),
}
}
impl TextVertex {
fn new(pos: [f32; 2], uv: [f32; 2], color: [f32; 4]) -> TextVertex {
TextVertex {
pos: pos,
uv: uv,
color: color,
}
}
}
fn create_texture<F, R>
(factory: &mut F,
width: u32,
height: u32,
data: &[u8])
-> (gfx::handle::Texture<R, SurfaceFormat>, gfx::handle::ShaderResourceView<R, [f32; 4]>)
where R: gfx::Resources,
F: gfx::Factory<R>
{
fn create_texture<T, F, R>(factory: &mut F,
kind: gfx::texture::Kind,
data: &[&[u8]])
-> Result<(gfx::handle::Texture<R, T::Surface>,
gfx::handle::ShaderResourceView<R, T::View>),
gfx::CombinedError>
where F: gfx::Factory<R>,
R: gfx::Resources,
T: gfx::format::TextureFormat
{
use gfx::{format, texture};
use gfx::memory::{Usage, SHADER_RESOURCE};
use gfx_core::memory::Typed;
let surface = <T::Surface as format::SurfaceTyped>::get_surface_type();
let num_slices = kind.get_num_slices().unwrap_or(1) as usize;
let num_faces = if kind.is_cube() { 6 } else { 1 };
let desc = texture::Info {
kind: kind,
levels: (data.len() / (num_slices * num_faces)) as texture::Level,
format: surface,
bind: SHADER_RESOURCE,
usage: Usage::Dynamic,
};
let cty = <T::Channel as format::ChannelTyped>::get_channel_type();
let raw = try!(factory.create_texture_raw(desc, Some(cty), Some(data)));
let levels = (0, raw.get_info().levels - 1);
let tex = Typed::new(raw);
let view = try!(factory.view_texture_as_shader_resource::<T>(
&tex, levels, format::Swizzle::new()
));
Ok((tex, view))
}
let kind = texture::Kind::D2(width as texture::Size,
height as texture::Size,
texture::AaMode::Single);
create_texture::<ColorFormat, F, R>(factory, kind, &[data]).unwrap()
}
fn update_texture<R, C>(encoder: &mut gfx::Encoder<R, C>,
texture: &gfx::handle::Texture<R, SurfaceFormat>,
offset: [u16; 2],
size: [u16; 2],
data: &[[u8; 4]])
where R: gfx::Resources,
C: gfx::CommandBuffer<R>
{
let info = texture::ImageInfoCommon {
xoffset: offset[0],
yoffset: offset[1],
zoffset: 0,
width: size[0],
height: size[1],
depth: 0,
format: (),
mipmap: 0,
};
encoder.update_texture::<SurfaceFormat, FullFormat>(texture, None, info, data).unwrap();
}
fn gamma_srgb_to_linear(c: [f32; 4]) -> [f32; 4] {
fn component(f: f32) -> f32 {
// Taken from https://github.com/PistonDevelopers/graphics/src/color.rs#L42
if f <= 0.04045 {
f / 12.92
} else {
((f + 0.055) / 1.055).powf(2.4)
}
}
[component(c[0]), component(c[1]), component(c[2]), c[3]]
}
pub struct TextRenderer<R: gfx::Resources> {
pso: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
glyph_cache: conrod::text::GlyphCache,
texture: gfx::handle::Texture<R, SurfaceFormat>,
texture_view: gfx::handle::ShaderResourceView<R, [f32; 4]>,
vertices: Vec<TextVertex>,
dpi: f32,
screen_width: f32,
screen_height: f32,
}
impl<R: gfx::Resources> TextRenderer<R> {
pub fn new<F: gfx::Factory<R>>(window_width: f32,
window_height: f32,
dpi: f32,
main_color: gfx::handle::RenderTargetView<R, ColorFormat>,
factory: &mut F)
-> Self {
// Create texture sampler
let sampler_info = texture::SamplerInfo::new(texture::FilterMethod::Bilinear,
texture::WrapMode::Clamp);
let sampler = factory.create_sampler(sampler_info);
// Dummy values for initialization
let vbuf = factory.create_vertex_buffer(&[]);
let (_, fake_texture) = create_texture(factory, 2, 2, &[0; 4]);
let data = pipe::Data {
vbuf: vbuf,
color: (fake_texture.clone(), sampler),
out: main_color.clone(),
};
// Compile GL program
let pso = factory.create_pipeline_simple(VERTEX_SHADER, FRAGMENT_SHADER, pipe::new())
.unwrap();
// Create glyph cache and its texture
let (glyph_cache, cache_tex, cache_tex_view) = {
let width = (window_width * dpi) as u32;
let height = (window_height * dpi) as u32;
const SCALE_TOLERANCE: f32 = 0.1;
const POSITION_TOLERANCE: f32 = 0.1;
let cache =
conrod::text::GlyphCache::new(width, height, SCALE_TOLERANCE, POSITION_TOLERANCE);
let data = vec![0; (width * height * 4) as usize];
let (texture, texture_view) = create_texture(factory, width, height, &data);
(cache, texture, texture_view)
};
TextRenderer {
pso: pso,
data: data,
glyph_cache: glyph_cache,
texture: cache_tex,
texture_view: cache_tex_view,
vertices: Vec::new(),
dpi: dpi,
screen_width: window_width,
screen_height: window_height,
}
}
pub fn prepare_frame(&mut self, dpi: f32, screen_width: f32, screen_height: f32) {
self.vertices = Vec::new();
self.dpi = dpi;
self.screen_height = screen_height * dpi;
self.screen_width = screen_width * dpi;
}
pub fn add_text<C: gfx::CommandBuffer<R>>(&mut self,
color: Color,
text: Text,
font_id: text::font::Id,
encoder: &mut gfx::Encoder<R, C>) {
let positioned_glyphs = text.positioned_glyphs(self.dpi);
// Queue the glyphs to be cached
for glyph in positioned_glyphs {
self.glyph_cache.queue_glyph(font_id.index(), glyph.clone());
}
let texture = &self.texture;
self.glyph_cache
.cache_queued(|rect, data| {
let offset = [rect.min.x as u16, rect.min.y as u16];
let size = [rect.width() as u16, rect.height() as u16];
let new_data = data.iter().map(|x| [0, 0, 0, *x]).collect::<Vec<_>>();
update_texture(encoder, texture, offset, size, &new_data);
})
.unwrap();
let color = gamma_srgb_to_linear(color.to_fsa());
let cache_id = font_id.index();
let origin = rt::point(0.0, 0.0);
let sw = self.screen_width;
let sh = self.screen_height;
// A closure to convert RustType rects to GL rects
let to_gl_rect = |screen_rect: rt::Rect<i32>| {
rt::Rect {
min: origin +
(rt::vector(screen_rect.min.x as f32 / sw - 0.5,
1.0 - screen_rect.min.y as f32 / sh - 0.5)) *
2.0,
max: origin +
(rt::vector(screen_rect.max.x as f32 / sw - 0.5,
1.0 - screen_rect.max.y as f32 / sh - 0.5)) *
2.0,
}
};
let ref gc = self.glyph_cache;
// Create new vertices
let extension = positioned_glyphs.into_iter()
.filter_map(|g| gc.rect_for(cache_id, g).ok().unwrap_or(None))
.flat_map(|(uv_rect, screen_rect)| {
use std::iter::once;
let gl_rect = to_gl_rect(screen_rect);
let v = |pos, uv| once(TextVertex::new(pos, uv, color));
v([gl_rect.min.x, gl_rect.max.y],
[uv_rect.min.x, uv_rect.max.y])
.chain(v([gl_rect.min.x, gl_rect.min.y],
[uv_rect.min.x, uv_rect.min.y]))
.chain(v([gl_rect.max.x, gl_rect.min.y],
[uv_rect.max.x, uv_rect.min.y]))
.chain(v([gl_rect.max.x, gl_rect.min.y],
[uv_rect.max.x, uv_rect.min.y]))
.chain(v([gl_rect.max.x, gl_rect.max.y],
[uv_rect.max.x, uv_rect.max.y]))
.chain(v([gl_rect.min.x, gl_rect.max.y],
[uv_rect.min.x, uv_rect.max.y]))
});
self.vertices.extend(extension);
}
pub fn render<C: gfx::CommandBuffer<R>, F: gfx::Factory<R>>(&mut self,
encoder: &mut gfx::Encoder<R, C>,
factory: &mut F) {
self.data.color.0 = self.texture_view.clone();
let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&self.vertices, ());
self.data.vbuf = vbuf;
encoder.draw(&slice, &self.pso, &self.data);
}
}
|
use yew::prelude::*;
use yew_router::components::RouterAnchor;
use crate::app::AppRoute;
use super::tab_setting::TabSettings;
use super::tab_permission::TabPermissions;
use super::tab_users::TabUsers;
pub enum Content{
Settings,
Permissions,
Users
}
pub struct ViewDetail {
content: Content,
link: ComponentLink<Self>
}
pub enum Msg {
ChangeContent(Content)
}
impl Component for ViewDetail {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
ViewDetail {
content: Content::Settings,
link
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeContent(content) => {
self.content = content;
true
}
}
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
type Anchor = RouterAnchor<AppRoute>;
html! {
<>
<div class="mx-auto pt-5 pb-5 px-4" style="max-width: 1048px;">
<div>
<Anchor route=AppRoute::RolesCreated classes="text-decoration-none text-muted">
<i class="bi bi-arrow-left"></i>
<span>{"Back To Roles"}</span>
</Anchor>
</div>
<div class="mt-2">
<p class="fw-bold fs-2">{"Brother Yeska"}</p>
<div class="pt-2">
<span class="text-muted">{"Role ID"}</span>
<code class="text-dark ms-2" style="background-color: #eff0f2; font-family: Roboto, sans-serif;">{"rol_Vbah0QfGcsV9Y28d"}</code>
</div>
</div>
<div class="mt-4">
<ul class="nav nav-tabs">
<li onclick=self.link.callback(|_|Msg::ChangeContent(Content::Settings)) class="nav-item">
<a class={
match self.content {
Content::Settings => "nav-link active",
_ => "nav-link"
}
}
aria-current="page"
href="#">{"Settings"}</a>
</li>
<li onclick=self.link.callback(|_|Msg::ChangeContent(Content::Permissions)) class="nav-item">
<a class={
match self.content{
Content::Permissions => "nav-link active",
_ => "nav-link"
}
}
href="#">{"Permissions"}</a>
</li>
<li onclick=self.link.callback(|_|Msg::ChangeContent(Content::Users)) class="nav-item">
<a class={
match self.content{
Content::Users => "nav-link active",
_ => "nav-link"
}
} href="#">{"Users"}</a>
</li>
</ul>
</div>
{
match self.content {
Content::Settings => html! { <TabSettings/> },
Content::Permissions => html! { <TabPermissions/> },
Content::Users => html! { <TabUsers/> }
}
}
</div>
</>
}
}
}
|
use crate::{
event::{self, Event},
shutdown::ShutdownSignal,
stream::StreamExt01,
topology::config::{DataType, GlobalOptions, SourceConfig, SourceDescription},
};
use bytes::Bytes;
use futures::compat::Compat;
use futures01::{sync::mpsc, Future, Sink, Stream};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use snafu::Snafu;
use std::{io, sync::Mutex, thread};
use tokio::sync::broadcast::{channel, Sender};
#[derive(Debug, Snafu)]
enum BuildError {
#[snafu(display("CRITICAL_SECTION poisoned"))]
CriticalSectionPoisoned,
}
lazy_static! {
static ref CRITICAL_SECTION: Mutex<Option<Sender<Bytes>>> = Mutex::default();
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct StdinConfig {
#[serde(default = "default_max_length")]
pub max_length: usize,
pub host_key: Option<String>,
}
impl Default for StdinConfig {
fn default() -> Self {
StdinConfig {
max_length: default_max_length(),
host_key: None,
}
}
}
fn default_max_length() -> usize {
bytesize::kib(100u64) as usize
}
inventory::submit! {
SourceDescription::new::<StdinConfig>("stdin")
}
#[typetag::serde(name = "stdin")]
impl SourceConfig for StdinConfig {
fn build(
&self,
_name: &str,
_globals: &GlobalOptions,
shutdown: ShutdownSignal,
out: mpsc::Sender<Event>,
) -> crate::Result<super::Source> {
stdin_source(io::BufReader::new(io::stdin()), self.clone(), shutdown, out)
}
fn output_type(&self) -> DataType {
DataType::Log
}
fn source_type(&self) -> &'static str {
"stdin"
}
}
pub fn stdin_source<R>(
stdin: R,
config: StdinConfig,
shutdown: ShutdownSignal,
out: mpsc::Sender<Event>,
) -> crate::Result<super::Source>
where
R: Send + io::BufRead + 'static,
{
// The idea is to have one dedicated future for reading stdin running in the background,
// and the sources would recieve the lines thorugh a multi consumer channel.
//
// Implemented solution relies on having a copy of optional sender behind a global mutex,
// and have stdin sources and background thread synchronize on it.
//
// When source is built it must:
// 1. enter critical section by locking mutex.
// 2. if sender isn't present start background thread and set sender.
// 3. gain receiver by calling subscribe on the sender.
// 4. release lock.
//
// When source has finished it should just drop it's receiver.
//
// Background thread should be started with copy of the sender.
//
// Once background thread wants to stop it must:
// 1. enter critical section by locking mutex.
// 2. if there are receivers it must abort the stop.
// 3. remove sender.
// 4. release lock.
//
// Although it's possible to implement this in a lock free, maybe even wait free manner,
// this should be easier to reason about and performance shouldn't suffer since this procedure
// is cold compared to the rest of the source.
let host_key = config
.host_key
.unwrap_or_else(|| event::log_schema().host_key().to_string());
let hostname = hostname::get_hostname();
let mut guard = CRITICAL_SECTION
.lock()
.map_err(|_| BuildError::CriticalSectionPoisoned)?;
let receiver = match guard.as_ref() {
Some(sender) => sender.subscribe(),
None => {
let (sender, receiver) = channel(1024);
*guard = Some(sender.clone());
// Start the background thread
thread::spawn(move || {
info!("Capturing STDIN.");
for line in stdin.lines() {
match line {
Err(e) => {
error!(message = "Unable to read from source.", error = %e);
break;
}
Ok(line) => {
if sender.send(Bytes::from(line)).is_err() {
// There are no active receivers.
// Try to stop.
let mut guard =
CRITICAL_SECTION.lock().expect("CRITICAL_SECTION poisoned");
if sender.receiver_count() == 0 {
guard.take();
return;
}
// A new receiver has shown up.
// It's fine not to resend the line since it came from
// before this new receiver has shown up.
}
}
}
}
CRITICAL_SECTION
.lock()
.expect("CRITICAL_SECTION poisoned")
.take();
});
receiver
}
};
std::mem::drop(guard);
Ok(Box::new(
Compat::new(receiver)
.take_until(shutdown)
.map(move |line| create_event(line, &host_key, &hostname))
.map_err(|e| error!("error reading line: {:?}", e))
.forward(
out.sink_map_err(|e| error!(message = "Unable to send event to out.", error = %e)),
)
.map(|_| info!("finished sending")),
))
}
fn create_event(line: Bytes, host_key: &str, hostname: &Option<String>) -> Event {
let mut event = Event::from(line);
// Add source type
event
.as_mut_log()
.insert(event::log_schema().source_type_key(), "stdin");
if let Some(hostname) = &hostname {
event.as_mut_log().insert(host_key, hostname.clone());
}
event
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{event, test_util::runtime};
use futures01::sync::mpsc;
use futures01::Async::*;
use std::io::Cursor;
#[test]
fn stdin_create_event() {
let line = Bytes::from("hello world");
let host_key = "host".to_string();
let hostname = Some("Some.Machine".to_string());
let event = create_event(line, &host_key, &hostname);
let log = event.into_log();
assert_eq!(log[&"host".into()], "Some.Machine".into());
assert_eq!(
log[&event::log_schema().message_key()],
"hello world".into()
);
assert_eq!(log[event::log_schema().source_type_key()], "stdin".into());
}
#[test]
fn stdin_decodes_line() {
crate::test_util::trace_init();
let (tx, mut rx) = mpsc::channel(10);
let config = StdinConfig::default();
let buf = Cursor::new("hello world\nhello world again");
let mut rt = runtime();
let source = stdin_source(buf, config, ShutdownSignal::noop(), tx).unwrap();
rt.block_on(source).unwrap();
let event = rx.poll().unwrap();
assert!(event.is_ready());
assert_eq!(
Ready(Some("hello world".into())),
event.map(|event| event
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy()))
);
let event = rx.poll().unwrap();
assert!(event.is_ready());
assert_eq!(
Ready(Some("hello world again".into())),
event.map(|event| event
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy()))
);
let event = rx.poll().unwrap();
assert!(event.is_ready());
assert_eq!(Ready(None), event);
}
}
|
fn main() {
let a = 3.1f32;
let b = 3.9f32;
let c = -3.1f32;
let d = -3.9f32;
assert_eq!(a.trunc(), 3.0);
assert_eq!(b.trunc(), 3.0);
assert_eq!(c.trunc(), -3.0);
assert_eq!(d.trunc(), -3.0);
}
|
#[doc = "Reader of register CR1"]
pub type R = crate::R<u32, super::CR1>;
#[doc = "Writer for register CR1"]
pub type W = crate::W<u32, super::CR1>;
#[doc = "Register CR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::CR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Locking the AF configuration of associated IOs\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IOLOCK_A {
#[doc = "0: IO configuration unlocked"]
UNLOCKED = 0,
#[doc = "1: IO configuration locked"]
LOCKED = 1,
}
impl From<IOLOCK_A> for bool {
#[inline(always)]
fn from(variant: IOLOCK_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `IOLOCK`"]
pub type IOLOCK_R = crate::R<bool, IOLOCK_A>;
impl IOLOCK_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IOLOCK_A {
match self.bits {
false => IOLOCK_A::UNLOCKED,
true => IOLOCK_A::LOCKED,
}
}
#[doc = "Checks if the value of the field is `UNLOCKED`"]
#[inline(always)]
pub fn is_unlocked(&self) -> bool {
*self == IOLOCK_A::UNLOCKED
}
#[doc = "Checks if the value of the field is `LOCKED`"]
#[inline(always)]
pub fn is_locked(&self) -> bool {
*self == IOLOCK_A::LOCKED
}
}
#[doc = "CRC calculation initialization pattern control for transmitter\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TCRCINI_A {
#[doc = "0: All zeros TX CRC initialization pattern"]
ALLZEROS = 0,
#[doc = "1: All ones TX CRC initialization pattern"]
ALLONES = 1,
}
impl From<TCRCINI_A> for bool {
#[inline(always)]
fn from(variant: TCRCINI_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TCRCINI`"]
pub type TCRCINI_R = crate::R<bool, TCRCINI_A>;
impl TCRCINI_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TCRCINI_A {
match self.bits {
false => TCRCINI_A::ALLZEROS,
true => TCRCINI_A::ALLONES,
}
}
#[doc = "Checks if the value of the field is `ALLZEROS`"]
#[inline(always)]
pub fn is_all_zeros(&self) -> bool {
*self == TCRCINI_A::ALLZEROS
}
#[doc = "Checks if the value of the field is `ALLONES`"]
#[inline(always)]
pub fn is_all_ones(&self) -> bool {
*self == TCRCINI_A::ALLONES
}
}
#[doc = "Write proxy for field `TCRCINI`"]
pub struct TCRCINI_W<'a> {
w: &'a mut W,
}
impl<'a> TCRCINI_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TCRCINI_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "All zeros TX CRC initialization pattern"]
#[inline(always)]
pub fn all_zeros(self) -> &'a mut W {
self.variant(TCRCINI_A::ALLZEROS)
}
#[doc = "All ones TX CRC initialization pattern"]
#[inline(always)]
pub fn all_ones(self) -> &'a mut W {
self.variant(TCRCINI_A::ALLONES)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "CRC calculation initialization pattern control for receiver\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RCRCINI_A {
#[doc = "0: All zeros RX CRC initialization pattern"]
ALLZEROS = 0,
#[doc = "1: All ones RX CRC initialization pattern"]
ALLONES = 1,
}
impl From<RCRCINI_A> for bool {
#[inline(always)]
fn from(variant: RCRCINI_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `RCRCINI`"]
pub type RCRCINI_R = crate::R<bool, RCRCINI_A>;
impl RCRCINI_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RCRCINI_A {
match self.bits {
false => RCRCINI_A::ALLZEROS,
true => RCRCINI_A::ALLONES,
}
}
#[doc = "Checks if the value of the field is `ALLZEROS`"]
#[inline(always)]
pub fn is_all_zeros(&self) -> bool {
*self == RCRCINI_A::ALLZEROS
}
#[doc = "Checks if the value of the field is `ALLONES`"]
#[inline(always)]
pub fn is_all_ones(&self) -> bool {
*self == RCRCINI_A::ALLONES
}
}
#[doc = "Write proxy for field `RCRCINI`"]
pub struct RCRCINI_W<'a> {
w: &'a mut W,
}
impl<'a> RCRCINI_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RCRCINI_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "All zeros RX CRC initialization pattern"]
#[inline(always)]
pub fn all_zeros(self) -> &'a mut W {
self.variant(RCRCINI_A::ALLZEROS)
}
#[doc = "All ones RX CRC initialization pattern"]
#[inline(always)]
pub fn all_ones(self) -> &'a mut W {
self.variant(RCRCINI_A::ALLONES)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "32-bit CRC polynomial configuration\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CRC33_17_A {
#[doc = "0: Full size (33/17 bit) CRC polynomial is not used"]
DISABLED = 0,
#[doc = "1: Full size (33/17 bit) CRC polynomial is used"]
ENABLED = 1,
}
impl From<CRC33_17_A> for bool {
#[inline(always)]
fn from(variant: CRC33_17_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CRC33_17`"]
pub type CRC33_17_R = crate::R<bool, CRC33_17_A>;
impl CRC33_17_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CRC33_17_A {
match self.bits {
false => CRC33_17_A::DISABLED,
true => CRC33_17_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CRC33_17_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CRC33_17_A::ENABLED
}
}
#[doc = "Write proxy for field `CRC33_17`"]
pub struct CRC33_17_W<'a> {
w: &'a mut W,
}
impl<'a> CRC33_17_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CRC33_17_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Full size (33/17 bit) CRC polynomial is not used"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(CRC33_17_A::DISABLED)
}
#[doc = "Full size (33/17 bit) CRC polynomial is used"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(CRC33_17_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Internal SS signal input level\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SSI_A {
#[doc = "0: 0 is forced onto the SS signal and the I/O value of the SS pin is ignored"]
SLAVESELECTED = 0,
#[doc = "1: 1 is forced onto the SS signal and the I/O value of the SS pin is ignored"]
SLAVENOTSELECTED = 1,
}
impl From<SSI_A> for bool {
#[inline(always)]
fn from(variant: SSI_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SSI`"]
pub type SSI_R = crate::R<bool, SSI_A>;
impl SSI_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SSI_A {
match self.bits {
false => SSI_A::SLAVESELECTED,
true => SSI_A::SLAVENOTSELECTED,
}
}
#[doc = "Checks if the value of the field is `SLAVESELECTED`"]
#[inline(always)]
pub fn is_slave_selected(&self) -> bool {
*self == SSI_A::SLAVESELECTED
}
#[doc = "Checks if the value of the field is `SLAVENOTSELECTED`"]
#[inline(always)]
pub fn is_slave_not_selected(&self) -> bool {
*self == SSI_A::SLAVENOTSELECTED
}
}
#[doc = "Write proxy for field `SSI`"]
pub struct SSI_W<'a> {
w: &'a mut W,
}
impl<'a> SSI_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SSI_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "0 is forced onto the SS signal and the I/O value of the SS pin is ignored"]
#[inline(always)]
pub fn slave_selected(self) -> &'a mut W {
self.variant(SSI_A::SLAVESELECTED)
}
#[doc = "1 is forced onto the SS signal and the I/O value of the SS pin is ignored"]
#[inline(always)]
pub fn slave_not_selected(self) -> &'a mut W {
self.variant(SSI_A::SLAVENOTSELECTED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Rx/Tx direction at Half-duplex mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HDDIR_A {
#[doc = "0: Receiver in half duplex mode"]
RECEIVER = 0,
#[doc = "1: Transmitter in half duplex mode"]
TRANSMITTER = 1,
}
impl From<HDDIR_A> for bool {
#[inline(always)]
fn from(variant: HDDIR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HDDIR`"]
pub type HDDIR_R = crate::R<bool, HDDIR_A>;
impl HDDIR_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HDDIR_A {
match self.bits {
false => HDDIR_A::RECEIVER,
true => HDDIR_A::TRANSMITTER,
}
}
#[doc = "Checks if the value of the field is `RECEIVER`"]
#[inline(always)]
pub fn is_receiver(&self) -> bool {
*self == HDDIR_A::RECEIVER
}
#[doc = "Checks if the value of the field is `TRANSMITTER`"]
#[inline(always)]
pub fn is_transmitter(&self) -> bool {
*self == HDDIR_A::TRANSMITTER
}
}
#[doc = "Write proxy for field `HDDIR`"]
pub struct HDDIR_W<'a> {
w: &'a mut W,
}
impl<'a> HDDIR_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HDDIR_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Receiver in half duplex mode"]
#[inline(always)]
pub fn receiver(self) -> &'a mut W {
self.variant(HDDIR_A::RECEIVER)
}
#[doc = "Transmitter in half duplex mode"]
#[inline(always)]
pub fn transmitter(self) -> &'a mut W {
self.variant(HDDIR_A::TRANSMITTER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Master SUSPend request\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CSUSP_AW {
#[doc = "0: Do not request master suspend"]
NOTREQUESTED = 0,
#[doc = "1: Request master suspend"]
REQUESTED = 1,
}
impl From<CSUSP_AW> for bool {
#[inline(always)]
fn from(variant: CSUSP_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `CSUSP`"]
pub struct CSUSP_W<'a> {
w: &'a mut W,
}
impl<'a> CSUSP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CSUSP_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Do not request master suspend"]
#[inline(always)]
pub fn not_requested(self) -> &'a mut W {
self.variant(CSUSP_AW::NOTREQUESTED)
}
#[doc = "Request master suspend"]
#[inline(always)]
pub fn requested(self) -> &'a mut W {
self.variant(CSUSP_AW::REQUESTED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Master transfer start\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CSTART_A {
#[doc = "0: Do not start master transfer"]
NOTSTARTED = 0,
#[doc = "1: Start master transfer"]
STARTED = 1,
}
impl From<CSTART_A> for bool {
#[inline(always)]
fn from(variant: CSTART_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CSTART`"]
pub type CSTART_R = crate::R<bool, CSTART_A>;
impl CSTART_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CSTART_A {
match self.bits {
false => CSTART_A::NOTSTARTED,
true => CSTART_A::STARTED,
}
}
#[doc = "Checks if the value of the field is `NOTSTARTED`"]
#[inline(always)]
pub fn is_not_started(&self) -> bool {
*self == CSTART_A::NOTSTARTED
}
#[doc = "Checks if the value of the field is `STARTED`"]
#[inline(always)]
pub fn is_started(&self) -> bool {
*self == CSTART_A::STARTED
}
}
#[doc = "Write proxy for field `CSTART`"]
pub struct CSTART_W<'a> {
w: &'a mut W,
}
impl<'a> CSTART_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CSTART_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Do not start master transfer"]
#[inline(always)]
pub fn not_started(self) -> &'a mut W {
self.variant(CSTART_A::NOTSTARTED)
}
#[doc = "Start master transfer"]
#[inline(always)]
pub fn started(self) -> &'a mut W {
self.variant(CSTART_A::STARTED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Master automatic SUSP in Receive mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MASRX_A {
#[doc = "0: Automatic suspend in master receive-only mode disabled"]
DISABLED = 0,
#[doc = "1: Automatic suspend in master receive-only mode enabled"]
ENABLED = 1,
}
impl From<MASRX_A> for bool {
#[inline(always)]
fn from(variant: MASRX_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MASRX`"]
pub type MASRX_R = crate::R<bool, MASRX_A>;
impl MASRX_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MASRX_A {
match self.bits {
false => MASRX_A::DISABLED,
true => MASRX_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == MASRX_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == MASRX_A::ENABLED
}
}
#[doc = "Write proxy for field `MASRX`"]
pub struct MASRX_W<'a> {
w: &'a mut W,
}
impl<'a> MASRX_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MASRX_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Automatic suspend in master receive-only mode disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(MASRX_A::DISABLED)
}
#[doc = "Automatic suspend in master receive-only mode enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(MASRX_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Serial Peripheral Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPE_A {
#[doc = "0: Peripheral disabled"]
DISABLED = 0,
#[doc = "1: Peripheral enabled"]
ENABLED = 1,
}
impl From<SPE_A> for bool {
#[inline(always)]
fn from(variant: SPE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SPE`"]
pub type SPE_R = crate::R<bool, SPE_A>;
impl SPE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SPE_A {
match self.bits {
false => SPE_A::DISABLED,
true => SPE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SPE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SPE_A::ENABLED
}
}
#[doc = "Write proxy for field `SPE`"]
pub struct SPE_W<'a> {
w: &'a mut W,
}
impl<'a> SPE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Peripheral disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SPE_A::DISABLED)
}
#[doc = "Peripheral enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SPE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 16 - Locking the AF configuration of associated IOs"]
#[inline(always)]
pub fn iolock(&self) -> IOLOCK_R {
IOLOCK_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 15 - CRC calculation initialization pattern control for transmitter"]
#[inline(always)]
pub fn tcrcini(&self) -> TCRCINI_R {
TCRCINI_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 14 - CRC calculation initialization pattern control for receiver"]
#[inline(always)]
pub fn rcrcini(&self) -> RCRCINI_R {
RCRCINI_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 13 - 32-bit CRC polynomial configuration"]
#[inline(always)]
pub fn crc33_17(&self) -> CRC33_17_R {
CRC33_17_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12 - Internal SS signal input level"]
#[inline(always)]
pub fn ssi(&self) -> SSI_R {
SSI_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11 - Rx/Tx direction at Half-duplex mode"]
#[inline(always)]
pub fn hddir(&self) -> HDDIR_R {
HDDIR_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 9 - Master transfer start"]
#[inline(always)]
pub fn cstart(&self) -> CSTART_R {
CSTART_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - Master automatic SUSP in Receive mode"]
#[inline(always)]
pub fn masrx(&self) -> MASRX_R {
MASRX_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 0 - Serial Peripheral Enable"]
#[inline(always)]
pub fn spe(&self) -> SPE_R {
SPE_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 15 - CRC calculation initialization pattern control for transmitter"]
#[inline(always)]
pub fn tcrcini(&mut self) -> TCRCINI_W {
TCRCINI_W { w: self }
}
#[doc = "Bit 14 - CRC calculation initialization pattern control for receiver"]
#[inline(always)]
pub fn rcrcini(&mut self) -> RCRCINI_W {
RCRCINI_W { w: self }
}
#[doc = "Bit 13 - 32-bit CRC polynomial configuration"]
#[inline(always)]
pub fn crc33_17(&mut self) -> CRC33_17_W {
CRC33_17_W { w: self }
}
#[doc = "Bit 12 - Internal SS signal input level"]
#[inline(always)]
pub fn ssi(&mut self) -> SSI_W {
SSI_W { w: self }
}
#[doc = "Bit 11 - Rx/Tx direction at Half-duplex mode"]
#[inline(always)]
pub fn hddir(&mut self) -> HDDIR_W {
HDDIR_W { w: self }
}
#[doc = "Bit 10 - Master SUSPend request"]
#[inline(always)]
pub fn csusp(&mut self) -> CSUSP_W {
CSUSP_W { w: self }
}
#[doc = "Bit 9 - Master transfer start"]
#[inline(always)]
pub fn cstart(&mut self) -> CSTART_W {
CSTART_W { w: self }
}
#[doc = "Bit 8 - Master automatic SUSP in Receive mode"]
#[inline(always)]
pub fn masrx(&mut self) -> MASRX_W {
MASRX_W { w: self }
}
#[doc = "Bit 0 - Serial Peripheral Enable"]
#[inline(always)]
pub fn spe(&mut self) -> SPE_W {
SPE_W { w: self }
}
}
|
use super::check;
#[test]
fn t01_inline() {
check(
".result {\n output: 'squoted';\n output: #{'squoted'};\n \
output: \"[#{'squoted'}]\";\n output: \"#{'squoted'}\";\n \
output: '#{'squoted'}';\n output: \"['#{'squoted'}']\";\n}\n",
".result {\n output: 'squoted';\n output: squoted;\n \
output: \"[squoted]\";\n output: \"squoted\";\n \
output: \"squoted\";\n output: \"['squoted']\";\n}\n",
)
}
#[test]
fn t02_variable() {
check(
"$input: 'squoted';\n.result {\n output: $input;\n \
output: #{$input};\n output: \"[#{$input}]\";\n \
output: \"#{$input}\";\n output: '#{$input}';\n \
output: \"['#{$input}']\";\n}\n",
".result {\n output: \"squoted\";\n output: squoted;\n \
output: \"[squoted]\";\n output: \"squoted\";\n \
output: \"squoted\";\n output: \"['squoted']\";\n}\n",
)
}
#[test]
fn t06_escape_interpolation() {
check(
"$input: 'squoted';\n.result {\n output: \"[\\#{'squoted'}]\";\n \
output: \"\\#{'squoted'}\";\n output: '\\#{'squoted'}';\n \
output: \"['\\#{'squoted'}']\";\n}\n",
".result {\n output: \"[\\#{'squoted'}]\";\n \
output: \"\\#{'squoted'}\";\n output: \"#{\" squoted \"}\";\n \
output: \"['\\#{'squoted'}']\";\n}\n",
)
}
|
use Command;
use hex;
use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::io::BufReader;
use atoi::atoi;
pub struct Request<'a> {
pub reader: BufReader<&'a TcpStream>,
}
impl<'a> Request<'a> {
// add code here
pub fn decode(&mut self) -> io::Result<Option<Command>> {
if let Some(line) = self.read_line()? {
let mut line_iter = line.iter();
if line_iter.next() != Some(&b'*') {
return Err(io::Error::new(io::ErrorKind::Other, "not an array"));
}
let argc = line_iter
.next()
.and_then(|arg| atoi::<u8>(&[*arg]))
.ok_or(io::Error::new(io::ErrorKind::Other, "Malformed request"))?;
let mut args: Vec<Vec<u8>> = Vec::new();
for _i in 0..argc {
self.read_line()?
.and_then(|line| {
if line.starts_with(&[b'$']) {
Some(line)
} else {
None
}
})
.and_then(|line| {
atoi::<usize>(line.get(1..)?)
})
.and_then(|size: usize| {
let mut line = self.read_exact(size + 2).ok()??;
line.truncate(size);
args.push(line);
Some(0)
})
.ok_or(io::Error::new(io::ErrorKind::Other, "Malformed request"))?;
}
match &args[0][..] {
b"PING" => Ok(Some(Command::PING)),
b"SET" => {
if args.len() < 2 {
return Err(io::Error::new(io::ErrorKind::Other, "Malformed request"));
}
Ok(Some(Command::SET(args.swap_remove(2))))
}
b"GET" => {
if args.len() < 1 {
return Err(io::Error::new(io::ErrorKind::Other, "Malformed request"));
}
let hash = match hex::decode(&args[1]) {
Ok(hash) => hash,
Err(_) => {
return Err(io::Error::new(io::ErrorKind::Other, "Malformed request"));
}
};
Ok(Some(Command::GET(hash)))
}
_ => Ok(Some(Command::NOTSUPPORTED)),
}
} else {
Ok(None)
}
}
fn read_line(&mut self) -> io::Result<Option<Vec<u8>>> {
let mut line = vec![];
self.reader.read_until(b'\n', &mut line)?;
line.pop();
line.pop();
if !line.is_empty() {
Ok(Some(line))
} else {
Ok(None)
}
}
fn read_exact(&mut self, size: usize) -> io::Result<Option<Vec<u8>>> {
let mut line = vec![0u8; size];
self.reader.read_exact(&mut line)?;
if !line.is_empty() {
Ok(Some(line))
} else {
Ok(None)
}
}
}
|
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
use structopt::StructOpt;
use std::net::UdpSocket;
const PIN_LED1: i32 = 0;
const PIN_LED2: i32 = 2;
const PIN_INPUT: i32 = 3;
fn set_led_state(buf: &mut [u8], pin: usize, val: &str) {
match val {
"on" => buf[pin] = 1,
"off" => buf[pin] = 0,
_ => (),
}
}
#[derive(StructOpt, Debug)]
struct Opt {
#[structopt(long = "led1", help = "turn led1 ON/OFF")]
led1: Option<String>,
#[structopt(long = "led2", help = "turn led2 ON/OFF")]
led2: Option<String>,
#[structopt(long="remoteaddr", help = "remote IP")]
remoteaddr: String,
}
fn main() {
let opt = Opt::from_args();
println!("{:?}", opt);
let mut buf = [2;2];
if let Some(state) = opt.led1 {
set_led_state(&mut buf, 0, &state);
}
if let Some(state) = opt.led2 {
set_led_state(&mut buf, 1, &state);
}
let serv_addr = opt.remoteaddr;
let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap();
socket.send_to(&buf, serv_addr);
}
|
use std::str::FromStr;
use solana_program::pubkey::Pubkey;
pub fn susy_wrapped_gton_mint() -> Pubkey {
Pubkey::from_str("nVZnRKdr3pmcgnJvYDE8iafgiMiBqxiffQMcyv5ETdA").unwrap()
}
|
test_stdout!(without_value_returns_empty_list, "[]\n");
test_stdout!(
with_value_returns_keys_with_value_in_list,
"true\ntrue\nfalse\n"
);
// From https://github.com/erlang/otp/blob/a62aed81c56c724f7dd7040adecaa28a78e5d37f/erts/doc/src/erlang.xml#L2104-L2112
test_stdout!(doc_test, "true\ntrue\ntrue\ntrue\ntrue\ntrue\n");
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// This test verifies that casting from the same lifetime on a value
// to the same lifetime on a trait succeeds. See issue #10766.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
use std::marker;
fn main() {
trait T { fn foo(&self) {} }
fn f<'a, V: T>(v: &'a V) -> &'a T {
v as &'a T
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IVibrationDevice(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVibrationDevice {
type Vtable = IVibrationDevice_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1b4a6595_cfcd_4e08_92fb_c1906d04498c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVibrationDevice_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, duration: super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVibrationDeviceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVibrationDeviceStatics {
type Vtable = IVibrationDeviceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x332fd2f1_1c69_4c91_949e_4bb67a85bdc7);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVibrationDeviceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VibrationDevice(pub ::windows::core::IInspectable);
impl VibrationDevice {
#[cfg(feature = "Foundation")]
pub fn Vibrate<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TimeSpan>>(&self, duration: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), duration.into_param().abi()).ok() }
}
pub fn Cancel(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }
}
pub fn GetDefault() -> ::windows::core::Result<VibrationDevice> {
Self::IVibrationDeviceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<VibrationDevice>(result__)
})
}
pub fn IVibrationDeviceStatics<R, F: FnOnce(&IVibrationDeviceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<VibrationDevice, IVibrationDeviceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for VibrationDevice {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Phone.Devices.Notification.VibrationDevice;{1b4a6595-cfcd-4e08-92fb-c1906d04498c})");
}
unsafe impl ::windows::core::Interface for VibrationDevice {
type Vtable = IVibrationDevice_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1b4a6595_cfcd_4e08_92fb_c1906d04498c);
}
impl ::windows::core::RuntimeName for VibrationDevice {
const NAME: &'static str = "Windows.Phone.Devices.Notification.VibrationDevice";
}
impl ::core::convert::From<VibrationDevice> for ::windows::core::IUnknown {
fn from(value: VibrationDevice) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VibrationDevice> for ::windows::core::IUnknown {
fn from(value: &VibrationDevice) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VibrationDevice {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a VibrationDevice {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VibrationDevice> for ::windows::core::IInspectable {
fn from(value: VibrationDevice) -> Self {
value.0
}
}
impl ::core::convert::From<&VibrationDevice> for ::windows::core::IInspectable {
fn from(value: &VibrationDevice) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VibrationDevice {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a VibrationDevice {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for VibrationDevice {}
unsafe impl ::core::marker::Sync for VibrationDevice {}
|
mod grid;
mod space;
mod value;
pub use grid::Grid;
|
use super::{Action, Content, History, Session, Subject, Topic};
use crate::state::SpentTime;
use std::error::Error;
mod sqlite;
pub use sqlite::Sqlite;
pub trait Backend {
fn transfer_content(&mut self, content: &Content) -> Result<(), Box<dyn Error>>;
fn transfer_history(&mut self, history: &History) -> Result<(), Box<dyn Error>>;
fn load_content(&mut self) -> Result<Content, Box<dyn Error>>;
fn load_history(&mut self, content: &Content) -> Result<History, Box<dyn Error>>;
fn create_action(&mut self, name: &str) -> Result<Action, Box<dyn Error>>;
fn create_subject(&mut self, name: &str) -> Result<Subject, Box<dyn Error>>;
fn update_time(&mut self, topic: &Topic, time: &SpentTime) -> Result<(), Box<dyn Error>>;
fn add_session(&mut self, session: &Session) -> Result<(), Box<dyn Error>>;
}
|
pub mod utilities;
use crate::utilities::Verify;
use proffer::*;
#[test]
fn impl_basic_gen_with_trait() {
let mut ipl = Impl::new("That")
.set_impl_trait(Some(Trait::new("This")))
.to_owned();
let expected = r#"
impl This for That
{
}
"#;
let src_code = ipl.generate_and_verify();
println!("{}", &src_code);
assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code));
// Add a function to the impl
let expected = r#"
impl This for That
{
fn foo() -> ()
{
}
}
"#;
let ipl = ipl.add_function(Function::new("foo"));
let src_code = ipl.generate_and_verify();
println!("{}", &src_code);
assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code));
}
#[test]
fn impl_basic_gen_without_trait() {
let ipl = Impl::new("That");
let expected = r#"
impl That
{
}
"#;
let src_code = ipl.generate_and_verify();
println!("{}", &src_code);
assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code));
}
#[test]
fn impl_with_generics() {
let ipl = Impl::new("That")
.add_generic(
Generic::new("T")
.add_trait_bounds(vec!["ToString"])
.to_owned(),
)
.add_function(
Function::new("foo")
.set_is_pub(true)
.add_parameter(Parameter::new("bar1", "T"))
.add_parameter(Parameter::new("bar2", "S"))
.set_return_ty("T")
.add_generic(Generic::new("S"))
.set_body("bar")
.to_owned(),
)
.to_owned();
let expected = r#"
impl<T> That<T>
where
T: ToString,
{
pub fn foo<S>(bar1: T, bar2: S) -> T
where
S: ,
{
bar
}
}
"#;
let src_code = ipl.generate_and_verify();
println!("{}", &src_code);
assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code));
}
#[test]
fn impl_with_associated_types() {
let ipl = Impl::new("That")
.set_impl_trait(Some(Trait::new("This")))
.add_associated_type(AssociatedTypeDefinition::new("FOO", "Bar"))
.add_associated_type(AssociatedTypeDefinition::new("BAR", "Foo"))
.to_owned();
let expected = r#"
impl This for That
{
type FOO = Bar;
type BAR = Foo;
}
"#;
let src_code = ipl.generate_and_verify();
println!("{}", &src_code);
assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code));
}
#[test]
fn impl_with_associated_type_attributes() {
let ipl = Impl::new("That")
.set_impl_trait(Some(Trait::new("This")))
.add_associated_type(
AssociatedTypeDefinition::new("FOO", "Bar")
.add_attribute("#[foo]")
.to_owned(),
)
.add_associated_type(
AssociatedTypeDefinition::new("BAR", "Foo")
.add_attributes(&["#[foo]", "#[bar]"])
.to_owned(),
)
.to_owned();
let expected = r#"
impl This for That
{
#[foo]
type FOO = Bar;
#[foo]
#[bar]
type BAR = Foo;
}
"#;
let src_code = ipl.generate_and_verify();
println!("{}", &src_code);
assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code));
}
|
use std::convert::Into;
use std::iter::*;
use std::fmt;
use std::default::Default;
use std::ops::Add;
use protobuf_iter::*;
#[derive(Clone)]
pub struct DeltaEncodedIter<'a, P: Packed<'a>, T: Clone + Add<T, Output=T> + From<<P as Packed<'a>>::Item> + Default> {
inner: PackedIter<'a, P, T>,
last: T,
}
impl<'a, P: Packed<'a>, T: Clone + Add<T, Output=T> + From<<P as Packed<'a>>::Item> + Default> DeltaEncodedIter<'a, P, T> {
pub fn new(value: ParseValue<'a>) -> Self {
DeltaEncodedIter {
inner: value.into(),
last: Default::default(), // 0
}
}
}
impl<'a, P: Packed<'a>, T: Clone + Add<T, Output=T> + From<<P as Packed<'a>>::Item> + Default> Iterator for DeltaEncodedIter<'a, P, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
.map(|value| {
let current = self.last.clone() + value;
self.last = current.clone();
current
})
}
}
impl<'a, P: Clone + Packed<'a>, T: fmt::Debug + Clone + Add<T, Output=T> + From<<P as Packed<'a>>::Item> + Default> fmt::Debug for DeltaEncodedIter<'a, P, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.clone().collect::<Vec<T>>().fmt(f)
}
}
|
use cube::corners::Corner;
use cube::edges::Edge;
#[derive(Clone, Copy)]
pub enum Move {
Up,
Right,
Front,
Down,
Left,
Back,
}
impl Move {
pub fn from_u(u :usize) -> Move {
match u {
0 => Move::Up,
1 => Move::Right,
2 => Move::Front,
3 => Move::Down,
4 => Move::Left,
5 => Move::Back,
_ => unimplemented!(),
}
}
}
pub struct Move_ {
pub corners_permutation: [Corner; 8],
pub corners_orientation: [u8; 8],
pub edges_permutation: [Edge; 12],
pub edges_orientation: [u8; 12],
}
impl Move_ {
pub fn move_definition(m: Move) -> Self {
use cube::corners::Corner::*;
use cube::edges::Edge::*;
use self::Move::*;
match m {
Up => Self {
corners_permutation: [UBR, URF, UFL, ULB, DFR, DLF, DBL, DRB],
corners_orientation: [0; 8],
edges_permutation: [UB, UR, UF, UL, DR, DF, DL, DB, FR, FL, BL, BR],
edges_orientation: [0; 12],
},
Right => Self {
corners_permutation: [DFR, UFL, ULB, URF, DRB, DLF, DBL, UBR],
corners_orientation: [2, 0, 0, 1, 1, 0, 0, 2],
edges_permutation: [FR, UF, UL, UB, BR, DF, DL, DB, DR, FL, BL, UR],
edges_orientation: [0; 12],
},
Front => Self {
corners_permutation: [UFL, DLF, ULB, UBR, URF, DFR, DBL, DRB],
corners_orientation: [1, 2, 0, 0, 2, 1, 0, 0],
edges_permutation: [UR, FL, UL, UB, DR, FR, DL, DB, UF, DF, BL, BR],
edges_orientation: [0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0],
},
Down => Self {
corners_permutation: [URF, UFL, ULB, UBR, DLF, DBL, DRB, DFR],
corners_orientation: [0; 8],
edges_permutation: [UR, UF, UL, UB, DF, DL, DB, DR, FR, FL, BL, BR],
edges_orientation: [0; 12],
},
Left => Self {
corners_permutation: [URF, ULB, DBL, UBR, DFR, UFL, DLF, DRB],
corners_orientation: [0, 1, 2, 0, 0, 2, 1, 0],
edges_permutation: [UR, UF, BL, UB, DR, DF, FL, DB, FR, UL, DL, BR],
edges_orientation: [0; 12],
},
Back => Self {
corners_permutation: [URF, UFL, UBR, DRB, DFR, DLF, ULB, DBL],
corners_orientation: [0, 0, 1, 2, 0, 0, 2, 1],
edges_permutation: [UR, UF, UL, BR, DR, DF, DL, BL, FR, FL, UB, DB],
edges_orientation: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1],
},
}
}
}
#[derive(Clone, Copy)]
pub enum UserMove {
Front,
FrontPrime,
Front2,
Right,
RightPrime,
Right2,
Up,
UpPrime,
Up2,
Back,
BackPrime,
Back2,
Left,
LeftPrime,
Left2,
Down,
DownPrime,
Down2,
}
impl UserMove {
pub fn sequence_from_str(s: &str) -> Result<Vec<(Self, usize)>, ()> {
let mut sequence = Vec::new();
let splitted = s.split_whitespace();
use self::UserMove::*;
for elem in splitted {
let move_ = match elem {
"F" => (Front, 1),
"F'" => (FrontPrime, 3),
"F2" => (Front2, 2),
"R" => (Right, 1),
"R'" => (RightPrime, 3),
"R2" => (Right2, 2),
"U" => (Up, 1),
"U'" => (UpPrime, 3),
"U2" => (Up2, 2),
"B" => (Back, 1),
"B'" => (BackPrime, 3),
"B2" => (Back2, 2),
"L" => (Left, 1),
"L'" => (LeftPrime, 3),
"L2" => (Left2, 2),
"D" => (Down, 1),
"D'" => (DownPrime, 3),
"D2" => (Down2, 2),
_ => return Err(()),
};
sequence.push(move_)
}
Ok(sequence)
}
pub fn to_move(&self) -> Move {
match *self {
UserMove::Front | UserMove::FrontPrime | UserMove::Front2 => Move::Front,
UserMove::Right | UserMove::RightPrime | UserMove::Right2 => Move::Right,
UserMove::Up | UserMove::UpPrime | UserMove::Up2 => Move::Up,
UserMove::Back | UserMove::BackPrime | UserMove::Back2 => Move::Back,
UserMove::Left | UserMove::LeftPrime | UserMove::Left2 => Move::Left,
UserMove::Down | UserMove::DownPrime | UserMove::Down2 => Move::Down,
}
}
}
impl ToString for UserMove {
fn to_string(&self) -> String {
use self::UserMove::*;
let string = match *self {
Front => "F",
FrontPrime => "F'",
Front2 => "F2",
Right => "R",
RightPrime => "R'",
Right2 => "R2",
Up => "U",
UpPrime => "U'",
Up2 => "U2",
Back => "B",
BackPrime => "B'",
Back2 => "B2",
Left => "L",
LeftPrime => "L'",
Left2 => "L2",
Down => "D",
DownPrime => "D'",
Down2 => "D2",
};
string.to_string()
}
}
|
use crate::parser::{Command, Source};
use anyhow::Result;
pub fn parse(cmd: &str, _current_function: &str, source: &Source, _arg1: Option<&str>, _arg2: Option<&str>) -> Option<Result<Command>> {
match cmd {
"add" => Some(Ok(Command::Add(source.clone()))),
"sub" => Some(Ok(Command::Sub(source.clone()))),
"neg" => Some(Ok(Command::Neg(source.clone()))),
"eq" => Some(Ok(Command::Eq(source.clone()))),
"gt" => Some(Ok(Command::Gt(source.clone()))),
"lt" => Some(Ok(Command::Lt(source.clone()))),
"and" => Some(Ok(Command::And(source.clone()))),
"or" => Some(Ok(Command::Or(source.clone()))),
"not" => Some(Ok(Command::Not(source.clone()))),
_ => None,
}
}
|
use P55::*;
pub fn main() {
let trees = cbal_trees(4, 'x');
for tree in trees {
println!("{}", tree);
}
}
|
//! A proportional-integral-derivative (PID) controller.
#![no_std]
extern crate num_traits;
use num_traits::float::FloatCore;
#[derive(Debug)]
pub struct Pid<T: FloatCore> {
/// Proportional gain.
pub kp: T,
/// Integral gain.
pub ki: T,
/// Derivative gain.
pub kd: T,
/// Limit of contribution of P term: `(-p_limit <= P <= p_limit)`
pub p_limit: T,
/// Limit of contribution of I term `(-i_limit <= I <= i_limit)`
pub i_limit: T,
/// Limit of contribution of D term `(-d_limit <= D <= d_limit)`
pub d_limit: T,
/// Limit of the sum of PID terms `(-limit <= P + I + D <+ limit)`
pub limit: T,
pub setpoint: T,
prev_measurement: Option<T>,
/// `integral_term = sum[error(t) * ki(t)] (for all t)`
integral_term: T,
}
#[derive(Debug)]
pub struct ControlOutput<T: FloatCore> {
/// Contribution of the P term to the output.
pub p: T,
/// Contribution of the I term to the output.
/// `i = sum[error(t) * ki(t)] (for all t)`
pub i: T,
/// Contribution of the D term to the output.
pub d: T,
/// Output of the PID controller.
pub output: T,
}
impl<T> Pid<T>
where
T: FloatCore,
{
pub fn new(kp: T, ki: T, kd: T, setpoint: T) -> Self {
let inf = T::infinity();
Self {
kp,
ki,
kd,
p_limit: inf,
i_limit: inf,
d_limit: inf,
limit: inf,
setpoint,
prev_measurement: None,
integral_term: T::zero(),
}
}
/// Resets the integral term back to zero. This may drastically change the
/// control output.
pub fn reset_integral_term(&mut self) {
self.integral_term = T::zero();
}
/// Given a new measurement, calculates the next control output.
pub fn next_control_output(&mut self, measurement: T) -> ControlOutput<T> {
let error = self.setpoint - measurement;
let p_unbounded = error * self.kp;
let p = self.p_limit.min(p_unbounded.abs()) * p_unbounded.signum();
// Mitigate output jumps when ki(t) != ki(t-1).
// While it's standard to use an error_integral that's a running sum of
// just the error (no ki), because we support ki changing dynamically,
// we store the entire term so that we don't need to remember previous
// ki values.
self.integral_term = self.integral_term + error * self.ki;
// Mitigate integral windup: Don't want to keep building up error
// beyond what i_limit will allow.
self.integral_term =
self.i_limit.min(self.integral_term.abs()) * self.integral_term.signum();
// Mitigate derivative kick: Use the derivative of the measurement
// rather than the derivative of the error.
let d_unbounded = -match self.prev_measurement.as_ref() {
Some(prev_measurement) => measurement - *prev_measurement,
None => T::zero(),
} * self.kd;
self.prev_measurement = Some(measurement);
let d = self.d_limit.min(d_unbounded.abs()) * d_unbounded.signum();
let output_unbounded = p + self.integral_term + d;
let output = self.limit.min(output_unbounded.abs()) * output_unbounded.signum();
ControlOutput {
p,
i: self.integral_term,
d,
output: output,
}
}
}
#[cfg(test)]
mod tests {
use super::Pid;
#[test]
fn proportional() {
let mut pid = Pid::new(2.0, 0.0, 0.0, 10.0);
assert_eq!(pid.setpoint, 10.0);
// Test simple proportional
assert_eq!(pid.next_control_output(0.0).output, 20.0);
// Test proportional limit
pid.p_limit = 10.0;
assert_eq!(pid.next_control_output(0.0).output, 10.0);
}
#[test]
fn derivative() {
let mut pid = Pid::new(0.0, 0.0, 2.0, 10.0);
// Test that there's no derivative since it's the first measurement
assert_eq!(pid.next_control_output(0.0).output, 0.0);
// Test that there's now a derivative
assert_eq!(pid.next_control_output(5.0).output, -10.0);
// Test derivative limit
pid.d_limit = 5.0;
assert_eq!(pid.next_control_output(10.0).output, -5.0);
}
#[test]
fn integral() {
let mut pid = Pid::new(0.0, 2.0, 0.0, 10.0);
// Test basic integration
assert_eq!(pid.next_control_output(0.0).output, 20.0);
assert_eq!(pid.next_control_output(0.0).output, 40.0);
assert_eq!(pid.next_control_output(5.0).output, 50.0);
// Test limit
pid.i_limit = 50.0;
assert_eq!(pid.next_control_output(5.0).output, 50.0);
// Test that limit doesn't impede reversal of error integral
assert_eq!(pid.next_control_output(15.0).output, 40.0);
// Test that error integral accumulates negative values
let mut pid2 = Pid::new(0.0, 2.0, 0.0, -10.0);
assert_eq!(pid2.next_control_output(0.0).output, -20.0);
assert_eq!(pid2.next_control_output(0.0).output, -40.0);
pid2.i_limit = 50.0;
assert_eq!(pid2.next_control_output(-5.0).output, -50.0);
// Test that limit doesn't impede reversal of error integral
assert_eq!(pid2.next_control_output(-15.0).output, -40.0);
}
#[test]
fn pid() {
let mut pid = Pid::new(1.0, 0.1, 1.0, 10.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.i, 1.0); // 0.1 * 10.0
assert_eq!(out.d, 0.0); // -(1.0 * 0.0)
assert_eq!(out.output, 11.0);
let out = pid.next_control_output(5.0);
assert_eq!(out.p, 5.0); // 1.0 * 5.0
assert_eq!(out.i, 1.5); // 0.1 * (10.0 + 5.0)
assert_eq!(out.d, -5.0); // -(1.0 * 5.0)
assert_eq!(out.output, 1.5);
let out = pid.next_control_output(11.0);
assert_eq!(out.p, -1.0); // 1.0 * -1.0
assert_eq!(out.i, 1.4); // 0.1 * (10.0 + 5.0 - 1)
assert_eq!(out.d, -6.0); // -(1.0 * 6.0)
assert_eq!(out.output, -5.6);
let out = pid.next_control_output(10.0);
assert_eq!(out.p, 0.0); // 1.0 * 0.0
assert_eq!(out.i, 1.4); // 0.1 * (10.0 + 5.0 - 1.0 + 0.0)
assert_eq!(out.d, 1.0); // -(1.0 * -1.0)
assert_eq!(out.output, 2.4);
}
#[test]
fn f32_and_f64() {
let mut pid32 = Pid::new(2.0f32, 0.0, 0.0, 10.0);
let mut pid64 = Pid::new(2.0f64, 0.0, 0.0, 10.0);
assert_eq!(
pid32.next_control_output(0.0).output,
pid64.next_control_output(0.0).output as f32
);
assert_eq!(
pid32.next_control_output(0.0).output as f64,
pid64.next_control_output(0.0).output
);
}
}
|
#[macro_use] extern crate allegro;
extern crate allegro_font;
extern crate allegro_image;
extern crate libloading;
extern crate game;
use allegro_font::FontAddon;
use allegro_image::ImageAddon;
use libloading::Library;
use game::{State, Platform};
use std::fs;
const FPS: f64 = 60.0;
const SCREEN_WIDTH: i32 = 640;
const SCREEN_HEIGHT: i32 = 480;
struct Application(Library);
impl Application {
fn update(&self, p: &Platform, s: State) -> State {
unsafe {
let f = self.0.get::<fn(&Platform, State) -> State>(b"update\0")
.unwrap_or_else(|error| panic!("failed to get symbol `update`: {}", error));
f(p, s)
}
}
fn render(&self, p: &Platform, s: &State) {
unsafe {
let f = self.0.get::<fn(&Platform, &State)>(b"render\0")
.unwrap_or_else(|error| panic!("failed to get symbol `render`: {}", error));
f(p, s)
}
}
fn handle_event(&self, p: &Platform, s: State, e: allegro::Event) -> State {
unsafe {
let f = self.0.get::<fn(&Platform, State, allegro::Event) -> State>(b"handle_event\0")
.unwrap_or_else(|error| panic!("failed to get symbol `handle_event`: {}", error));
f(p, s, e)
}
}
fn clean_up(&self, s: State) {
unsafe {
let f = self.0.get::<fn(State)>(b"clean_up\0")
.unwrap_or_else(|error| panic!("failed to get symbol `clean_up`: {}", error));
f(s)
}
}
}
const LIB_PATH: &'static str = "../game/target/debug/libgame.dylib";
allegro_main!
{
let core = allegro::Core::init().unwrap();
let mut platform = Platform {
font_addon: FontAddon::init(&core).unwrap_or_else(|msg| panic!(msg)),
image_addon: ImageAddon::init(&core).unwrap_or_else(|msg| panic!(msg)),
core: core,
};
let disp = allegro::Display::new(&platform.core, SCREEN_WIDTH, SCREEN_HEIGHT).unwrap();
disp.set_window_title("Hello, Allegro!");
platform.core.install_keyboard().unwrap();
platform.core.install_mouse().unwrap();
let mut app = Application(Library::new(LIB_PATH).unwrap());
let mut last_modified = fs::metadata(LIB_PATH).unwrap().modified().unwrap();
let mut state = game::State::new(&platform);
let timer = allegro::Timer::new(&platform.core, 1.0 / FPS).unwrap();
let q = allegro::EventQueue::new(&platform.core).unwrap();
q.register_event_source(disp.get_event_source());
q.register_event_source(platform.core.get_keyboard_event_source());
q.register_event_source(platform.core.get_mouse_event_source());
q.register_event_source(timer.get_event_source());
let mut redraw = true;
timer.start();
'main: loop {
if redraw && q.is_empty() {
app.render(&platform, &state);
platform.core.flip_display();
redraw = false;
}
match q.wait_for_event() {
allegro::DisplayClose{..} => break 'main,
allegro::TimerTick{..} => {
if let Ok(Ok(modified)) = fs::metadata(LIB_PATH).map(|m| m.modified()) {
if modified > last_modified {
drop(app);
app = Application(Library::new(LIB_PATH)
.unwrap_or_else(|error| panic!("{}", error)));
last_modified = modified;
}
}
state = app.update(&platform, state);
redraw = true;
},
e => {
state = app.handle_event(&platform, state, e);
},
}
}
println!("Cleaning up...");
app.clean_up(state);
//mem::forget(state);
println!("Bye!");
}
|
use std::borrow::{Borrow, BorrowMut};
use std::cell::RefCell;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::iter::{FromIterator, Once};
use std::ops::{Deref, DerefMut, Range};
use std::rc::Rc;
use std::time::Duration;
use rand::Rng;
use rust_tools::bench::Bench;
use crate::mcts_tree::mcts::{BRANCH_FACTOR, MCTS, TREE_SIZE};
use crate::mcts_tree::mcts::MStats;
use crate::mcts_tree::tree::Tree;
pub struct M2<T> {
id_gen: usize,
arena: Vec<Rc<RefCell<T>>>,
}
impl Tree<NodeId> for M2<Node> {
fn new_node(&mut self, size: usize) -> NodeId {
let id = self.id_gen;
self.id_gen += 1;
let node = Rc::new(RefCell::new(Node::new(id, size)));
//TODO: use the arena strategy
Some(node)
}
fn node_count(&self) -> usize {
self.id_gen
}
fn node_size(&self, node: &NodeId) -> usize {
match node {
None => 0,
Some(n) => n.as_ref().borrow().size(),
}
}
fn display(&self, node: &NodeId) {
log::trace!("display...");
let data = &node.clone().map(|x| x.as_ref().borrow().to_string());
match data {
None => {}
Some(data) => {
println!("{}", data);
}
}
}
fn set_child(&mut self, i: usize, parent: &NodeId, child: &NodeId) {
todo!()
}
}
impl MCTS<NodeId> for M2<Node> {
fn select_from(&mut self, tree: &NodeId) -> NodeId {
match tree {
None => panic!(),
Some(n) => {
if n.as_ref().borrow().data.is_leaf() {
n.as_ref().borrow_mut().data.explored += 1;
tree.clone()
} else {
let mut rng = rand::thread_rng();
n.as_ref().borrow_mut().data.explored += 1;
let childs = n.as_ref().borrow().children.len();
let index = rng.gen_range(0..childs);
self.select_from(&n.as_ref().borrow().children[index])
}
}
}
}
fn expand(&mut self, node: &NodeId, max_children: usize) {
match &node {
None => panic!(),
Some(node) => {
let nn = node.as_ref().borrow().children.len();
for i in 0..nn {
let child = self.new_node(max_children);
node.as_ref().borrow_mut().set_child(i, child);
}
}
}
}
}
impl M2<Node> {
pub fn new() -> M2<Node> {
M2 {
id_gen: 0,
arena: Vec::new(),
}
}
}
//TODO: change to Rc<RefCell<Option<Node>>> ?? (this would make the data easily clonable)
pub type NodeId = Option<Rc<RefCell<Node>>>;
#[derive(Clone, Debug)]
pub struct Node {
id: usize,
data: MStats,
children: Vec<NodeId>,
}
impl Node {
pub fn new(id: usize, size: usize) -> Node {
let mut stats = MStats::new();
stats.leafs = size;
Node {
id,
data: stats,
children: vec![None; size],
}
}
fn size(&self) -> usize {
let cpt: usize = self
.children
.iter()
.map(|c| match c {
None => 1,
Some(n) => n.as_ref().borrow().size(),
})
.sum();
return cpt + 1;
}
fn set_child(&mut self, i: usize, child: NodeId) {
// update child depth
match &child {
None => {}
Some(n) => {
n.as_ref().borrow_mut().data.depth = self.data.depth + 1;
// n.as_ref().borrow_mut().depth = self.depth + 1;
}
}
match &self.children[i] {
None => {
self.data.leafs -= 1;
}
_ => {}
}
self.children[i] = child;
}
}
impl Display for Node {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let tab = String::from_iter(vec![' '; self.data.depth].iter());
write!(f, "{}{}:{}", tab, self.id, self.data.leafs);
if !(self.data.is_leaf()) {
for child in self.children.iter() {
match child {
None => write!(f, "X"),
Some(c) => write!(f, "\n{}{}", tab, c.as_ref().borrow()),
};
}
}
Ok(())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.