text stringlengths 8 4.13M |
|---|
//! YAML Functions
//! These functions can be used to allow an object to perform YAML actions.
use std::error::Error;
use uuid::Uuid;
/// Convert an object that implements Serialize to a String
pub fn object_to_string<T>(object: (Uuid, T)) -> Result<String, Box<dyn Error>>
where
T: serde::ser::Serialize,
{
Ok(serde_yaml::to_string(&object)?)
}
/// Convert objects that implement Serialize to a String
pub fn objects_to_string<T>(objects: &[(Uuid, T)]) -> Result<String, Box<dyn Error>>
where
T: serde::ser::Serialize,
{
Ok(serde_yaml::to_string(&objects)?)
}
/// Convert a YAML string into an object that implement Deserialize
pub fn string_to_object<T>(string: &str) -> Result<(Uuid, T), Box<dyn Error>>
where
T: serde::de::DeserializeOwned,
{
Ok(serde_yaml::from_str(string)?)
}
/// Convert a YAML string into objects that implement Deserialize
pub fn string_to_objects<T>(string: &str) -> Result<Vec<(Uuid, T)>, Box<dyn Error>>
where
T: serde::de::DeserializeOwned,
{
Ok(serde_yaml::from_str(string)?)
}
|
// Copyright 2019 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause
/// Adds some variations of `Add` given a definition for `Add` that takes references. i.e. assuming we have
/// ```ignore
/// impl<'a, 'b> Add<&'b Foo> for &'a Foo {
/// type Output = Foo;
/// fn add(self, rhs: &'b rhs) -> Foo {...}
/// }
/// ```
/// which allows `&foo1 + &foo2` This macro adds definitions for
/// * `&foo1 + foo2`
/// * `foo1 + &foo2`
/// * `foo1 + foo2`
macro_rules! define_add_variants {
(LHS = $lhs:ty, RHS = $rhs:ty, Output = $out:ty) => {
impl<'b> Add<&'b $rhs> for $lhs {
type Output = $out;
fn add(self, rhs: &'b $rhs) -> $out {
&self + rhs
}
}
impl<'a> Add<$rhs> for &'a $lhs {
type Output = $out;
fn add(self, rhs: $rhs) -> $out {
self + &rhs
}
}
impl Add<$rhs> for $lhs {
type Output = $out;
fn add(self, rhs: $rhs) -> $out {
&self + &rhs
}
}
};
}
/// Add variations for `Sub` definitions, similar to those for `Add`
macro_rules! define_sub_variants {
(LHS = $lhs:ty, RHS = $rhs:ty, Output = $out:ty) => {
impl<'b> Sub<&'b $rhs> for $lhs {
type Output = $out;
fn sub(self, rhs: &'b $rhs) -> $out {
&self - rhs
}
}
impl<'a> Sub<$rhs> for &'a $lhs {
type Output = $out;
fn sub(self, rhs: $rhs) -> $out {
self - &rhs
}
}
impl Sub<$rhs> for $lhs {
type Output = $out;
fn sub(self, rhs: $rhs) -> $out {
&self - &rhs
}
}
};
}
/// Add variations for `Mul` definitions, similar to those for `Add`
macro_rules! define_mul_variants {
(LHS = $lhs:ty, RHS = $rhs:ty, Output = $out:ty) => {
impl<'b> Mul<&'b $rhs> for $lhs {
type Output = $out;
fn mul(self, rhs: &'b $rhs) -> $out {
&self * rhs
}
}
impl<'a> Mul<$rhs> for &'a $lhs {
type Output = $out;
fn mul(self, rhs: $rhs) -> $out {
self * &rhs
}
}
impl Mul<$rhs> for $lhs {
type Output = $out;
fn mul(self, rhs: $rhs) -> $out {
&self * &rhs
}
}
};
}
|
#[doc = "Reader of register SPISR2"]
pub type R = crate::R<u32, super::SPISR2>;
#[doc = "Reader of field `SPISR2`"]
pub type SPISR2_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - shared peripheral interrupt"]
#[inline(always)]
pub fn spisr2(&self) -> SPISR2_R {
SPISR2_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
extern crate der_parser;
extern crate nom;
extern crate rusticata_macros;
extern crate x509_parser;
use std::io::Cursor;
use x509_parser::parse_x509_der;
use x509_parser::pem::{pem_to_der, Pem};
static IGCA_PEM: &[u8] = include_bytes!("../assets/IGC_A.pem");
#[test]
fn test_x509_parse_pem() {
let (rem, pem) = pem_to_der(IGCA_PEM).expect("PEM parsing failed");
// println!("{:?}", pem);
assert!(rem.is_empty());
assert_eq!(pem.label, String::from("CERTIFICATE"));
//
// now check that the content is indeed a certificate
let (rem, crt) = parse_x509_der(&pem.contents).expect("X.509 parsing failed");
// println!("res: {:?}", res);
assert!(rem.is_empty());
assert_eq!(crt.tbs_certificate.version, 2);
}
#[test]
fn test_pem_read() {
let reader = Cursor::new(IGCA_PEM);
let (pem, bytes_read) = Pem::read(reader).expect("Reading PEM failed");
// println!("{:?}", pem);
assert_eq!(bytes_read, IGCA_PEM.len());
assert_eq!(pem.label, String::from("CERTIFICATE"));
//
// now check that the content is indeed a certificate
let x509 = pem.parse_x509().expect("X.509: decoding DER failed");
assert_eq!(x509.tbs_certificate.version, 2);
}
#[test]
fn test_pem_not_pem() {
let bytes = vec![0x1, 0x2, 0x3, 0x4, 0x5];
let reader = Cursor::new(bytes);
let res = Pem::read(reader);
assert!(res.is_err());
}
static NO_END: &[u8] = include_bytes!("../assets/no_end.pem");
#[test]
fn test_pem_no_end() {
let reader = Cursor::new(NO_END);
let res = Pem::read(reader);
assert!(res.is_err());
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use types::U256;
pub const BLOCK_TIME_SEC: u32 = 20;
pub const BLOCK_WINDOW: u64 = 24;
use anyhow::Result;
use logger::prelude::*;
use traits::ChainReader;
pub fn difficult_1_target() -> U256 {
U256::max_value()
}
pub fn current_hash_rate(target: &[u8]) -> u64 {
// current_hash_rate = (difficult_1_target/target_current) * difficult_1_hash/block_per_esc
let target_u256: U256 = target.into();
(difficult_1_target() / target_u256).low_u64() / (BLOCK_TIME_SEC as u64)
}
/// Get the target of next pow work
pub fn get_next_work_required(chain: &dyn ChainReader) -> Result<U256> {
let mut current_header = chain.current_header();
if current_header.number <= 1 {
return Ok(difficult_to_target(current_header.difficulty));
}
let blocks = {
let mut blocks: Vec<BlockInfo> = vec![];
let calculate_window = if current_header.number < BLOCK_WINDOW {
current_header.number
} else {
BLOCK_WINDOW
};
blocks.push(BlockInfo {
timestamp: current_header.timestamp,
target: difficult_to_target(current_header.difficulty),
});
for _ in 1..calculate_window {
match chain.get_header(current_header.parent_hash)? {
Some(header) => {
// Skip genesis
if header.number == 0 {
break;
}
blocks.push(BlockInfo {
timestamp: header.timestamp,
target: difficult_to_target(header.difficulty),
});
current_header = header;
}
None => {
anyhow::bail!("Invalid block, header not exist");
}
}
}
blocks
};
let mut avg_time: u64 = 0;
let mut avg_target = U256::zero();
let mut latest_block_index = 0;
let block_n = blocks.len() - 1;
while latest_block_index < block_n {
let solve_time =
blocks[latest_block_index].timestamp - blocks[latest_block_index + 1].timestamp;
avg_time += solve_time * (block_n - latest_block_index) as u64;
debug!(
"solve_time:{:?}, avg_time:{:?}, block_n:{:?}",
solve_time, avg_time, block_n
);
avg_target = avg_target + blocks[latest_block_index].target / block_n.into();
latest_block_index += 1
}
avg_time /= (block_n as u64) * ((block_n + 1) as u64) / 2;
if avg_time == 0 {
avg_time = 1
}
let time_plan = BLOCK_TIME_SEC;
// new_target = avg_target * avg_time_used/time_plan
// avoid the target increase or reduce too fast.
let new_target =
if let Some(new_target) = (avg_target / time_plan.into()).checked_mul(avg_time.into()) {
if new_target / 2.into() > avg_target {
debug!("target increase too fast, limit to 2 times");
avg_target * 2
} else if new_target < avg_target / 2.into() {
debug!("target reduce too fase, limit to 2 times");
avg_target / 2.into()
} else {
new_target
}
} else {
debug!("target large than max value, set to 1_difficulty");
difficult_1_target()
};
debug!(
"avg_time:{:?}s, time_plan:{:?}s, target: {:?}",
avg_time, time_plan, new_target
);
Ok(new_target)
}
pub fn target_to_difficulty(target: U256) -> U256 {
difficult_1_target() / target
}
pub fn difficult_to_target(difficulty: U256) -> U256 {
difficult_1_target() / difficulty
}
#[derive(Clone)]
pub struct BlockInfo {
pub timestamp: u64,
pub target: U256,
}
|
use super::*;
use std::io::Read;
pub struct TableSection<'a> {
pub count: u32,
pub entries_raw: &'a [u8],
}
pub struct TableEntryIterator<'a> {
count: u32,
iter: &'a [u8]
}
pub struct TableEntry {
pub ty: u8,
pub limits: ResizableLimits,
}
impl<'a> TableSection<'a> {
pub fn entries(&self) -> TableEntryIterator<'a> {
TableEntryIterator {
count: self.count,
iter: self.entries_raw
}
}
}
impl<'a> Iterator for TableEntryIterator<'a> {
type Item = Result<TableEntry, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 {
return None
}
self.count -= 1;
let mut ty = [0; 1];
try_opt!((&mut self.iter).read_exact(&mut ty));
let limits = try_opt!(ResizableLimits::parse(&mut self.iter));
Some(Ok(TableEntry {
ty: ty[0],
limits: limits,
}))
}
}
|
use std::cmp::Ordering;
use std::collections::HashMap;
fn main() {
main_ordering();
main_account();
}
fn main_ordering() {
assert_eq!(Ordering::Less, compare(2, 3));
}
fn compare(n: i32, m: i32) -> Ordering {
if n < m {
Ordering::Less
} else if n > m {
Ordering::Greater
} else {
Ordering::Equal
}
}
enum TimeUnit {
Seconds,
Minutes,
Hours,
Days,
Months,
Years,
}
impl TimeUnit {
fn plural(&self) -> &'static str {
match self {
TimeUnit::Seconds => "seconds",
TimeUnit::Minutes => "minutes",
TimeUnit::Hours => "hours",
TimeUnit::Days => "days",
TimeUnit::Months => "months",
TimeUnit::Years => "years",
}
}
fn singular(self) -> &'static str {
self.plural().trim_end_matches('s')
}
}
enum RoughTime {
InThePast(TimeUnit, u32),
JustNow,
InTheFuture(TimeUnit, u32),
}
fn rough_time_to_english(rt: &RoughTime) -> String {
match rt {
RoughTime::InThePast(units, counts) =>
format!("{} {} ago", counts, units.plural()),
RoughTime::JustNow =>
format!("just now"),
RoughTime::InTheFuture(units, count) =>
format!("{} {} from now", count, units.plural())
}
}
enum Json {
Null,
Boolean(bool),
Number(f64),
String(String),
Array(Vec<Json>),
Object(Box<HashMap<String, Json>>),
}
enum BinaryTree<T> {
Empty,
NonEmpty(Box<TreeNode<T>>),
}
struct TreeNode<T> {
element: T,
left: BinaryTree<T>,
right: BinaryTree<T>,
}
impl<T: Ord> BinaryTree<T> {
fn add(&mut self, value: T) {
match *self {
BinaryTree::Empty =>
*self = BinaryTree::NonEmpty(Box::new(TreeNode {
element: value,
left: BinaryTree::Empty,
right: BinaryTree::Empty,
})),
BinaryTree::NonEmpty(ref mut node) =>
if value <= node.element {
node.left.add(value);
} else {
node.right.add(value);
}
}
}
}
#[derive(Debug)]
struct Account {
name: String,
language: String,
id: usize,
}
fn main_account() {
let account = Account { name: "Doe".to_string(), language: "fr".to_string(), id: 0 };
match account {
Account { ref name, ref language, .. } => {
println!("greet {} {}", &name, &language);
println!("show_settings {:?}", account)
}
}
let r = &account;
match r {
&Account { ref name, .. } => println!("borrow name {}", name)
}
let s = "cat".to_string();
match s.chars().by_ref().into_iter().peekable().peek() {
Some(&c) => println!("char {}", c),
None => println!("end of chars"),
};
let n = 1;
match n {
0 => println!("0"),
1 | 2 => println!("1 or 2"),
x @ 3...5 => println!("3..5 = {}", x),
x if x / 2 == 0 => println!("even"),
_ => println!("other"),
}
let mut tree = BinaryTree::Empty;
tree.add("Mercury");
tree.add("Venus");
} |
use log::*;
use crate::bus::ModuleMsgEnum;
use crate::system::SystemModules;
use msgbus::{MsgBusHandle, Message};
use serde::{Serialize, Deserialize};
use tokio::sync::mpsc::Receiver;
use tokio::sync::{Mutex};
use std::sync::Arc;
mod terminal;
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct CliConfiguration {
}
impl Default for CliConfiguration {
fn default() -> Self {
Self {
}
}
}
#[derive(Clone)]
pub struct CliManager {
bus_handle: MsgBusHandle<SystemModules, ModuleMsgEnum>,
rx: Arc<Mutex<Receiver<Message<ModuleMsgEnum>>>>,
cli_conf: CliConfiguration,
}
impl CliManager {
pub async fn new(mut bus_handle: MsgBusHandle<SystemModules, ModuleMsgEnum>) -> Self {
let rx = bus_handle.register(SystemModules::CLI).await.unwrap();
Self {
rx: Arc::new(Mutex::new(rx)),
bus_handle,
cli_conf: CliConfiguration::default(),
}
}
pub async fn start(self) {
debug!("In CliManager.start()");
let bh = self.bus_handle.clone();
// let orig_conf = crate::conf::get_cli_conf(&mut bh.clone()).await;
// let clim = self.clone();
let _handle = tokio::task::spawn_blocking(move || self::terminal::start(bh.clone()));
let rx = self.rx.clone();
while let Some(msg) = rx.lock().await.recv().await {
match msg {
// Message::Message(ModuleMsgEnum::MsgConf(crate::conf::ConfMessage::DataConfigCli(conf_cli))) => {
// let clim = self.clone();
// TODO Think if we need to do something
// },
_ => {}
}
}
}
}
|
use crate::{qs_params, session::CallbackProvider, Messages};
use crate::{MarketSession, Product, SecurityType, Session, Store};
use anyhow::Result;
use http::Method;
use std::sync::Arc;
use strum::EnumString;
pub struct Api<T: Store> {
session: Arc<Session<T>>,
}
impl<T> Api<T>
where
T: Store,
{
pub fn new(session: Arc<Session<T>>) -> Self {
Self { session }
}
pub async fn list(
&self,
account_id_key: &str,
params: ListOrdersRequest,
callbacks: impl CallbackProvider,
) -> Result<OrdersResponse> {
let orders: serde_json::Value = self
.session
.send(
Method::GET,
format!("/v1/accounts/{}/orders", account_id_key),
qs_params(¶ms)?,
callbacks,
)
.await?;
debug!("orders json: {}", serde_json::to_string_pretty(&orders)?);
Ok(serde_json::from_value(orders.get("OrdersResponse").unwrap().clone())?)
}
pub async fn preview(
&self,
account_id_key: &str,
params: PreviewOrderRequest,
callbacks: impl CallbackProvider,
) -> Result<PreviewOrderResponse> {
let preview: serde_json::Value = self
.session
.clone()
.send(
Method::POST,
format!("/v1/accounts/{}/orders/preview", account_id_key),
Some(params),
callbacks,
)
.await?;
debug!("preview json: {}", serde_json::to_string_pretty(&preview)?);
Ok(serde_json::from_value(
preview.get("PreviewOrderResponse").unwrap().clone(),
)?)
}
pub async fn place(
&self,
account_id_key: &str,
params: PlaceOrderRequest,
callbacks: impl CallbackProvider,
) -> Result<PlaceOrderResponse> {
let place: serde_json::Value = self
.session
.clone()
.send(
Method::POST,
format!("/v1/accounts/{}/orders/place", account_id_key),
Some(params),
callbacks,
)
.await?;
debug!("placed order json: {}", serde_json::to_string_pretty(&place)?);
Ok(serde_json::from_value(
place.get("PlaceOrderResponse").unwrap().clone(),
)?)
}
pub async fn cancel(
&self,
account_id_key: &str,
params: CancelOrderRequest,
callback: impl CallbackProvider,
) -> Result<CancelOrderResponse> {
let cancellation: serde_json::Value = self
.session
.clone()
.send(
Method::PUT,
format!("/v1/accounts/{}/orders/cancel", account_id_key),
Some(params),
callback,
)
.await?;
debug!("cancellation json: {}", serde_json::to_string_pretty(&cancellation)?);
Ok(serde_json::from_value(
cancellation.get("CancelOrderResponse").unwrap().clone(),
)?)
}
pub async fn change_preview(
&self,
account_id_key: &str,
order_id: &str,
params: PreviewOrderRequest,
callback: impl CallbackProvider,
) -> Result<PreviewOrderResponse> {
let preview: serde_json::Value = self
.session
.clone()
.send(
Method::PUT,
format!("/v1/accounts/{}/orders/{}/change/preview", account_id_key, order_id),
Some(params),
callback,
)
.await?;
debug!("changed preview json: {}", serde_json::to_string_pretty(&preview)?);
Ok(serde_json::from_value(
preview.get("PreviewOrderResponse").unwrap().clone(),
)?)
}
pub async fn change_order(
&self,
account_id_key: &str,
order_id: &str,
params: PlaceOrderRequest,
callback: impl CallbackProvider,
) -> Result<PlaceOrderResponse> {
let place: serde_json::Value = self
.session
.clone()
.send(
Method::PUT,
format!("/v1/accounts/{}/orders/{}/change/place", account_id_key, order_id),
Some(params),
callback,
)
.await?;
debug!("changed placed order json: {}", serde_json::to_string_pretty(&place)?);
Ok(serde_json::from_value(
place.get("PlaceOrderResponse").unwrap().clone(),
)?)
}
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct CancelOrderRequest {
pub order_id: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct CancelOrderResponse {
pub account_id: String,
pub order_id: i64,
pub cancel_time: i64,
#[serde(rename = "Messages", skip_serializing_if = "Messages::is_empty")]
pub messages: Messages,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct PlaceOrderRequest {
pub order_type: Option<OrderType>,
pub client_order_id: String,
#[serde(rename = "Order", skip_serializing_if = "Vec::is_empty")]
pub order: Vec<OrderDetail>,
#[serde(rename = "PreviewIds", skip_serializing_if = "Vec::is_empty")]
pub preview_ids: Vec<PreviewId>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct PlaceOrderResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub order_type: Option<OrderType>,
#[serde(skip_serializing_if = "Messages::is_empty")]
pub message_list: Messages,
pub total_order_value: f64,
pub total_commission: f64,
pub order_id: i64,
#[serde(rename = "Order", skip_serializing_if = "Vec::is_empty")]
pub order: Vec<OrderDetail>,
pub dst_flag: bool,
pub account_id: String,
pub option_level_cd: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub margin_level_cd: Option<MarginLevelCd>,
#[serde(skip_serializing_if = "Option::is_none")]
pub portfolio_margin: Option<PortfolioMargin>,
pub is_employee: bool,
pub commission_msg: String,
#[serde(rename = "OrderIds", skip_serializing_if = "Vec::is_empty")]
pub order_ids: Vec<OrderId>,
#[serde(rename = "Disclosure", skip_serializing_if = "Option::is_none")]
pub disclosure: Option<Disclosure>,
pub placed_time: i64,
pub client_order_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct OrderId {
pub order_id: i64,
pub cash_margin: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct PreviewOrderRequest {
pub order_type: Option<OrderType>,
pub client_order_id: String,
#[serde(rename = "Order", skip_serializing_if = "Vec::is_empty")]
pub order: Vec<OrderDetail>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct PreviewOrderResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub order_id: Option<OrderType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message_list: Option<Messages>,
pub total_order_value: f64,
pub total_commission: f64,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub order: Vec<OrderDetail>,
#[serde(rename = "PreviewIds", skip_serializing_if = "Vec::is_empty")]
pub preview_ids: Vec<PreviewId>,
pub preview_time: i64,
pub dst_flag: bool,
pub account_id: String,
pub option_level_cd: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub margin_level_cd: Option<MarginLevelCd>,
#[serde(skip_serializing_if = "Option::is_none")]
pub portfolio_margin: Option<PortfolioMargin>,
pub is_employee: bool,
pub commission_message: String,
#[serde(rename = "Disclosure", skip_serializing_if = "Option::is_none")]
pub disclosure: Option<Disclosure>,
pub client_order_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub margin_bp_details: Option<MarginBuyingPowerDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cash_bp_details: Option<CashBuyingPowerDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dt_bp_details: Option<DtBuyingPowerDetails>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct OrderBuyPowerEffect {
pub current_bp: f64,
pub current_oor: f64,
pub current_net_bp: f64,
pub current_order_impact: f64,
pub net_bp: f64,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct CashBuyingPowerDetails {
#[serde(rename = "settledUnsettled", skip_serializing_if = "Option::is_none")]
pub settled_unsettled: Option<OrderBuyPowerEffect>,
#[serde(skip_serializing_if = "Option::is_none")]
pub settled: Option<OrderBuyPowerEffect>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct MarginBuyingPowerDetails {
#[serde(rename = "nonMarginable", skip_serializing_if = "Option::is_none")]
pub non_marginable: Option<OrderBuyPowerEffect>,
#[serde(skip_serializing_if = "Option::is_none")]
pub marginable: Option<OrderBuyPowerEffect>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct DtBuyingPowerDetails {
#[serde(rename = "nonMarginable", skip_serializing_if = "Option::is_none")]
pub non_marginable: Option<OrderBuyPowerEffect>,
#[serde(skip_serializing_if = "Option::is_none")]
pub marginable: Option<OrderBuyPowerEffect>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Disclosure {
pub eh_disclosure_flag: bool,
pub ah_disclosure_flag: bool,
pub conditional_disclosure_flag: bool,
pub ao_disclosure_flag: bool,
#[serde(rename = "mfFLConsent")]
pub mf_fl_consent: bool,
#[serde(rename = "mfEOConsent")]
pub mf_eo_consent: bool,
}
#[derive(Debug, Deserialize, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct PortfolioMargin {
pub house_excess_equity_new: f64,
pub pm_eligible: f64,
pub house_excess_equity_curr: f64,
pub house_excess_equity_change: f64,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct PreviewId {
pub preview_id: i64,
pub cash_margin: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct ListOrdersRequest {
pub marker: Option<String>,
pub count: Option<usize>,
pub status: Option<OrderStatus>,
pub from_date: Option<String>,
pub to_date: Option<String>,
pub symbol: Option<Vec<String>>,
pub security_type: Option<SecurityType>,
pub transaction_type: Option<TransactionType>,
pub market_session: Option<MarketSession>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct OrdersResponse {
pub marker: String,
pub next: String,
#[serde(rename = "Order", skip_serializing_if = "Vec::is_empty")]
pub order: Vec<Order>,
#[serde(rename = "Messages", skip_serializing_if = "Messages::is_empty")]
pub messages: Messages,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Order {
pub order_id: i64,
pub details: String,
pub order_type: String,
pub total_order_value: f64,
pub total_commission: f64,
#[serde(rename = "OrderDetail", skip_serializing_if = "Vec::is_empty")]
pub order_detail: Vec<OrderDetail>,
#[serde(rename = "Events")]
pub events: Events,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct OrderDetail {
pub order_number: isize,
pub account_id: String,
pub preview_time: i64,
pub placed_time: i64,
pub executed_time: i64,
pub order_value: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<OrderStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_type: Option<OrderType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_term: Option<OrderTerm>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_type: Option<PriceType>,
pub price_value: String,
pub limit_price: f64,
pub stop_price: f64,
pub stop_limit_price: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub offset_type: Option<OffsetType>,
pub offset_value: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub market_session: Option<MarketSession>,
pub routing_destination: RoutingDestination,
pub bracketed_limit_price: f64,
pub initial_stop_price: f64,
pub trail_price: f64,
pub trigger_price: f64,
pub condition_price: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub condition_type: Option<ConditionType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub condition_follow_price: Option<ConditionFollowPrice>,
pub condition_security_type: String,
pub replaced_by_order_id: isize,
pub replaces_order_id: isize,
pub all_or_none: bool,
pub preview_id: i64,
#[serde(rename = "Instrument", skip_serializing_if = "Vec::is_empty")]
pub instrument: Vec<Instrument>,
#[serde(rename = "messages", skip_serializing_if = "Option::is_none")]
pub messages: Option<Messages>,
pub pre_clearance_code: String,
pub override_restricted_cd: i32,
pub investment_amount: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub position_quantity: Option<PositionQuantity>,
pub aip_flag: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub eq_qual: Option<EgQual>,
#[serde(skip_serializing_if = "Option::is_none")]
pub re_invest_option: Option<ReInvestOption>,
pub estimated_commission: f64,
pub estimated_fees: f64,
pub estimated_total_amount: f64,
pub net_price: f64,
pub net_bid: f64,
pub net_ask: f64,
pub gcd: i32,
pub ratio: String,
pub mfprice_type: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Event {
pub name: EventName,
pub date_time: i64,
pub order_number: isize,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub instrument: Vec<Instrument>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Instrument {
pub product: Product,
pub symbol_description: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_action: Option<OrderAction>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity_type: Option<QuantityType>,
pub quantity: f64,
pub cancel_quantity: f64,
pub ordered_quantity: f64,
pub filled_quantity: f64,
pub average_execution_price: f64,
pub estimated_commission: f64,
pub estimated_fees: f64,
pub bid: f64,
pub ask: f64,
pub lastprice: f64,
pub currency: Currency,
#[serde(rename = "Lots")]
pub lots: Lots,
#[serde(rename = "MFQuantity")]
pub mf_quantity: MFQuantity,
pub osi_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub mf_transaction: Option<MFTransaction>,
pub reserve_order: bool,
pub reserve_quantity: f64,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct MFQuantity {
pub cash: f64,
pub margin: f64,
pub cusip: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Lots {
#[serde(rename = "Lot", skip_serializing_if = "Vec::is_empty")]
pub lot: Vec<Lot>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Lot {
pub id: i64,
pub size: f64,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "UPPERCASE")]
pub enum Currency {
#[serde(rename = "USD")]
Usd,
#[serde(rename = "EUR")]
Eur,
#[serde(rename = "GBP")]
Gbp,
#[serde(rename = "HKD")]
Hkd,
#[serde(rename = "JPY")]
Jpy,
#[serde(rename = "CAD")]
Cad,
}
impl Default for Currency {
fn default() -> Self {
Currency::Usd
}
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum QuantityType {
#[serde(rename = "QUANTITY")]
Quantity,
#[serde(rename = "DOLLAR")]
Dollar,
#[serde(rename = "ALL_I_OWN")]
AllIOwn,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum MFTransaction {
#[serde(rename = "BUY")]
Buy,
#[serde(rename = "SELL")]
Sell,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum OrderAction {
#[serde(rename = "BUY")]
Buy,
#[serde(rename = "SELL")]
Sell,
#[serde(rename = "BUY_TO_COVER")]
BuyToCover,
#[serde(rename = "SELL_SHORT")]
SellShort,
#[serde(rename = "BUY_OPEN")]
BuyOpen,
#[serde(rename = "BUY_CLOSE")]
BuyClose,
#[serde(rename = "SELL_OPEN")]
SellOpen,
#[serde(rename = "SELL_CLOSE")]
SellClose,
#[serde(rename = "EXCHANGE")]
Exchange,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum EventName {
#[serde(rename = "UNSPECIFIED")]
Unspecified,
#[serde(rename = "ORDER_PLACED")]
OrderPlaced,
#[serde(rename = "SENT_TO_CMS")]
SentToCms,
#[serde(rename = "SENT_TO_MARKET")]
SentToMarket,
#[serde(rename = "MARKET_SENT_ACKNOWLEDGED")]
MarketSentAcknowledged,
#[serde(rename = "CANCEL_REQUESTED")]
CancelRequested,
#[serde(rename = "ORDER_MODIFIED")]
OrderModified,
#[serde(rename = "ORDER_SENT_TO_BROKER_REVIEW")]
OrderSentToBrokerReview,
#[serde(rename = "SYSTEM_REJECTED")]
SystemRejected,
#[serde(rename = "ORDER_REJECTED")]
OrderRejected,
#[serde(rename = "ORDER_CANCELLED")]
OrderCancelled,
#[serde(rename = "CANCEL_REJECTED")]
CancelRejected,
#[serde(rename = "ORDER_EXPIRED")]
OrderExpired,
#[serde(rename = "ORDER_EXECUTED")]
OrderExecuted,
#[serde(rename = "ORDER_ADJUSTED")]
OrderAdjusted,
#[serde(rename = "ORDER_REVERSED")]
OrderReversed,
#[serde(rename = "REVERSE_CANCELLATION")]
ReverseCancellation,
#[serde(rename = "REVERSE_EXPIRATION")]
ReverseExpiration,
#[serde(rename = "OPTION_POSITION_ASSIGNED")]
OptionPositionAssigned,
#[serde(rename = "OPEN_ORDER_ADJUSTED")]
OpenOrderAdjusted,
#[serde(rename = "CA_CANCELLED")]
CaCancelled,
#[serde(rename = "CA_BOOKED")]
CaBooked,
#[serde(rename = "IPO_ALLOCATED")]
IpoAllocated,
#[serde(rename = "DONE_TRADE_EXECUTED")]
DoneTradeExecuted,
#[serde(rename = "REJECTION_REVERSAL")]
RejectionReversal,
}
impl Default for EventName {
fn default() -> Self {
EventName::Unspecified
}
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Events {
#[serde(rename = "Events", skip_serializing_if = "Vec::is_empty")]
pub event: Vec<Event>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum OrderStatus {
#[serde(rename = "OPEN")]
Open,
#[serde(rename = "EXECUTED")]
Executed,
#[serde(rename = "CANCELLED")]
Cancelled,
#[serde(rename = "INDIVIDUAL_FILLS")]
IndividualFills,
#[serde(rename = "CANCEL_REQUESTED")]
CancelRequested,
#[serde(rename = "EXPIRED")]
Expired,
#[serde(rename = "REJECTED")]
Rejected,
#[serde(rename = "PARTIAL")]
Partial,
#[serde(rename = "DO_NOT_EXERCISE")]
DoNotExercise,
#[serde(rename = "DONE_TRADE_EXECUTED")]
DoneTradeExecuted,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum TransactionType {
#[serde(rename = "ATNM")]
Atnm,
#[serde(rename = "BUY")]
Buy,
#[serde(rename = "SELL")]
Sell,
#[serde(rename = "SELL_SHORT")]
SellShort,
#[serde(rename = "BUY_TO_COVER")]
BuyToCover,
#[serde(rename = "MF_EXCHANGE")]
MfExchange,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum OrderTerm {
#[serde(rename = "GOOD_UNTIL_CANCEL")]
GoodUntilCancel,
#[serde(rename = "GOOD_FOR_DAY")]
GoodForDay,
#[serde(rename = "GOOD_TILL_DATE")]
GoodTillDate,
#[serde(rename = "IMMEDIATE_OR_CANCEL")]
ImmediateOrCancel,
#[serde(rename = "FILL_OR_KILL")]
FillOrKill,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum OrderType {
#[serde(rename = "EQ")]
Eq,
#[serde(rename = "OPTN")]
Optn,
#[serde(rename = "SPREADS")]
Spreads,
#[serde(rename = "BUY_WRITES")]
BuyWrites,
#[serde(rename = "BUTTERFLY")]
Butterfly,
#[serde(rename = "IRON_BUTTERFLY")]
IronButterfly,
#[serde(rename = "CONDOR")]
Condor,
#[serde(rename = "IRON_CONDOR")]
IronCondor,
#[serde(rename = "MF")]
Mf,
#[serde(rename = "MMF")]
Mmf,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum PriceType {
#[serde(rename = "MARKET")]
Market,
#[serde(rename = "LIMIT")]
Limit,
#[serde(rename = "STOP")]
Stop,
#[serde(rename = "STOP_LIMIT")]
StopLimit,
#[serde(rename = "TRAILING_STOP_CNST_BY_LOWER_TRIGGER")]
TrailingStopCnstByLowerTrigger,
#[serde(rename = "UPPER_TRIGGER_BY_TRAILING_STOP_CNST")]
UpperTriggerByTrailingStopCnst,
#[serde(rename = "TRAILING_STOP_PRCT_BY_LOWER_TRIGGER")]
TrailingStopPrctByLowerTrigger,
#[serde(rename = "UPPER_TRIGGER_BY_TRAILING_STOP_PRCT")]
UpperTriggerByTrailingStopPrct,
#[serde(rename = "TRAILING_STOP_CNST")]
TrailingStopCnst,
#[serde(rename = "TRAILING_STOP_PRCT")]
TrailingStopPrct,
#[serde(rename = "HIDDEN_STOP")]
HiddenStop,
#[serde(rename = "HIDDEN_STOP_BY_LOWER_TRIGGER")]
HiddenStopByLowerTrigger,
#[serde(rename = "UPPER_TRIGGER_BY_HIDDEN_STOP")]
UpperTriggerByHiddenStop,
#[serde(rename = "NET_DEBIT")]
NetDebit,
#[serde(rename = "NET_CREDIT")]
NetCredit,
#[serde(rename = "NET_EVEN")]
NetEven,
#[serde(rename = "MARKET_ON_OPEN")]
MarketOnOpen,
#[serde(rename = "MARKET_ON_CLOSE")]
MarketOnClose,
#[serde(rename = "LIMIT_ON_OPEN")]
LimitOnOpen,
#[serde(rename = "LIMIT_ON_CLOSE")]
LimitOnClose,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum OffsetType {
#[serde(rename = "TRAILING_STOP_CNST")]
TrailingStopCnst,
#[serde(rename = "TRAILING_STOP_PRCT")]
TrailingStopPrct,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum RoutingDestination {
#[serde(rename = "AUTO")]
Auto,
#[serde(rename = "AMEX")]
Amex,
#[serde(rename = "BOX")]
Box,
#[serde(rename = "CBOE")]
Cboe,
#[serde(rename = "ISE")]
Ise,
#[serde(rename = "NOM")]
Nom,
#[serde(rename = "NYSE")]
Nyse,
#[serde(rename = "PHX")]
Phx,
}
impl Default for RoutingDestination {
fn default() -> Self {
RoutingDestination::Auto
}
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum ConditionType {
#[serde(rename = "CONTINGENT_GTE")]
Gte,
#[serde(rename = "CONTINGENT_LTE")]
Lte,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum ConditionFollowPrice {
#[serde(rename = "ASK")]
Ask,
#[serde(rename = "BID")]
Bid,
#[serde(rename = "LAST")]
Last,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum PositionQuantity {
#[serde(rename = "ENTIRE_POSITION")]
EntirePosition,
#[serde(rename = "CASH")]
Cash,
#[serde(rename = "MARGIN")]
Margin,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum EgQual {
#[serde(rename = "EG_QUAL_UNSPECIFIED")]
EgQualUnspecified,
#[serde(rename = "EG_QUAL_QUALIFIED")]
EgQualQualified,
#[serde(rename = "EG_QUAL_NOT_IN_FORCE")]
EgQualNotInForce,
#[serde(rename = "EG_QUAL_NOT_A_MARKET_ORDER")]
EgQualNotAMarketOrder,
#[serde(rename = "EG_QUAL_NOT_AN_ELIGIBLE_SECURITY")]
EgQualNotAnEligibleSecurity,
#[serde(rename = "EG_QUAL_INVALID_ORDER_TYPE")]
EgQualInvalidOrderType,
#[serde(rename = "EG_QUAL_SIZE_NOT_QUALIFIED")]
EgQualSizeNotQualified,
#[serde(rename = "EG_QUAL_OUTSIDE_GUARANTEED_PERIOD")]
EgQualOutsideGuaranteedPeriod,
#[serde(rename = "EG_QUAL_INELIGIBLE_GATEWAY")]
EgQualIneligibleGateway,
#[serde(rename = "EG_QUAL_INELIGIBLE_DUE_TO_IPO")]
EgQualIneligibleDueToIpo,
#[serde(rename = "EG_QUAL_INELIGIBLE_DUE_TO_SELF_DIRECTED")]
EgQualIneligibleDueToSelfDirected,
#[serde(rename = "EG_QUAL_INELIGIBLE_DUE_TO_CHANGEORDER")]
EgQualIneligibleDueToChangeorder,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum ReInvestOption {
#[serde(rename = "REINVEST")]
Reinvest,
#[serde(rename = "DEPOSIT")]
Deposit,
#[serde(rename = "CURRENT_HOLDING")]
CurrentHolding,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum MarginLevelCd {
#[serde(rename = "UNSPECIFIED")]
Unspecified,
#[serde(rename = "MARGIN_TRADING_NOT_ALLOWED")]
MarginTradingNotAllowed,
#[serde(rename = "MARGIN_TRADING_ALLOWED")]
MarginTradingAllowed,
#[serde(rename = "MARGIN_TRADING_ALLOWED_ON_OPTIONS")]
MarginTradingAllowedOnOptions,
#[serde(rename = "MARGIN_TRADING_ALLOWED_ON_PM")]
MarginTradingAllowedOnPm,
}
|
fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
let mut res = vec![1];
for i in 0..nums.len() - 1 {
res.push(nums[i] * res[i]);
}
let mut prefix = 1;
for i in (1..nums.len()).rev() {
prefix = nums[i] * prefix;
res[i - 1] = res[i - 1] * prefix;
}
res
}
fn main() {
assert_eq!(product_except_self(vec![1, 2, 3, 4]), vec![24, 12, 8, 6]);
assert_eq!(
product_except_self(vec![-1, 1, 0, -3, 3]),
vec![0, 0, 9, 0, 0]
);
assert_eq!(product_except_self(vec![2, 3, 5, 0]), vec![0, 0, 0, 30]);
assert_eq!(
product_except_self(vec![4, 3, 2, 1, 2]),
vec![12, 16, 24, 48, 24]
);
}
|
use enigo::*;
use websocket::ClientBuilder;
use websocket::OwnedMessage;
const TABLET_MAX_X: i64 = 20966;
const TABLET_MAX_Y: i64 = 15725;
const SCREEN_MAX_X: i64 = 1920;
const SCREEN_MAX_Y: i64 = 1080;
const RATIO_X: i64 = TABLET_MAX_X / SCREEN_MAX_X;
const RATIO_Y: i64 = TABLET_MAX_Y / SCREEN_MAX_Y;
fn main() {
let mut client = ClientBuilder::new("ws://192.168.1.41:55555").unwrap()
.connect_insecure().unwrap();
let mut enigo = Enigo::new();
let mut is_down = false;
while let Ok(packet) = client.recv_message() {
if let OwnedMessage::Text(text) = packet {
let dots: [i64; 3] = serde_json::from_str(text.as_str()).unwrap();
if !is_down && dots[2] > 0 {
enigo.mouse_down(MouseButton::Left);
is_down = true;
} else if is_down && dots[2] == 0 {
enigo.mouse_up(MouseButton::Left);
is_down = false;
}
enigo.mouse_move_to((dots[0] / RATIO_X) as i32, (dots[1] / RATIO_Y) as i32);
}
}
}
|
const PI: f64 = 3.141592;
const MAX_SECTOR: i16 = 36;
const MAX_CYLINDER: i16 = 5;
const MAX_RADIUS: i16 = 300;
const RADIUS_PER_CYLINDER: f64 = (MAX_RADIUS / MAX_CYLINDER) as f64;
pub const CENTER_X: i16 = 400;
pub const CENTER_Y: i16 = 300;
pub fn cylinders_to_triangles() -> Vec<Vec<i16>> {
let mut points: Vec<Vec<i16>> = Vec::new();
for cylinder in 0..MAX_CYLINDER {
let mut circle: Vec<i16> = Vec::new();
let mut angle: f64 = 0.0;
for _sector in 0..MAX_SECTOR {
let hypotenuse: f64 = RADIUS_PER_CYLINDER * cylinder as f64;
let xoffset: i16 = (hypotenuse * angle.cos()) as i16;
let yoffset: i16 = (hypotenuse * angle.sin()) as i16;
let x = CENTER_X + xoffset;
let y = CENTER_Y + yoffset;
circle.push(x);
circle.push(y);
angle += PI / MAX_SECTOR as f64;
}
points.push(circle);
}
points
}
|
use wasm_bindgen::prelude::*;
use std::ops::Range;
#[wasm_bindgen]
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
pub trait IndicesHelper {
fn indices(&self) -> Range<usize>;
}
impl<T> IndicesHelper for Vec<T> {
fn indices(&self) -> Range<usize> {
0 .. self.len()
}
}
|
use crate::components::HpComponent;
use crate::indices::*;
use crate::profile;
use crate::storage::views::{DeferredDeleteEntityView, View};
use tracing::{debug, trace};
pub fn death_update(mut delete: DeferredDeleteEntityView, (hps,): (View<EntityId, HpComponent>,)) {
profile!("DeathSystem update");
debug!("update death system called");
hps.iter().for_each(|(id, hp)| {
if hp.hp == 0 {
trace!("Entity {:?} has died, deleting", id);
unsafe {
delete.delete_entity(id);
}
}
});
debug!("update death system done");
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{query, world::World};
use crate::{storage::views::FromWorld, storage::views::FromWorldMut};
#[test]
fn test_dead_entity_is_deleted() {
let mut store = World::new();
let entity_1 = store.insert_entity();
let entity_2 = store.insert_entity();
query!(
mutate
store
{
EntityId, HpComponent, .insert(entity_1, HpComponent {
hp: 0,
hp_max: 123
});
EntityId, HpComponent, .insert(entity_2, HpComponent {
hp: 50,
hp_max: 123
});
}
);
let entities: Vec<_> = store
.view::<EntityId, HpComponent>()
.iter()
.map(|(id, _)| id)
.collect();
assert_eq!(entities, vec![entity_1, entity_2]);
death_update(
FromWorldMut::from_world_mut(&mut store),
FromWorld::from_world(&mut store),
);
store.post_process();
let entities: Vec<_> = store
.view::<EntityId, HpComponent>()
.iter()
.map(|(id, _)| id)
.collect();
assert_eq!(entities, vec![entity_2]);
}
}
|
fn main() {
const INPUT: &'static str = include_str!("inputs/day05.txt");
let highest_id = INPUT
.lines()
.map(|x| get_row_and_col(x))
.map(|x| x.0 * 8 + x.1)
.max()
.unwrap();
println!("max: {}", highest_id)
}
fn get_row_and_col(s: &str) -> (isize, isize) {
let (row, col) = s.split_at(7);
let row = row.replace("F", "0").replace("B", "1");
let col = col.replace("L", "0").replace("R", "1");
let row = isize::from_str_radix(&row, 2).unwrap();
let col = isize::from_str_radix(&col, 2).unwrap();
(row, col)
}
|
use crate::image_data::{ImageData, ImageFormat};
use crate::resources::{self, GraphicResourceManager, GraphicResource, GraphicResourceError};
use crate::texture_resource::{TextureResource, TextureHandle};
use crate::vec2::Vec2;
use crate::rect::Rect;
use std::fmt;
use std::any::Any;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use rusttype;
use rusttype::gpu_cache::{Cache, CacheBuilder};
use font_loader::system_fonts;
use lazy_static::lazy_static;
uione_graphic_resource!(FontResource, get_font_resource, FONT_RESOURCE_HANDLE);
#[derive(Clone)]
pub struct FontEntry {
id: usize,
pub font: Arc<rusttype::Font<'static>>,
}
//#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
//pub struct FontHandle(usize);
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct FontDetails {
pub family: String,
pub italic: bool,
pub oblique: bool,
pub bold: bool,
pub monospace: bool,
}
impl FontDetails {
pub fn new(family: String) -> FontDetails {
FontDetails {
family,
italic: false,
oblique: false,
bold: false,
monospace: false,
}
}
}
pub struct FontStore {
loaded_fonts: Vec<Arc<rusttype::Font<'static>>>,
font_details_mapping: HashMap<FontDetails, usize>,
}
impl FontStore {
fn new() -> FontStore {
FontStore {
loaded_fonts: vec![],
font_details_mapping: HashMap::new(),
}
}
fn add_font(&mut self, details: FontDetails, font: Arc<rusttype::Font<'static>>) -> FontEntry {
let id = self.loaded_fonts.len();
self.font_details_mapping.insert(details, id);
self.loaded_fonts.push(font.clone());
FontEntry {
id,
font,
}
}
pub fn font_for_details(&mut self, details: FontDetails) -> FontEntry {
if let Some(entry_index) = self.font_details_mapping.get(&details) {
return FontEntry {
id: *entry_index,
font: self.loaded_fonts[*entry_index].clone(),
};
}
let mut info_builder = system_fonts::FontPropertyBuilder::new()
.family(&details.family);
if details.italic { info_builder = info_builder.italic(); }
if details.oblique { info_builder = info_builder.oblique(); }
if details.bold { info_builder = info_builder.bold(); }
if details.monospace { info_builder = info_builder.monospace(); }
let font_info = info_builder.build();
let font_data = system_fonts::get(&font_info).unwrap().0;
//for font_name in system_fonts::query_specific(font_info) {}
let font = rusttype::Font::from_bytes(font_data).unwrap();
self.add_font(details, Arc::new(font))
}
}
lazy_static! {
pub static ref STATIC_FONT_STORE: Mutex<FontStore> = Mutex::new(FontStore::new());
}
/*struct GlyphIdWithXPos {
id: usize,
sub_pixel_offset: i8,
}
struct GlyphCache {
// Mapping from glyphs that need to be drawn on the texture atlas, to the rectangle of where the
// glyph should be drawn on the atlas.
pending_glyphs: Hash<GlyphIdWithXPos, Rect<u32>>,
atlas_width: u32,
atlas_height: u32,
current_row_height: u32,
current_x: u32,
current_y: u32,
}
impl GlyphCache {
fn process_pending(&mut self) {
for (glyphidpos, rect) in self.pending_glyphs.drain() {
}
}
}*/
pub struct FontResource {
pub cache: Cache<'static>,
pub tex: Option<Arc<TextureHandle>>,
}
impl fmt::Debug for FontResource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "FontResource")
}
}
impl FontResource {
pub fn new() -> FontResource {
let cache = CacheBuilder {
width: 256,
height: 256,
scale_tolerance: 0.1,
position_tolerance: 0.1,
pad_glyphs: true,
}.build();
FontResource {
cache,
tex: None,
}
}
pub fn ensure_tex(&mut self, texture_resource: &mut TextureResource) -> Arc<TextureHandle> {
if self.tex.is_none() {
let (w, h) = self.cache.dimensions();
let image = ImageData::new_zero(Vec2::new(w as usize, h as usize), ImageFormat::RGBA8888);
self.tex = Some(texture_resource.make_texture(&image));
}
let tex = self.tex.as_mut().unwrap();
tex.clone()
}
pub fn queue_glyph(&mut self, font: &FontEntry, positioned_glyph: rusttype::PositionedGlyph<'static>) {
self.cache.queue_glyph(font.id, positioned_glyph);
}
pub fn cache_queued(&mut self, texture_resource: &mut TextureResource) {
let tex = self.ensure_tex(texture_resource);
self.cache.cache_queued(|rect, pixel_data| {
let image_data = ImageData::new_borrowed(pixel_data, Vec2::new(rect.width() as usize, rect.height() as usize), ImageFormat::R8).unwrap();
tex.blit(&image_data, Rect::new_xywh(rect.min.x as isize, rect.min.y as isize, rect.width() as isize, rect.height() as isize));
}).unwrap();
}
pub fn get_glyph_rect(&self, font: &FontEntry, positioned_glyph: &rusttype::PositionedGlyph<'static>) -> Option<Rect<f32>> {
match self.cache.rect_for(font.id, positioned_glyph) {
Ok(Some((glyph_rect, _dest_rect))) => {
Some(Rect::new_xywh(glyph_rect.min.x, glyph_rect.min.y, glyph_rect.width(), glyph_rect.height()))
}
_ => None
}
}
}
|
// unihernandez22
// https://codeforces.com/problemset/problem/1154/A
// math
use std::io::stdin;
fn main() {
let mut s = String::new();
stdin().read_line(&mut s).unwrap();
let mut words: Vec<i32> = s
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
words.sort();
println!("{} {} {}", words[3]-words[0], words[3]-words[1], words[3]-words[2])
}
|
use std::cmp::Ordering;
use std::{env, fs, process};
use handlebars::TemplateRenderError;
use serde::Deserialize;
use thiserror::Error;
const CFG_PATH: &str = "$HOME/.config/polybar-forecast/config.toml";
// Represents user configs
#[derive(Debug, Deserialize, Clone)]
pub struct Configuration {
#[serde(default = "api_key_from_env")]
pub api_key: String,
pub city_id: String,
pub display: String,
}
impl Configuration {
pub fn new() -> Result<Self, Error> {
let content = dirs::config_dir()
.and_then(|mut path| {
// Check in .config first
path.push("polybar-forecast/config.toml");
fs::read_to_string(&path).ok()
})
.or_else(|| {
// Otherwise, check in the same folder as the executable
let mut dir = env::current_exe().ok()?;
dir.pop();
dir.push("config.toml");
fs::read_to_string(&dir).ok()
})
.ok_or(Error::MissingConfigFile)?;
let decoded: Configuration = toml::from_str(&content)?;
Ok(decoded)
}
}
// Suported temperature units
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
Kelvin,
Celcius,
Fahrenheit,
}
impl Unit {
pub fn to_api(&self) -> &str {
match self {
Unit::Celcius => "metric",
Unit::Fahrenheit => "imperial",
Unit::Kelvin => "kelvin",
}
}
}
// Wrapper type for a temperature, allows abstractions around units, conversions ...
#[derive(Debug, Clone, Copy, Eq)]
pub struct Temperature(pub i16, pub Unit);
impl PartialEq for Temperature {
fn eq(&self, other: &Temperature) -> bool {
let other = other.as_unit(self.1);
self.0 == other.0
}
}
impl PartialOrd for Temperature {
fn partial_cmp(&self, other: &Temperature) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for Temperature {
fn cmp(&self, other: &Temperature) -> Ordering {
let other = other.as_unit(self.1);
self.0.cmp(&other.0)
}
}
impl Temperature {
pub fn as_unit(self, unit: Unit) -> Temperature {
use Unit::*;
match (self.0, self.1, unit) {
// Kelvin to Celcius
(val, Kelvin, Celcius) => Temperature(val - 273.15 as i16, Celcius),
// Kelvin to Fahrenheit
(val, Kelvin, Fahrenheit) => Temperature(val * 9 / 5 - 459.67 as i16, Fahrenheit),
// Celcius to Kelvin
(val, Celcius, Kelvin) => Temperature(val + 273.15 as i16, Kelvin),
// Celcius to Fahrenheit
(val, Celcius, Fahrenheit) => Temperature(val * 9 / 5 + 32 as i16, Fahrenheit),
// Fahrenheit to Kelvin
(val, Fahrenheit, Kelvin) => Temperature((val + 459.67 as i16) * 5 / 9 as i16, Kelvin),
// Fahrenheit to Celcius
(val, Fahrenheit, Celcius) => Temperature((val - 32) * 5 / 9 as i16, Celcius),
// Identity
_ => self,
}
}
}
// If the api_key field is missing in the config file, we try to read it from env variables
fn api_key_from_env() -> String {
match env::var("OWM_API_KEY") {
Ok(key) => key,
Err(_) => {
eprintln!("\nCould not find OpenWeatherMap API key. Make sure api_key is set in the config file, or the OWM_API_KEY env variable is defined");
process::exit(1);
}
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("Failed to query OpenWeatherMap: {}", _0)]
HttpError(#[from] reqwest::Error),
#[error("Config file error, please check {}: {}", CFG_PATH, _0)]
InvalidConfigFile(#[from] toml::de::Error),
#[error("Failed to render output, {}", _0)]
InvalidTemplate(#[from] TemplateRenderError),
#[error("Could not open config file, please check {}", CFG_PATH)]
MissingConfigFile,
#[error("Invalid response from OpenWeatherMap")]
InvalidResponse,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unit_converter() {
use Unit::*;
assert_eq!(
Temperature(0, Celcius).as_unit(Fahrenheit),
Temperature(32, Fahrenheit)
);
assert_eq!(
Temperature(-50, Celcius).as_unit(Kelvin),
Temperature(223.15 as i16, Kelvin)
);
assert_eq!(
Temperature(32, Fahrenheit).as_unit(Celcius),
Temperature(0, Celcius)
);
assert_eq!(
Temperature(-459.67 as i16, Fahrenheit).as_unit(Kelvin),
Temperature(0, Kelvin)
);
assert_eq!(
Temperature(223.15 as i16, Kelvin).as_unit(Celcius),
Temperature(-50, Celcius)
);
assert_eq!(
Temperature(0, Kelvin).as_unit(Fahrenheit),
Temperature(-459.67 as i16, Fahrenheit)
);
}
#[test]
fn unit_cmp() {
use Unit::*;
assert!(Temperature(0, Celcius) <= Temperature(0, Celcius));
assert!(!(Temperature(0, Celcius) < Temperature(0, Celcius)));
assert!(Temperature(1, Celcius) > Temperature(30, Fahrenheit));
assert!(Temperature(100, Kelvin) < Temperature(25, Celcius));
}
}
|
use std::fmt::{self, Display, Formatter};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone, Debug)]
pub struct Id(String);
impl Id {
pub fn new<I: AsRef<str>>(id: I) -> Self { Self(id.as_ref().to_string()) }
}
impl Display for Id {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<&str> for Id {
fn from(string: &str) -> Self { Self(string.to_string()) }
}
impl From<String> for Id {
fn from(string: String) -> Self { Self(string) }
}
impl Into<String> for Id {
fn into(self) -> String { self.0 }
}
impl Into<String> for &Id {
fn into(self) -> String { self.0.to_string() }
}
impl AsRef<str> for Id {
fn as_ref(&self) -> &str { &self.0 }
}
|
use std::io;
use anyhow::{anyhow, Context, Result};
use serde::Deserialize;
use crate::config::read_config;
use crate::note::{InputNote, DbNote};
use crate::db::{init_schema, insert_notes};
pub fn exec() -> Result<()> {
let cfg = read_config()
.context("Reading config")?;
let db = sqlite::open(&cfg.db_path)
.context("Opening database file")?;
init_schema(&db)
.context("Initializing database schema")?;
let notes = read_notes(io::stdin())
.context("Reading notes from stdin")?;
let notes = transform_notes(¬es)
.context("Invalid note format")?;
insert_notes(&db, ¬es)
}
fn read_notes<T: io::Read>(r: T) -> Result<Vec<InputNote>> {
let val = serde_yaml::from_reader(r)?;
match val {
serde_yaml::Value::Sequence(_) =>
Vec::<InputNote>::deserialize(val)
.context("Parsing a sequence of notes from YAML"),
serde_yaml::Value::Mapping(_) => Ok(vec![
InputNote::deserialize(val)
.context("Parsing a note from YAML")?
]),
_ => anyhow::bail!("Object or sequence of objects expected.")
}
}
fn transform_notes(notes: &[InputNote]) -> Result<Vec<DbNote>>
{
let mut res = Vec::new();
let mut err = Vec::new();
for r in notes.iter().map(InputNote::to_db_note) {
match r {
Ok(n) => res.push(n),
Err(e) => err.push(e),
}
}
if err.is_empty() {
Ok(res)
} else {
let err: String = err.iter()
.map(|s| "- ".to_string() + &s.to_string() + "\n")
.collect();
Err(anyhow!(err))
}
}
|
fn main() {
println!("Another top-level source");
}
|
use crate::{backend::Backend, error::error};
use cloudevents::{
event::{Data, ExtensionValue},
AttributesReader, Event,
};
use drogue_cloud_service_api::{EXT_APPLICATION, EXT_DEVICE};
use itertools::Itertools;
use patternfly_yew::*;
use unicode_segmentation::UnicodeSegmentation;
use wasm_bindgen::{closure::Closure, JsValue};
use web_sys::{EventSource, EventSourceInit};
use yew::prelude::*;
pub struct Spy {
link: ComponentLink<Self>,
source: Option<EventSource>,
events: SharedTableModel<Entry>,
application: String,
running: bool,
total_received: usize,
}
pub enum Msg {
Start(Option<String>),
StartPressed,
Stop,
Event(Box<Event>),
/// Failed when processing an event
Error(String),
/// Source failed
Failed,
SetApplication(String),
}
const DEFAULT_MAX_SIZE: usize = 200;
#[derive(Clone, Debug, PartialEq)]
pub struct Entry(pub Event);
impl TableRenderer for Entry {
fn render(&self, col: ColumnIndex) -> Html {
match col.index {
// timestamp
0 => render_timestamp(&self.0),
// device id
1 => self.device().into(),
// payload
2 => render_data_short(&self.0),
// ignore
_ => html! {},
}
}
fn render_details(&self) -> Vec<Span> {
vec![Span::max(render_details(&self.0)).truncate()]
}
}
impl Entry {
fn device(&self) -> String {
let app_id = self.extension_as_string(EXT_APPLICATION);
let device_id = self.extension_as_string(EXT_DEVICE);
format!("{} / {}", app_id, device_id)
}
fn extension_as_string(&self, name: &str) -> String {
self.0
.extension(name)
.map(|s| match s {
ExtensionValue::String(s) => s.clone(),
ExtensionValue::Integer(i) => i.to_string(),
ExtensionValue::Boolean(true) => "true".into(),
ExtensionValue::Boolean(false) => "false".into(),
})
.unwrap_or_default()
}
}
impl Component for Spy {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
events: Default::default(),
link,
source: None,
running: false,
total_received: 0,
application: String::new(),
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Start(app_id) => {
log::info!("Starting: {:?}", app_id);
self.start(app_id);
}
Msg::StartPressed => {
self.link.send_message(Msg::Start(self.app_id_filter()));
}
Msg::Stop => {
self.stop();
}
Msg::Event(event) => {
// log::debug!("Pushing event: {:?}", event);
self.total_received += 1;
self.events.insert(0, Entry(*event));
while self.events.len() > DEFAULT_MAX_SIZE {
self.events.pop();
}
}
Msg::Error(err) => {
error("Failed to process event", err);
}
Msg::Failed => {
error("Source error", "Failed to connect to the event source");
self.running = false;
}
Msg::SetApplication(application) => {
self.application = application;
}
}
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
let is_valid = self.app_id_filter().is_some();
let is_running = self.running;
let v = |value: &str| match value {
"" => InputState::Error,
_ => InputState::Default,
};
return html! {
<>
<PageSection variant=PageSectionVariant::Light limit_width=true>
<Content>
<Title>{"Device Message Spy"}</Title>
</Content>
</PageSection>
<PageSection>
<Toolbar>
<ToolbarGroup>
<ToolbarItem>
<TextInput
disabled=self.running
onchange=self.link.callback(|app|Msg::SetApplication(app))
validator=Validator::from(v)
placeholder="Application ID to spy on"/>
</ToolbarItem>
<ToolbarItem>
{if is_running {
html!{<Button
disabled=!is_valid
label="Stop"
icon=Icon::Pause
variant=Variant::Secondary
onclick=self.link.callback(|_|Msg::Stop)
/>}
} else {
html!{<Button
disabled=!is_valid
label="Start"
icon=Icon::Play
variant=Variant::Primary
onclick=self.link.callback(|_|Msg::StartPressed)
/>}
}}
</ToolbarItem>
</ToolbarGroup>
<ToolbarItem modifiers=vec![ToolbarElementModifier::Right.all()]>
{ if self.running { html!{
<strong>{"events received: "}{self.total_received}</strong>
} } else { html!{} } }
</ToolbarItem>
</Toolbar>
<Table<SharedTableModel<Entry>>
entries=self.events.clone()
mode=TableMode::CompactExpandable
header={html_nested!{
<TableHeader>
<TableColumn label="Timestamp (UTC)"/>
<TableColumn label="Device ID"/>
<TableColumn label="Payload"/>
</TableHeader>
}}
>
</Table<SharedTableModel<Entry>>>
{ if self.events.is_empty() {
self.render_empty()
} else {
html!{}
}}
</PageSection>
</>
};
}
fn destroy(&mut self) {
if let Some(source) = self.source.take() {
source.close();
}
}
}
impl Spy {
fn app_id_filter(&self) -> Option<String> {
let value = self.application.clone();
match value.is_empty() {
true => None,
false => Some(value),
}
}
fn start(&mut self, app_id: Option<String>) {
let mut url = Backend::url("/api/console/v1alpha1/spy").unwrap();
// add optional filter
if let Some(app_id) = &app_id {
url.query_pairs_mut().append_pair("app", app_id);
}
// EventSource doesn't support passing headers, so we cannot send
// the bearer token the normal way
url.query_pairs_mut()
.append_pair("token", &Backend::access_token().unwrap_or_default());
// create source
let source =
EventSource::new_with_event_source_init_dict(&url.to_string(), &EventSourceInit::new())
.unwrap();
// setup onmessage
let link = self.link.clone();
let on_message = Closure::wrap(Box::new(move |msg: &JsValue| {
let msg = extract_event(msg);
link.send_message(msg);
}) as Box<dyn FnMut(&JsValue)>);
source.set_onmessage(Some(&on_message.into_js_value().into()));
// setup onerror
let link = self.link.clone();
let on_error = Closure::wrap(Box::new(move || {
link.send_message(Msg::Failed);
}) as Box<dyn FnMut()>);
source.set_onerror(Some(&on_error.into_js_value().into()));
// store result
self.running = true;
self.source = Some(source);
}
fn stop(&mut self) {
if let Some(source) = self.source.take() {
source.close();
}
self.running = false
}
fn render_empty(&self) -> Html {
return html! {
<div style="padding-bottom: 10rem; height: 100%;">
<Bullseye>
<EmptyState
title="No new messages"
icon=Icon::Pending
size=Size::XLarge
>
{ "The " } <q> {"message spy"} </q> { " will only show "} <strong> {"new"} </strong> {" messages received by the system.
When the next message arrives, you will see it right here." }
</EmptyState>
</Bullseye>
</div>
};
}
}
fn extract_event(msg: &JsValue) -> Msg {
// web_sys::console::debug_2(&JsValue::from("event: "), msg);
let data: String = js_sys::Reflect::get(msg, &JsValue::from("data"))
.unwrap()
.as_string()
.unwrap();
match serde_json::from_str(&data) {
Ok(event) => Msg::Event(event),
Err(e) => Msg::Error(e.to_string()),
}
}
fn render_data(event: &Event) -> Html {
// let data: Option<Data> = event.get_data();
match event.data() {
None => html! {},
Some(Data::String(text)) => html! { <pre> {text} </pre> },
Some(Data::Binary(blob)) => html! { <>
<pre> { pretty_hex::pretty_hex(&blob) } </pre>
<pre> { base64_block(&blob) } </pre>
</> },
Some(Data::Json(value)) => {
let value = serde_json::to_string_pretty(&value).unwrap();
return html! { <pre> {value} </pre> };
}
}
}
fn base64_block(input: &[u8]) -> String {
base64::encode(input)
.chars()
.collect::<Vec<_>>()
.chunks(120)
.map(|chunk| chunk.iter().collect::<String>())
.join("\n")
}
fn render_blob(blob: &[u8]) -> String {
let max = blob.len().min(25);
let ellipsis = if blob.len() > max { ", …" } else { "" };
format!("[{}; {:02x?}{}]", blob.len(), &blob[0..max], ellipsis)
}
fn truncate_str(len: usize, string: &str) -> String {
let mut r = String::new();
for c in string.graphemes(true) {
if r.len() > len || r.contains('\n') || r.contains('\r') {
r.push('…');
break;
}
r.push_str(c);
}
r
}
fn render_data_short(event: &Event) -> Html {
match event.data() {
None => html! {},
Some(Data::String(text)) => html! {
<pre>
<Label label="String" color=Color::Purple/>{" "}{truncate_str(100, text)}
</pre>
},
Some(Data::Binary(blob)) => html! {
<pre>
<Label label="BLOB" color=Color::Blue/>{" "}{render_blob(&blob)}
</pre>
},
Some(Data::Json(value)) => html! {
<pre>
<Label label="JSON" color=Color::Cyan/>{" "}{truncate_str(100, &value.to_string())}
</pre>
},
}
}
fn render_timestamp(event: &Event) -> Html {
event
.time()
.map(|ts| {
return html! {
<span>
<pre>{ts.format("%H:%M:%S%.3f %Y-%m-%d")}</pre>
</span>
};
})
.unwrap_or_default()
}
#[derive(Clone, Debug, PartialEq)]
struct AttributeEntry(pub String, pub Html);
impl TableRenderer for AttributeEntry {
fn render(&self, index: ColumnIndex) -> Html {
match index.index {
0 => html! {&self.0},
1 => self.1.clone(),
_ => html! {},
}
}
}
fn render_details(event: &Event) -> Html {
let mut attrs: Vec<AttributeEntry> = event
.iter()
.map(|(key, value)| {
(
key.to_string(),
html! {
<pre class="pf-c-table__text">{ value.to_string() }</pre>
},
)
})
.map(|(key, value)| AttributeEntry(key, value))
.collect();
attrs.sort_by(|a, b| a.0.cmp(&b.0));
return html! {
<>
<h3>{"Attributes"}</h3>
<Table<SimpleTableModel<AttributeEntry>>
entries=SimpleTableModel::from(attrs)
mode=TableMode::CompactNoBorders
header=html_nested!{
<TableHeader>
<TableColumn label="Key"/>
<TableColumn label="Value"/>
</TableHeader>
}
>
</Table<SimpleTableModel<AttributeEntry>>>
<h3>{"Payload"}</h3>
{ render_data(event) }
</>
};
}
|
use std::sync::Arc;
use hashbrown::HashSet;
use rosu_v2::prelude::{GameMode, OsuError, Username};
use crate::{
embeds::{EmbedData, UntrackEmbed},
util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
MessageExt,
},
BotResult, CommandData, Context, MessageBuilder,
};
use super::TrackArgs;
#[command]
#[authority()]
#[short_desc("Untrack user(s) in a channel")]
#[long_desc(
"Stop notifying a channel about new plays in a user's top100.\n\
Specified users will be untracked for all modes.\n\
You can specify up to ten usernames per command invocation."
)]
#[usage("[username1] [username2] ...")]
#[example("badewanne3 cookiezi \"freddie benson\" peppy")]
async fn untrack(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, num } => {
let track_args = match TrackArgs::args(&ctx, &mut args, num, None).await {
Ok(Ok(args)) => args,
Ok(Err(content)) => return msg.error(&ctx, content).await,
Err(why) => {
let _ = msg.error(&ctx, GENERAL_ISSUE).await;
return Err(why);
}
};
_untrack(ctx, CommandData::Message { msg, args, num }, track_args).await
}
CommandData::Interaction { command } => super::slash_track(ctx, *command).await,
}
}
pub(super) async fn _untrack(
ctx: Arc<Context>,
data: CommandData<'_>,
args: TrackArgs,
) -> BotResult<()> {
let TrackArgs {
name,
mode,
mut more_names,
..
} = args;
more_names.push(name);
if let Some(name) = more_names.iter().find(|name| name.len() > 15) {
let content = format!("`{name}` is too long for an osu! username");
return data.error(&ctx, content).await;
}
let mode = mode.unwrap_or(GameMode::STD);
let users = match super::get_names(&ctx, &more_names, mode).await {
Ok(map) => map,
Err((OsuError::NotFound, name)) => {
let content = format!("User `{name}` was not found");
return data.error(&ctx, content).await;
}
Err((err, _)) => {
let _ = data.error(&ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
let channel = data.channel_id();
let mut success = HashSet::with_capacity(users.len());
for (username, user_id) in users.into_iter() {
let remove_fut = ctx
.tracking()
.remove_user(user_id, Some(mode), channel, ctx.psql());
match remove_fut.await {
Ok(_) => success.insert(username),
Err(err) => {
warn!("Error while adding tracked entry: {err}");
return send_message(&ctx, data, Some(&username), success).await;
}
};
}
send_message(&ctx, data, None, success).await?;
Ok(())
}
async fn send_message(
ctx: &Context,
data: CommandData<'_>,
name: Option<&Username>,
success: HashSet<Username>,
) -> BotResult<()> {
let success = success.into_iter().collect();
let embed = UntrackEmbed::new(success, name).into_builder().build();
let builder = MessageBuilder::new().embed(embed);
data.create_message(ctx, builder).await?;
Ok(())
}
|
use std::iter::Peekable;
use std::str::Chars;
use crate::token::Token;
use crate::token::Token::{Values, Value, Pipe};
trait VecExt<T> {
fn push_value(&mut self, ele: T);
}
impl VecExt<Token> for Vec<Token> {
fn push_value(&mut self, token: Token) {
if token.value().is_some() {
self.push(token)
}
}
}
pub fn parse(input: String) -> Vec<Token> {
let mut tokens = Vec::new();
let mut iter = input.chars().peekable();
while let Some(c) = iter.peek() {
let token = match c {
'"' => consume_multiple_strings(&mut iter),
_ => consume_word(&mut iter),
};
tokens.push_value(token);
}
tokens
}
fn consume_word(iter: &mut Peekable<Chars>) -> Token {
let mut token_string = String::new();
while let Some(c) = iter.next() {
let next = iter.peek().map(|c| c.to_owned());
match c {
'\\' if next == Some(' ') => {
token_string.push(iter.next().unwrap_or_default())
}
' ' => break,
_ => token_string.push(c)
}
}
token_from(token_string)
}
fn token_from(s: String) -> Token {
match s.trim() {
"|" => Pipe,
_ => Value(s)
}
}
fn consume_multiple_strings(iter: &mut Peekable<Chars>) -> Token {
let mut values = Vec::new();
while let Some(c) = iter.peek() {
match c {
'"' => values.push(consume_string(iter)),
_ => break
}
}
Values(values)
}
fn consume_string(iter: &mut Peekable<Chars>) -> String {
let mut token = String::new();
let _ = iter.next(); // Ignore first already seen quote
while let Some(c) = iter.next() {
let next = iter.peek().map(|c| c.to_owned());
match c {
'\\' if next == Some('"') => {
token.push(iter.next().unwrap_or_default())
}
'"' => break,
_ => token.push(c)
}
}
token
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//*****Tests**************************************************************************************//
////////////////////////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
pub mod tests {
use crate::parser::parse;
use crate::token::Token;
use crate::token::Token::*;
#[test]
fn should_parse_empty_string() {
let actual = parse("".to_owned());
let expected: Vec<Token> = vec![];
assert_eq!(expected, actual)
}
#[test]
fn should_parse_multiple_words() {
let actual = parse("hello world".to_owned());
let expected: Vec<Token> = vec![Value(String::from("hello")), Value(String::from("world"))];
assert_eq!(expected, actual)
}
#[test]
fn should_parse_word_with_string() {
let actual = parse("echo \"hello world\"".to_owned());
let expected: Vec<Token> = vec![Value(String::from("echo")), Values(vec![String::from("hello world")])];
assert_eq!(expected, actual)
}
#[test]
fn should_parse_word_with_escaped_space_string() {
let actual = parse("echo hello\\ world".to_owned());
let expected: Vec<Token> = vec![Value(String::from("echo")), Value(String::from("hello world"))];
assert_eq!(expected, actual)
}
#[test]
fn should_parse_word_joined_strings() {
let actual = parse("echo \"hello\"\"world\"".to_owned());
let expected: Vec<Token> = vec![Value(String::from("echo")), Values(vec![String::from("hello"), String::from("world")])];
assert_eq!(expected, actual)
}
#[test]
fn should_parse_with_pipe() {
let actual = parse("echo hello | cat".to_owned());
let expected: Vec<Token> = vec![Value(String::from("echo")), Value(String::from("hello")), Pipe, Value(String::from("cat"))];
assert_eq!(expected, actual)
}
}
|
#[macro_use]
extern crate criterion;
use criterion::{BatchSize, Criterion};
use hacspec_chacha20::*;
use hacspec_chacha20poly1305::*;
use hacspec_dev::rand::random_byte_vec;
use hacspec_lib::prelude::*;
fn benchmark(c: &mut Criterion) {
c.bench_function("ChaCha20Poly1305 encrypt", |b| {
b.iter_batched(
|| {
let key = ChaChaKey::from_public_slice(&random_byte_vec(32));
let nonce = ChaChaIV::from_public_slice(&random_byte_vec(12));
let data = ByteSeq::from_public_slice(&random_byte_vec(10_000));
let aad = ByteSeq::from_public_slice(&random_byte_vec(1_000));
(data, nonce, aad, key)
},
|(data, nonce, aad, key)| {
let (_cipher, _tag) = chacha20_poly1305_encrypt(key, nonce, &aad, &data);
},
BatchSize::SmallInput,
)
});
c.bench_function("ChaCha20Poly1305 decrypt", |b| {
b.iter_batched(
|| {
let key = ChaChaKey::from_public_slice(&random_byte_vec(32));
let nonce = ChaChaIV::from_public_slice(&random_byte_vec(12));
let data = ByteSeq::from_public_slice(&random_byte_vec(10_000));
let aad = ByteSeq::from_public_slice(&random_byte_vec(1_000));
let (cipher, tag) = chacha20_poly1305_encrypt(key, nonce, &aad, &data);
(nonce, aad, key, cipher, tag)
},
|(nonce, aad, key, cipher, tag)| {
let _msg = chacha20_poly1305_decrypt(key, nonce, &aad, &cipher, tag);
},
BatchSize::SmallInput,
)
});
}
criterion_group!(benches, benchmark);
criterion_main!(benches);
|
mod art;
mod artist;
mod postgres;
pub mod scheduler;
#[allow(unused_imports)]
mod schema;
pub use art::PgArtRepository;
pub use artist::PgArtistRepository;
pub use postgres::{Connection, Postgres};
pub use scheduler::PgSchedulerRepository;
|
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let filename = "input/input.txt";
let binary_numbers = parse_input_file(filename);
// println!("{:?}", binary_numbers);
// Part 1
let gamma_str = calculate_gamma_rate_str(&binary_numbers);
let gamma_val = binary_str_to_num(&gamma_str);
println!("gamma rate string: {}", gamma_str);
println!("gamma rate value: {}", gamma_val);
let epsilon_str = binary_complement(&gamma_str);
let epsilon_val = binary_str_to_num(&epsilon_str);
println!("epsilon rate: {}", epsilon_str);
println!("epsilon rate: {}", epsilon_val);
let power_consumption = gamma_val * epsilon_val;
println!("power consumption: {}", power_consumption);
assert_eq!(3882564, power_consumption);
// Part 2
let oxygen_generator_rating = calculate_oxygen_generator_rating(&binary_numbers);
println!("oxygen_generator_rating: {}", oxygen_generator_rating);
let co2_scrubber_rating = calculate_co2_scrubber_rating(&binary_numbers);
println!("co2_scrubber_rating: {}", co2_scrubber_rating);
let life_support_rating = oxygen_generator_rating * co2_scrubber_rating;
println!("life support rating: {}", life_support_rating);
assert_eq!(3385170, life_support_rating);
}
fn parse_input_file(filename: &str) -> Vec<String> {
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).expect("couldn't open file");
let reader = BufReader::new(file);
// Read the file line by line using the lines() iterator from std::io::BufRead.
reader
.lines()
.map(|line_res| line_res.expect("couldn't unwrap line"))
.collect()
}
fn calculate_gamma_rate_str(binary_numbers: &Vec<String>) -> String {
let binary_nums_as_chars: Vec<Vec<char>> =
binary_numbers.iter().map(|n| n.chars().collect()).collect();
(0..binary_numbers[0].len())
.map(|i| most_common_bit(&binary_nums_as_chars, i))
.collect::<String>()
}
fn calculate_oxygen_generator_rating(binary_numbers: &Vec<String>) -> isize {
filter_binary_nums_by_criteria(binary_numbers, most_common_bit)
}
fn calculate_co2_scrubber_rating(binary_numbers: &Vec<String>) -> isize {
filter_binary_nums_by_criteria(binary_numbers, least_common_bit)
}
fn filter_binary_nums_by_criteria(
binary_numbers: &Vec<String>,
bit_criteria: BitCriteria,
) -> isize {
let mut binary_nums_as_chars: Vec<Vec<char>> =
binary_numbers.iter().map(|n| n.chars().collect()).collect();
let mut bit_position = 0;
while binary_nums_as_chars.len() != 1 {
let column_bit_value = bit_criteria(&binary_nums_as_chars, bit_position);
// filter binary_numbers by only those that have the most common bit in this position
let filtered_nums: Vec<Vec<char>> = binary_nums_as_chars
.into_iter()
.filter(|bn| bn[bit_position] == column_bit_value)
.collect();
binary_nums_as_chars = filtered_nums;
bit_position += 1;
}
let rating_str: String = binary_nums_as_chars
.first()
.expect("expected to find last binary number")
.iter()
.collect();
binary_str_to_num(&rating_str)
}
type BitCriteria = fn(binary_nums_as_chars: &Vec<Vec<char>>, bit_position: usize) -> char;
fn most_common_bit(binary_nums_as_chars: &Vec<Vec<char>>, i: usize) -> char {
let (num_zeros, num_ones) = count_digits(binary_nums_as_chars, i);
if num_zeros > num_ones {
'0'
} else {
'1'
}
}
fn least_common_bit(binary_nums_as_chars: &Vec<Vec<char>>, i: usize) -> char {
let most_common_bit = most_common_bit(binary_nums_as_chars, i);
flip(most_common_bit)
}
fn count_digits(binary_nums_as_chars: &Vec<Vec<char>>, i: usize) -> (usize, usize) {
binary_nums_as_chars
.iter()
.map(move |bn| bn[i])
.fold((0, 0), |(num_zeros, num_ones), n| {
if n == '0' {
(num_zeros + 1, num_ones)
} else {
(num_zeros, num_ones + 1)
}
})
}
fn binary_str_to_num(binary_str: &str) -> isize {
isize::from_str_radix(binary_str, 2).unwrap()
}
fn binary_complement(binary_str: &str) -> String {
String::from(binary_str).chars().map(flip).collect()
}
fn flip(bit: char) -> char {
if bit == '0' {
'1'
} else {
'0'
}
}
|
use crate::bstream::BstreamHdr;
use crate::io::TwzIOHdr;
use crate::io::{PollStates, ReadFlags, ReadOutput, ReadResult, WriteFlags, WriteOutput, WriteResult};
use twz::event::Event;
use twz::mutex::TwzMutex;
use twz::obj::CreateSpec;
use twz::obj::Twzobj;
use twz::ptr::Pptr;
use twz::refs::Pref;
use twz::TwzErr;
const PTY_BUFFER_SZ: usize = 1024;
const NCCS: usize = 32;
const OPOST: u32 = 1;
const ONLCR: u32 = 4;
const OCRNL: u32 = 0o10;
const ICANON: u32 = 0o0000002;
const ECHO: u32 = 0o0000010;
const VERASE: u32 = 2;
const VEOF: u32 = 4;
const BRKINT: u32 = 0o0000002;
const ISIG: u32 = 0o0000001;
const ECHOE: u32 = 0o0000020;
const ICRNL: u32 = 0o0000400;
const INLCR: u32 = 0o0000100;
#[derive(Clone, Copy)]
#[repr(C)]
struct Termios {
c_iflag: u32,
c_oflag: u32,
c_cflag: u32,
c_lflag: u32,
c_line: u8,
c_cc: [u8; NCCS],
__c_ispeed: u32,
__c_ospeed: u32,
}
impl Default for Termios {
fn default() -> Self {
Termios {
c_iflag: BRKINT | ICRNL,
c_oflag: ONLCR | OPOST,
c_cflag: 0,
c_lflag: ICANON | ECHO | ISIG | ECHOE,
c_line: 0,
c_cc: [
3, 0, 8, 0, 4, 0, 1, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
__c_ispeed: 0,
__c_ospeed: 0,
}
}
}
#[derive(Clone, Copy)]
#[repr(C)]
struct WinSize {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
}
impl Default for WinSize {
fn default() -> Self {
WinSize {
ws_row: 25,
ws_col: 80,
ws_xpixel: 0,
ws_ypixel: 0,
}
}
}
#[derive(Clone, Copy)]
#[repr(C)]
struct PtyBuffer {
bufpos: usize,
buffer: [u8; PTY_BUFFER_SZ],
}
impl Default for PtyBuffer {
fn default() -> Self {
PtyBuffer {
bufpos: 0,
buffer: [0; PTY_BUFFER_SZ],
}
}
}
#[derive(Default)]
#[repr(C)]
pub struct PtyServerHdr {
stoc: Pptr<BstreamHdr>,
ctos: Pptr<BstreamHdr>,
io: TwzIOHdr,
termios: Termios,
wsz: WinSize,
input_buflock: TwzMutex<PtyBuffer>,
output_buflock: TwzMutex<PtyBuffer>,
}
#[derive(Default)]
#[repr(C)]
pub struct PtyClientHdr {
server: Pptr<PtyServerHdr>,
io: TwzIOHdr,
}
impl PtyBuffer {
fn enqueue(&mut self, bytes: &[u8]) -> bool {
if self.bufpos + bytes.len() >= PTY_BUFFER_SZ {
return false;
}
for i in 0..bytes.len() {
let b = bytes[i];
self.buffer[self.bufpos] = b;
self.bufpos += 1;
}
true
}
fn erase(&mut self) {
if self.bufpos > 0 {
self.bufpos -= 1;
}
}
fn drain(&mut self, hdr: &PtyServerHdr, nonblock: bool, towards_client: bool) -> bool {
let current_len = self.bufpos;
let bs = if towards_client { hdr.stoc.lea() } else { hdr.ctos.lea() };
while self.bufpos > 0 {
let result = bs
.write(
&self.buffer[0..self.bufpos],
if nonblock { WriteFlags::NONBLOCK } else { WriteFlags::none() },
)
.unwrap();
if let WriteOutput::Done(thislen) = result {
if thislen != self.bufpos {
self.buffer.copy_within(thislen..self.bufpos, 0);
}
self.bufpos -= thislen;
} else {
return false;
}
}
true
}
}
impl PtyServerHdr {
fn transform_write_char(&self, ch: u8, tr: &mut [u8]) -> usize {
if ch == b'\n' && (self.termios.c_oflag & ONLCR) != 0 {
tr[0] = b'\r';
tr[1] = b'\n';
2
} else if ch == b'\r' && (self.termios.c_oflag & OCRNL) != 0 {
tr[0] = b'\n';
1
} else {
tr[0] = ch;
1
}
}
fn transform_input_char(&self, ch: u8, tr: &mut [u8]) -> usize {
if ch == b'\n' && self.termios.c_iflag & INLCR != 0 {
tr[0] = b'\r';
1
} else if ch == b'\r' && self.termios.c_iflag & ICRNL != 0 {
tr[0] = b'\n';
1
} else if ch == 27 {
tr[0] = b'^';
1
} else {
tr[0] = ch;
1
}
}
fn should_take_action(&self, buf: &[u8]) -> u8 {
for b in buf {
if *b == self.termios.c_cc[VEOF as usize] {
return 2;
}
if *b == b'\n' {
return 1;
}
}
0
}
}
impl crate::io::TwzIO for PtyServerHdr {
fn poll(&self, events: PollStates) -> Option<Event> {
if events.contains_any(PollStates::READ) {
let bs = self.ctos.lea();
bs.poll(events)
} else if events.contains_any(PollStates::WRITE) {
let bs = self.stoc.lea();
bs.poll(events)
} else {
None
}
}
fn read(&self, buf: &mut [u8], flags: ReadFlags) -> ReadResult {
let bs = self.ctos.lea();
let result = bs.read(buf, flags)?;
if result.is_blocked() {
let mut output_buffer = self.output_buflock.lock();
output_buffer.drain(self, flags.contains_any(ReadFlags::NONBLOCK), false);
return bs.read(buf, flags);
}
Ok(result)
}
fn write(&self, buf: &[u8], flags: WriteFlags) -> WriteResult {
if self.termios.c_lflag & ICANON != 0 {
let mut input_buffer = self.input_buflock.lock();
let echo_bs = self.ctos.lea();
for i in 0..buf.len() {
if buf[i] == self.termios.c_cc[VERASE as usize] {
input_buffer.erase();
echo_bs.write(&[buf[i], b' ', buf[i]], WriteFlags::NONBLOCK);
}
let mut tr = [0; 2];
let len = self.transform_input_char(buf[i], &mut tr);
/* we don't care if this doesn't work, since we discard anything after buffer is
* filled.*/
input_buffer.enqueue(&tr[0..len]);
if self.termios.c_lflag & ECHO != 0 {
/* TODO: can we do better than this best-effort? */
echo_bs.write(&tr[0..len], WriteFlags::NONBLOCK);
}
let act = self.should_take_action(&tr[0..len]);
let mut eof = false;
if act == 2 && input_buffer.bufpos > 0 {
eof = true;
}
if act > 0 {
if !input_buffer.drain(self, flags.contains_any(WriteFlags::NONBLOCK), true) {
eprintln!("PTY buffer backup, needs fixing");
/* TODO: urgent */
}
}
if eof { /* TODO: EOF */ }
}
if !input_buffer.drain(&self, flags.contains_any(WriteFlags::NONBLOCK), true) {
if flags.contains_any(WriteFlags::NONBLOCK) {
return Ok(WriteOutput::WouldBlock);
}
}
Ok(WriteOutput::Done(buf.len()))
} else {
/* TODO: sync between echoing and actual writing. Currently, we could have non-echo'd
* stuff get past when it should be echoed. */
let len = if self.termios.c_lflag & ECHO != 0 {
let echo_bs = self.ctos.lea();
let result = echo_bs.write(buf, flags)?;
if let WriteOutput::Done(len) = result {
len
} else {
return Ok(result);
}
} else {
buf.len()
};
if len == 0 && flags.contains_any(WriteFlags::NONBLOCK) {
return Ok(WriteOutput::WouldBlock);
}
let bs = self.stoc.lea();
bs.write(buf, flags)
}
}
}
impl crate::io::TwzIO for PtyClientHdr {
fn poll(&self, events: PollStates) -> Option<Event> {
let server = self.server.lea();
if events.contains_any(PollStates::READ) {
let bs = server.stoc.lea();
bs.poll(events)
} else if events.contains_any(PollStates::WRITE) {
let bs = server.ctos.lea();
bs.poll(events)
} else {
None
}
}
fn read(&self, buf: &mut [u8], flags: ReadFlags) -> ReadResult {
let server = self.server.lea();
let bs = server.stoc.lea();
let result = bs.read(buf, flags)?;
if result.is_blocked() {
let mut input_buffer = server.input_buflock.lock();
input_buffer.drain(&server, flags.contains_any(ReadFlags::NONBLOCK), true);
return bs.read(buf, flags);
}
Ok(result)
}
fn write(&self, buf: &[u8], flags: WriteFlags) -> WriteResult {
let server = self.server.lea();
let bs = server.ctos.lea();
if (server.termios.c_oflag & OPOST) != 0 {
let mut output_buffer = server.output_buflock.lock();
if !output_buffer.drain(&server, flags.contains_any(WriteFlags::NONBLOCK), false) && flags.contains_any(WriteFlags::NONBLOCK) {
return Ok(WriteOutput::WouldBlock);
}
for i in 0..buf.len() {
let mut tr = [0; 2];
let len = server.transform_write_char(buf[i], &mut tr);
let wrote_all = output_buffer.enqueue(&tr[0..len]);
if !wrote_all {
panic!("failed to enqueue to output buffer in pty");
}
if !output_buffer.drain(&server, flags.contains_any(WriteFlags::NONBLOCK), false) {
if i == 0 && flags.contains_any(WriteFlags::NONBLOCK) {
return Ok(WriteOutput::WouldBlock);
}
if i > 0 {
return Ok(WriteOutput::Done(i + 1));
}
/* can't have i == 0 here because we would have blocked in drain() */
}
}
Ok(WriteOutput::Done(buf.len()))
} else {
bs.write(buf, flags)
}
}
}
use crate::io::{TwzIO, TwzIOType};
pub fn create_pty_pair(
_client_spec: &CreateSpec,
_server_spec: &CreateSpec,
) -> Result<(Twzobj<PtyClientHdr>, Twzobj<PtyServerHdr>), TwzErr> {
let server = Twzobj::<PtyServerHdr>::create_ctor(_server_spec, |obj, tx| {
let mut base = obj.base_mut(tx);
base.stoc.set(obj.new_item(tx), tx);
base.ctos.set(obj.new_item(tx), tx);
base.io.io_type = TwzIOType::PtyServer;
unsafe {
obj.add_metaext(crate::io::METAEXT_TAG, &base.io);
}
//base.ctos = base.stoc;
})
.unwrap();
/*
let base = server.base();
let bs = base.stoc.lea();
let data = b"Hello, Bstream!";
let mut rcount = 0;
let mut wcount = 0;
while true {
let result: WriteOutput = bs.write(data, crate::io::WriteFlags::none()).unwrap();
// println!("write: {:?}", result);
if let WriteOutput::Done(n) = result {
wcount += n;
}
let mut buffer = [0; 128];
let result = bs.read(&mut buffer, crate::io::ReadFlags::none()).unwrap();
if let ReadOutput::Done(n) = result {
rcount += n;
}
if rcount != wcount {
panic!("");
}
// println!("read: {} {} {:?} : {:?}", wcount, rcount, result, buffer);
}
loop {}
*/
let client = Twzobj::<PtyClientHdr>::create_ctor(_client_spec, |obj, tx| {
let mut base = obj.base_mut(tx);
base.server.set(server.base(), tx);
base.io.io_type = TwzIOType::PtyClient;
unsafe {
obj.add_metaext(crate::io::METAEXT_TAG, &base.io);
}
})
.unwrap();
/*
let client_base = client.base();
let server_base = server.base();
let result = server_base.write(b"Hello, from server", WriteFlags::none());
println!("write {:?}", result);
let mut buffer = [0; 1024];
let result = client_base.read(&mut buffer, ReadFlags::none());
println!("read {:?} {:?}", result, buffer);
let result = client_base.write(b"Hello, from CLIENT", WriteFlags::none());
println!("write client {:?}", result);
let result = server_base.read(&mut buffer, ReadFlags::none());
println!("read client {:?} {:?}", result, buffer);
*/
Ok((client, server))
}
|
use ptgui::prelude::*;
use std::cmp::{max, min};
pub trait PhysicsCollider {
fn is_colliding<T>(&self, other: T) -> bool
where
T: PhysicsCollider,
{
let t_size = self.get_size();
let t_pos = self.get_pos();
let o_size = other.get_size();
let o_pos = other.get_pos();
let t_rect = [t_pos.0, t_pos.1, t_pos.0 + t_size.0, t_pos.1 + t_size.1];
let o_rect = [o_pos.0, o_pos.1, o_pos.0 + o_size.0, o_pos.1 + o_size.1];
(min(t_rect[2], o_rect[2]) > max(t_rect[0], o_rect[0]))
&& (min(t_rect[3], o_rect[3]) > max(t_rect[1], o_rect[1]))
}
fn get_pos(&self) -> Point;
fn get_size(&self) -> Dimensions;
}
|
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i+1),
}
}
fn main() {
let x = 5;
println!("Val: {}, plus one: {}", x, plus_one(Some(x)).unwrap_or(1));
let x = Some(x);
println!("Val: {}, plus one: {}", x.unwrap(), plus_one(x).expect("Bad val"));
let x = None;
println!("Val of none with default of 1: {}", x.unwrap_or(1));
println!("Val of none with expect will panic: {}", x.expect("This will be panic because we have a None value"));
}
|
use std::{env, path};
use ggez::event::{self, EventHandler};
use ggez::nalgebra::Point2;
use ggez::{filesystem, graphics, timer};
use ggez::{Context, GameResult};
impl EventHandler for VSync {
fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
println!(
"[update] ticks: {}\tfps: {}\tdelta: {:?}",
timer::ticks(ctx),
timer::fps(ctx),
timer::delta(ctx)
);
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
let fps = timer::fps(ctx);
let fps_display = graphics::Text::new(format!("FPS: {}", fps));
println!(
"[draw] ticks: {}\tfps: {}\tdelta: {:?}",
timer::ticks(ctx),
fps,
timer::delta(ctx)
);
graphics::clear(ctx, graphics::WHITE);
graphics::draw(ctx, &fps_display, (Point2::new(0.0, 0.0), graphics::BLACK))?;
graphics::present(ctx)
}
}
struct VSync {}
impl VSync {
pub fn new(_ctx: &mut Context) -> VSync {
VSync {}
}
}
fn main() -> GameResult {
let mut cb = ggez::ContextBuilder::new("name", "author");
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let path = path::PathBuf::from(manifest_dir).join("resources");
cb = cb.add_resource_path(path);
}
let (ctx, event_loop) = &mut cb.build()?;
println!("{:#?}", filesystem::read_config(ctx));
let mut vsync_demo = VSync::new(ctx);
event::run(ctx, event_loop, &mut vsync_demo)
}
|
pub const VOICE_COUNT: usize = 16;
pub const CHANNEL_COUNT: usize = 3;
pub const SAMPLE_HZ: f32 = 48000.0;
pub const MAX_STEPS: usize = 24;
|
use kube_derive::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)]
#[kube(group = "clux.dev", version = "v1", kind = "FooEnum")]
#[serde(rename_all = "camelCase")]
#[allow(clippy::enum_variant_names)]
enum FooEnumSpec {
/// First variant with an int
VariantOne { int: i32 },
/// Second variant with an String
VariantTwo { str: String },
/// Third variant which doesn't has an attribute
VariantThree {},
}
#[test]
fn test_crd_name() {
use kube::core::CustomResourceExt;
assert_eq!("fooenums.clux.dev", FooEnum::crd_name());
}
#[test]
fn test_serialized_matches_expected() {
assert_eq!(
serde_json::to_value(FooEnum::new("bar", FooEnumSpec::VariantOne { int: 42 })).unwrap(),
serde_json::json!({
"apiVersion": "clux.dev/v1",
"kind": "FooEnum",
"metadata": {
"name": "bar",
},
"spec": {
"variantOne": {
"int": 42
}
}
})
);
assert_eq!(
serde_json::to_value(FooEnum::new("bar", FooEnumSpec::VariantThree {})).unwrap(),
serde_json::json!({
"apiVersion": "clux.dev/v1",
"kind": "FooEnum",
"metadata": {
"name": "bar",
},
"spec": {
"variantThree": {}
}
})
);
}
#[test]
fn test_crd_schema_matches_expected() {
use kube::core::CustomResourceExt;
assert_eq!(
FooEnum::crd(),
serde_json::from_value(serde_json::json!({
"apiVersion": "apiextensions.k8s.io/v1",
"kind": "CustomResourceDefinition",
"metadata": {
"name": "fooenums.clux.dev"
},
"spec": {
"group": "clux.dev",
"names": {
"categories": [],
"kind": "FooEnum",
"plural": "fooenums",
"shortNames": [],
"singular": "fooenum"
},
"scope": "Cluster",
"versions": [
{
"additionalPrinterColumns": [],
"name": "v1",
"schema": {
"openAPIV3Schema": {
"description": "Auto-generated derived type for FooEnumSpec via `CustomResource`",
"properties": {
"spec": {
"oneOf": [
{
"required": [
"variantOne"
]
},
{
"required": [
"variantTwo"
]
},
{
"required": [
"variantThree"
]
}
],
"properties": {
"variantOne": {
"description": "First variant with an int",
"properties": {
"int": {
"format": "int32",
"type": "integer"
}
},
"required": [
"int"
],
"type": "object"
},
"variantThree": {
"description": "Third variant which doesn't has an attribute",
"type": "object"
},
"variantTwo": {
"description": "Second variant with an String",
"properties": {
"str": {
"type": "string"
}
},
"required": [
"str"
],
"type": "object"
}
},
"type": "object"
}
},
"required": [
"spec"
],
"title": "FooEnum",
"type": "object"
}
},
"served": true,
"storage": true,
"subresources": {}
}
]
}
}
))
.unwrap()
);
}
|
#[doc = "Register `PATT3` reader"]
pub type R = crate::R<PATT3_SPEC>;
#[doc = "Register `PATT3` writer"]
pub type W = crate::W<PATT3_SPEC>;
#[doc = "Field `ATTSETx` reader - ATTSETx"]
pub type ATTSETX_R = crate::FieldReader;
#[doc = "Field `ATTSETx` writer - ATTSETx"]
pub type ATTSETX_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `ATTWAITx` reader - ATTWAITx"]
pub type ATTWAITX_R = crate::FieldReader;
#[doc = "Field `ATTWAITx` writer - ATTWAITx"]
pub type ATTWAITX_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `ATTHOLDx` reader - ATTHOLDx"]
pub type ATTHOLDX_R = crate::FieldReader;
#[doc = "Field `ATTHOLDx` writer - ATTHOLDx"]
pub type ATTHOLDX_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `ATTHIZx` reader - ATTHIZx"]
pub type ATTHIZX_R = crate::FieldReader;
#[doc = "Field `ATTHIZx` writer - ATTHIZx"]
pub type ATTHIZX_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - ATTSETx"]
#[inline(always)]
pub fn attsetx(&self) -> ATTSETX_R {
ATTSETX_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - ATTWAITx"]
#[inline(always)]
pub fn attwaitx(&self) -> ATTWAITX_R {
ATTWAITX_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - ATTHOLDx"]
#[inline(always)]
pub fn attholdx(&self) -> ATTHOLDX_R {
ATTHOLDX_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - ATTHIZx"]
#[inline(always)]
pub fn atthizx(&self) -> ATTHIZX_R {
ATTHIZX_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - ATTSETx"]
#[inline(always)]
#[must_use]
pub fn attsetx(&mut self) -> ATTSETX_W<PATT3_SPEC, 0> {
ATTSETX_W::new(self)
}
#[doc = "Bits 8:15 - ATTWAITx"]
#[inline(always)]
#[must_use]
pub fn attwaitx(&mut self) -> ATTWAITX_W<PATT3_SPEC, 8> {
ATTWAITX_W::new(self)
}
#[doc = "Bits 16:23 - ATTHOLDx"]
#[inline(always)]
#[must_use]
pub fn attholdx(&mut self) -> ATTHOLDX_W<PATT3_SPEC, 16> {
ATTHOLDX_W::new(self)
}
#[doc = "Bits 24:31 - ATTHIZx"]
#[inline(always)]
#[must_use]
pub fn atthizx(&mut self) -> ATTHIZX_W<PATT3_SPEC, 24> {
ATTHIZX_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Attribute memory space timing register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`patt3::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`patt3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PATT3_SPEC;
impl crate::RegisterSpec for PATT3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`patt3::R`](R) reader structure"]
impl crate::Readable for PATT3_SPEC {}
#[doc = "`write(|w| ..)` method takes [`patt3::W`](W) writer structure"]
impl crate::Writable for PATT3_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PATT3 to value 0xfcfc_fcfc"]
impl crate::Resettable for PATT3_SPEC {
const RESET_VALUE: Self::Ux = 0xfcfc_fcfc;
}
|
// Copyright (c) 2019 Anatoly Ikorsky
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use futures_util::future::FutureExt;
use futures_util::stream::{StreamExt, StreamFuture};
use pin_project::pin_project;
use tokio::time::{self, Interval};
use std::future::Future;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use super::Inner;
use crate::prelude::Queryable;
use crate::PoolOptions;
use futures_core::task::{Context, Poll};
use std::pin::Pin;
/// Idling connections TTL check interval.
///
/// The purpose of this interval is to remove idling connections that both:
/// * overflows min bound of the pool;
/// * idles longer then `inactive_connection_ttl`.
#[pin_project]
pub struct TtlCheckInterval {
inner: Arc<Inner>,
#[pin]
interval: StreamFuture<Interval>,
pool_options: PoolOptions,
}
impl TtlCheckInterval {
/// Creates new `TtlCheckInterval`.
pub fn new(pool_options: PoolOptions, inner: Arc<Inner>) -> Self {
let interval = time::interval(pool_options.ttl_check_interval()).into_future();
Self {
inner,
interval,
pool_options,
}
}
/// Perform the check.
pub fn check_ttl(&self) {
let num_idling = self.inner.idle.len();
let mut num_to_drop = num_idling.saturating_sub(self.pool_options.constraints().min());
let mut num_returned = 0;
for _ in 0..num_idling {
match self.inner.idle.pop() {
Ok(idling_conn) => {
if idling_conn.elapsed() > self.pool_options.inactive_connection_ttl() {
tokio::spawn(idling_conn.conn.disconnect().map(drop));
self.inner.exist.fetch_sub(1, Ordering::AcqRel);
num_to_drop -= 1;
if num_to_drop == 0 {
break;
}
} else {
self.inner.push_to_idle(idling_conn);
num_returned += 1;
}
}
Err(_) => break,
}
}
if num_returned > 0 {
self.inner.wake(num_returned);
}
}
}
impl Future for TtlCheckInterval {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let (_, interval) = futures_core::ready!(self.as_mut().project().interval.poll(cx));
let close = self.inner.close.load(Ordering::Acquire);
if !close {
self.check_ttl();
self.interval = interval.into_future();
} else {
return Poll::Ready(());
}
}
}
}
|
extern crate bme280;
use bme280::{Bme280Device, DEFAULT_DEVICE, DEFAULT_ADDRESS};
fn main() {
let mut dev = Bme280Device::new(DEFAULT_DEVICE, DEFAULT_ADDRESS)?;
let r = dev.read_all()?;
println!("temperature: {}", r.temperature);
println!("humidity: {}", r.humidity);
println!("pressure: {}", r.pressure);
}
|
use std::net::TcpStream;
pub use craftping::sync::ping;
fn main() {
let servers = ["us.mineplex.com", "mc.hypixel.net"];
for &server in servers.iter() {
let mut stream = TcpStream::connect((server, 25565)).unwrap();
let response = ping(&mut stream, server, 25565).unwrap();
println!("ping to {}:", server);
println!("{:?}", response);
}
}
|
#[doc = "Reader of register UARTPCELLID3"]
pub type R = crate::R<u32, super::UARTPCELLID3>;
#[doc = "Reader of field `UARTPCELLID3`"]
pub type UARTPCELLID3_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - These bits read back as 0xB1"]
#[inline(always)]
pub fn uartpcellid3(&self) -> UARTPCELLID3_R {
UARTPCELLID3_R::new((self.bits & 0xff) as u8)
}
}
|
#![cfg(test)]
use super::*;
use crate::physics::single_chain::test::Parameters;
mod base
{
use super::*;
use rand::Rng;
#[test]
fn init()
{
let parameters = Parameters::default();
let _ = SWFJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, parameters.hinge_mass_reference, parameters.well_width_reference);
}
#[test]
fn number_of_links()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
assert_eq!(number_of_links, SWFJC::init(number_of_links, parameters.link_length_reference, parameters.hinge_mass_reference, parameters.well_width_reference).number_of_links);
}
}
#[test]
fn link_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
assert_eq!(link_length, SWFJC::init(parameters.number_of_links_minimum, link_length, parameters.hinge_mass_reference, parameters.well_width_reference).link_length);
}
}
#[test]
fn hinge_mass()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
assert_eq!(hinge_mass, SWFJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, hinge_mass, parameters.well_width_reference).hinge_mass);
}
}
#[test]
fn well_width()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
assert_eq!(well_width, SWFJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, parameters.hinge_mass_reference, well_width).well_width);
}
}
#[test]
fn all_parameters()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
assert_eq!(number_of_links, model.number_of_links);
assert_eq!(link_length, model.link_length);
assert_eq!(hinge_mass, model.hinge_mass);
assert_eq!(well_width, model.well_width);
}
}
}
mod nondimensional
{
use super::*;
use rand::Rng;
#[test]
fn helmholtz_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_helmholtz_free_energy = model.nondimensional_helmholtz_free_energy(&nondimensional_force, &temperature);
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let helmholtz_free_energy = model.helmholtz_free_energy(&force, &temperature);
let residual_abs = &helmholtz_free_energy/BOLTZMANN_CONSTANT/temperature - &nondimensional_helmholtz_free_energy;
let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn helmholtz_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_helmholtz_free_energy_per_link = model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_force, &temperature);
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let helmholtz_free_energy_per_link = model.helmholtz_free_energy_per_link(&force, &temperature);
let residual_abs = &helmholtz_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - &nondimensional_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn relative_helmholtz_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_helmholtz_free_energy = model.nondimensional_relative_helmholtz_free_energy(&nondimensional_force);
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let relative_helmholtz_free_energy = model.relative_helmholtz_free_energy(&force, &temperature);
let residual_abs = &relative_helmholtz_free_energy/BOLTZMANN_CONSTANT/temperature - &nondimensional_relative_helmholtz_free_energy;
let residual_rel = &residual_abs/&nondimensional_relative_helmholtz_free_energy;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn relative_helmholtz_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_helmholtz_free_energy_per_link = model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_force);
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let relative_helmholtz_free_energy_per_link = model.relative_helmholtz_free_energy_per_link(&force, &temperature);
let residual_abs = &relative_helmholtz_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - &nondimensional_relative_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&nondimensional_relative_helmholtz_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
}
mod per_link
{
use super::*;
use rand::Rng;
#[test]
fn helmholtz_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let helmholtz_free_energy = model.helmholtz_free_energy(&force, &temperature);
let helmholtz_free_energy_per_link = model.helmholtz_free_energy_per_link(&force, &temperature);
let residual_abs = &helmholtz_free_energy/(number_of_links as f64) - &helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&helmholtz_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn relative_helmholtz_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let relative_helmholtz_free_energy = model.relative_helmholtz_free_energy(&force, &temperature);
let relative_helmholtz_free_energy_per_link = model.relative_helmholtz_free_energy_per_link(&force, &temperature);
let residual_abs = &relative_helmholtz_free_energy/(number_of_links as f64) - &relative_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&relative_helmholtz_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_helmholtz_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_helmholtz_free_energy = model.nondimensional_helmholtz_free_energy(&nondimensional_force, &temperature);
let nondimensional_helmholtz_free_energy_per_link = model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_force, &temperature);
let residual_abs = &nondimensional_helmholtz_free_energy/(number_of_links as f64) - &nondimensional_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_relative_helmholtz_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_helmholtz_free_energy = model.nondimensional_relative_helmholtz_free_energy(&nondimensional_force);
let nondimensional_relative_helmholtz_free_energy_per_link = model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_force);
let residual_abs = &nondimensional_relative_helmholtz_free_energy/(number_of_links as f64) - &nondimensional_relative_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&nondimensional_relative_helmholtz_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
}
mod relative
{
use super::*;
use rand::Rng;
#[test]
fn helmholtz_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let helmholtz_free_energy = model.helmholtz_free_energy(&force, &temperature);
let helmholtz_free_energy_0 = model.helmholtz_free_energy(&(ZERO*BOLTZMANN_CONSTANT*temperature/link_length), &temperature);
let relative_helmholtz_free_energy = model.relative_helmholtz_free_energy(&force, &temperature);
let residual_abs = &helmholtz_free_energy - &helmholtz_free_energy_0 - &relative_helmholtz_free_energy;
let residual_rel = &residual_abs/&helmholtz_free_energy_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn helmholtz_free_energy_per_link()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let force = nondimensional_force*BOLTZMANN_CONSTANT*temperature/link_length;
let helmholtz_free_energy_per_link = model.helmholtz_free_energy_per_link(&force, &temperature);
let helmholtz_free_energy_per_link_0 = model.helmholtz_free_energy_per_link(&(ZERO*BOLTZMANN_CONSTANT*temperature/link_length), &temperature);
let relative_helmholtz_free_energy_per_link = model.relative_helmholtz_free_energy_per_link(&force, &temperature);
let residual_abs = &helmholtz_free_energy_per_link - &helmholtz_free_energy_per_link_0 - &relative_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&helmholtz_free_energy_per_link_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_helmholtz_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_helmholtz_free_energy = model.nondimensional_helmholtz_free_energy(&nondimensional_force, &temperature);
let nondimensional_helmholtz_free_energy_0 = model.nondimensional_helmholtz_free_energy(&ZERO, &temperature);
let nondimensional_relative_helmholtz_free_energy = model.nondimensional_relative_helmholtz_free_energy(&nondimensional_force);
let residual_abs = &nondimensional_helmholtz_free_energy - &nondimensional_helmholtz_free_energy_0 - &nondimensional_relative_helmholtz_free_energy;
let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_helmholtz_free_energy_per_link()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_force = parameters.nondimensional_force_reference + parameters.nondimensional_force_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_helmholtz_free_energy_per_link = model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_force, &temperature);
let nondimensional_helmholtz_free_energy_per_link_0 = model.nondimensional_helmholtz_free_energy_per_link(&ZERO, &temperature);
let nondimensional_relative_helmholtz_free_energy_per_link = model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_force);
let residual_abs = &nondimensional_helmholtz_free_energy_per_link - &nondimensional_helmholtz_free_energy_per_link_0 - &nondimensional_relative_helmholtz_free_energy_per_link;
let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy_per_link_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
}
mod zero
{
use super::*;
use rand::Rng;
#[test]
fn relative_helmholtz_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let relative_helmholtz_free_energy_0 = model.relative_helmholtz_free_energy(&(ZERO*BOLTZMANN_CONSTANT*temperature/link_length), &temperature);
assert!(relative_helmholtz_free_energy_0.abs() <= ZERO);
}
}
#[test]
fn relative_helmholtz_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let relative_helmholtz_free_energy_per_link_0 = model.relative_helmholtz_free_energy_per_link(&(ZERO*BOLTZMANN_CONSTANT*temperature/link_length), &temperature);
assert!(relative_helmholtz_free_energy_per_link_0.abs() <= ZERO);
}
}
#[test]
fn nondimensional_relative_helmholtz_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_relative_helmholtz_free_energy_0 = model.nondimensional_relative_helmholtz_free_energy(&ZERO);
assert!(nondimensional_relative_helmholtz_free_energy_0.abs() <= ZERO);
}
}
#[test]
fn nondimensional_relative_helmholtz_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let well_width = parameters.well_width_reference + parameters.well_width_scale*(0.5 - rng.gen::<f64>());
let model = SWFJC::init(number_of_links, link_length, hinge_mass, well_width);
let nondimensional_relative_helmholtz_free_energy_per_link_0 = model.nondimensional_relative_helmholtz_free_energy_per_link(&ZERO);
assert!(nondimensional_relative_helmholtz_free_energy_per_link_0.abs() <= ZERO);
}
}
}
|
#![no_std]
use num_derive::*;
#[derive(FromPrimitive, ToPrimitive)]
pub enum ABC {
A,
B,
C,
}
#[derive(PartialEq, FromPrimitive, Num, NumCast, NumOps, One, ToPrimitive, Zero)]
pub struct NewFloat(f32);
|
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
#![allow(unused)]
#![deny(missing_docs)]
//! A safe wrapper around the kernel's KVM interface.
extern crate kvm_bindings;
extern crate libc;
#[macro_use]
mod sys_ioctl;
#[macro_use]
mod kvm_ioctls;
mod cap;
mod ioctls;
pub use cap::Cap;
pub use ioctls::device::DeviceFd;
pub use ioctls::system::Kvm;
pub use ioctls::vcpu::{VcpuExit, VcpuFd};
pub use ioctls::vm::VmFd;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub use ioctls::CpuId;
// The following example is used to verify that our public
// structures are exported properly.
/// # Example
///
/// ```
/// #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
/// use kvm_ioctls::{KvmRunWrapper, Result};
/// ```
pub use ioctls::{KvmRunWrapper, Result};
/// Maximum number of CPUID entries that can be returned by a call to KVM ioctls.
///
/// This value is taken from Linux Kernel v4.14.13 (arch/x86/include/asm/kvm_host.h).
/// It can be used for calls to [get_supported_cpuid](struct.Kvm.html#method.get_supported_cpuid) and
/// [get_emulated_cpuid](struct.Kvm.html#method.get_emulated_cpuid).
pub const MAX_KVM_CPUID_ENTRIES: usize = 80;
|
use super::*;
use std::ffi::CStr;
pub fn expression() -> Expression {
Expression {
boostrap_compiler: boostrap_compiler,
typecheck: typecheck,
codegen: codegen,
}
}
fn boostrap_compiler(compiler: &mut Compiler) {
add_function_to_compiler(compiler, "int", Type::Int, &vec![Type::String], "int");
}
fn typecheck(
resolver: &mut TypeResolver<TypecheckType>,
_function: &TypevarFunction,
args: &Vec<TypeVar>,
) -> GenericResult<TypeVar> {
let type_var = resolver.create_type_var();
resolver.add_constraint(Constraint::IsLiteral(
args[0],
Unresolved::Literal(TypecheckType::String),
))?;
resolver.add_constraint(Constraint::IsLiteral(
type_var,
Unresolved::Literal(TypecheckType::Int),
))?;
Ok(type_var)
}
pub fn codegen(context: &mut Context, args: &[Token]) -> CodegenResult<Object> {
call_function(context, "int", args)
}
#[no_mangle]
pub extern "C" fn int(value: *const c_char) -> i64 {
let s = unsafe { CStr::from_ptr(value).to_str().unwrap() };
s.parse::<i64>().unwrap()
}
|
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::jwk::Jwk;
use jsonwebtoken::{
crypto::{sign, verify},
decode, decode_header, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation,
};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct Claims {
sub: String,
company: String,
exp: i64,
}
#[test]
fn sign_hs256() {
let result =
sign(b"hello world", &EncodingKey::from_secret(b"secret"), Algorithm::HS256).unwrap();
let expected = "c0zGLzKEFWj0VxWuufTXiRMk5tlI5MbGDAYhzaxIYjo";
assert_eq!(result, expected);
}
#[test]
fn verify_hs256() {
let sig = "c0zGLzKEFWj0VxWuufTXiRMk5tlI5MbGDAYhzaxIYjo";
let valid = verify(sig, b"hello world", &DecodingKey::from_secret(b"secret"), Algorithm::HS256)
.unwrap();
assert!(valid);
}
#[test]
fn encode_with_custom_header() {
let my_claims = Claims {
sub: "b@b.com".to_string(),
company: "ACME".to_string(),
exp: OffsetDateTime::now_utc().unix_timestamp() + 10000,
};
let header = Header { kid: Some("kid".to_string()), ..Default::default() };
let token = encode(&header, &my_claims, &EncodingKey::from_secret(b"secret")).unwrap();
let token_data = decode::<Claims>(
&token,
&DecodingKey::from_secret(b"secret"),
&Validation::new(Algorithm::HS256),
)
.unwrap();
assert_eq!(my_claims, token_data.claims);
assert_eq!("kid", token_data.header.kid.unwrap());
}
#[test]
fn round_trip_claim() {
let my_claims = Claims {
sub: "b@b.com".to_string(),
company: "ACME".to_string(),
exp: OffsetDateTime::now_utc().unix_timestamp() + 10000,
};
let token =
encode(&Header::default(), &my_claims, &EncodingKey::from_secret(b"secret")).unwrap();
let token_data = decode::<Claims>(
&token,
&DecodingKey::from_secret(b"secret"),
&Validation::new(Algorithm::HS256),
)
.unwrap();
assert_eq!(my_claims, token_data.claims);
assert!(token_data.header.kid.is_none());
}
#[test]
fn decode_token() {
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjI1MzI1MjQ4OTF9.9r56oF7ZliOBlOAyiOFperTGxBtPykRQiWNFxhDCW98";
let claims = decode::<Claims>(
token,
&DecodingKey::from_secret(b"secret"),
&Validation::new(Algorithm::HS256),
);
println!("{:?}", claims);
claims.unwrap();
}
#[test]
#[should_panic(expected = "InvalidToken")]
fn decode_token_missing_parts() {
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
let claims = decode::<Claims>(
token,
&DecodingKey::from_secret(b"secret"),
&Validation::new(Algorithm::HS256),
);
claims.unwrap();
}
#[test]
#[should_panic(expected = "InvalidSignature")]
fn decode_token_invalid_signature() {
let token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUifQ.wrong";
let claims = decode::<Claims>(
token,
&DecodingKey::from_secret(b"secret"),
&Validation::new(Algorithm::HS256),
);
claims.unwrap();
}
#[test]
#[should_panic(expected = "InvalidAlgorithm")]
fn decode_token_wrong_algorithm() {
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUifQ.I1BvFoHe94AFf09O6tDbcSB8-jp8w6xZqmyHIwPeSdY";
let claims = decode::<Claims>(
token,
&DecodingKey::from_secret(b"secret"),
&Validation::new(Algorithm::RS512),
);
claims.unwrap();
}
#[test]
#[should_panic(expected = "InvalidAlgorithm")]
fn encode_wrong_alg_family() {
let my_claims = Claims {
sub: "b@b.com".to_string(),
company: "ACME".to_string(),
exp: OffsetDateTime::now_utc().unix_timestamp() + 10000,
};
let claims = encode(&Header::default(), &my_claims, &EncodingKey::from_rsa_der(b"secret"));
claims.unwrap();
}
#[test]
fn decode_token_with_bytes_secret() {
let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjI1MzI1MjQ4OTF9.Hm0yvKH25TavFPz7J_coST9lZFYH1hQo0tvhvImmaks";
let claims = decode::<Claims>(
token,
&DecodingKey::from_secret(b"\x01\x02\x03"),
&Validation::new(Algorithm::HS256),
);
assert!(claims.is_ok());
}
#[test]
fn decode_header_only() {
let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb21wYW55IjoiMTIzNDU2Nzg5MCIsInN1YiI6IkpvaG4gRG9lIn0.S";
let header = decode_header(token).unwrap();
assert_eq!(header.alg, Algorithm::HS256);
assert_eq!(header.typ, Some("JWT".to_string()));
}
#[test]
fn dangerous_insecure_decode_valid_token() {
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjI1MzI1MjQ4OTF9.9r56oF7ZliOBlOAyiOFperTGxBtPykRQiWNFxhDCW98";
let mut validation = Validation::new(Algorithm::HS256);
validation.insecure_disable_signature_validation();
let claims = decode::<Claims>(token, &DecodingKey::from_secret(&[]), &validation);
claims.unwrap();
}
#[test]
fn dangerous_insecure_decode_token_invalid_signature() {
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjI1MzI1MjQ4OTF9.wrong";
let mut validation = Validation::new(Algorithm::HS256);
validation.insecure_disable_signature_validation();
let claims = decode::<Claims>(token, &DecodingKey::from_secret(&[]), &validation);
claims.unwrap();
}
#[test]
fn dangerous_insecure_decode_token_wrong_algorithm() {
let token = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjI1MzI1MjQ4OTF9.fLxey-hxAKX5rNHHIx1_Ch0KmrbiuoakDVbsJjLWrx8fbjKjrPuWMYEJzTU3SBnYgnZokC-wqSdqckXUOunC-g";
let mut validation = Validation::new(Algorithm::HS256);
validation.insecure_disable_signature_validation();
let claims = decode::<Claims>(token, &DecodingKey::from_secret(&[]), &validation);
claims.unwrap();
}
#[test]
fn dangerous_insecure_decode_token_with_validation_wrong_algorithm() {
let token = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjk1MzI1MjQ4OX0.ONtEUTtP1QmyksYH9ijtPCaXoHjZVHcHKZGX1DuJyPiSyKlT93Y-oKgrp_OSkHSu4huxCcVObLzwsdwF-xwiAQ";
let mut validation = Validation::new(Algorithm::HS256);
validation.insecure_disable_signature_validation();
let claims = decode::<Claims>(token, &DecodingKey::from_secret(&[]), &validation);
let err = claims.unwrap_err();
assert_eq!(err.kind(), &ErrorKind::ExpiredSignature);
}
#[test]
fn verify_hs256_rfc7517_appendix_a1() {
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
struct C {
iss: String,
}
let token = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let jwk = r#"{"kty":"oct",
"k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
}"#;
let jwk: Jwk = serde_json::from_str(jwk).unwrap();
let key = DecodingKey::from_jwk(&jwk).unwrap();
let mut validation = Validation::new(Algorithm::HS256);
// The RFC example signed jwt has expired
validation.validate_exp = false;
let c = decode::<C>(token, &key, &validation).unwrap();
assert_eq!(c.claims.iss, "joe");
}
|
use postgrest::Postgrest;
use std::error::Error;
const REST_URL: &str = "http://localhost:3000";
#[tokio::test]
async fn basic_data() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.select("username")
.eq("status", "OFFLINE")
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(body[0]["username"], "kiwicopple");
Ok(())
}
#[tokio::test]
async fn special_characters_eq() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.select("username")
.eq("username", "ihave.special,c:haracter(s)")
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(body[0]["username"], "ihave.special,c:haracter(s)");
Ok(())
}
#[tokio::test]
async fn special_characters_neq() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.select("username")
.neq("username", "ihave.special,c:haracter(s)")
.and("catchphrase.eq.fat bat")
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert!(body.is_empty());
Ok(())
}
#[tokio::test]
async fn relational_join() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("channels")
.select("slug, messages(message)")
.eq("slug", "public")
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(body[0]["messages"][0]["message"], "Hello World 👋");
assert_eq!(body[0]["slug"], "public");
Ok(())
}
#[tokio::test]
async fn insert() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("messages")
.insert(r#"[{"message": "Test message 0", "channel_id": 1, "username": "kiwicopple"}]"#)
.execute()
.await?;
let status = resp.status();
assert_eq!(status.as_u16(), 201);
Ok(())
}
#[tokio::test]
async fn upsert() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.upsert(
r#"[{"username": "dragarcia", "status": "OFFLINE"},
{"username": "supabot2", "status": "ONLINE"}]"#,
)
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(body[0]["username"], "dragarcia");
assert_eq!(body[1]["username"], "supabot2");
Ok(())
}
#[tokio::test]
async fn upsert_existing() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.upsert(r#"{"username": "dragarcia", "status": "ONLINE"}"#)
.on_conflict("username")
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(body[0]["username"], "dragarcia");
assert_eq!(body[0]["status"], "ONLINE");
Ok(())
}
#[tokio::test]
async fn upsert_nonexisting() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.upsert(r#"{"username": "supabot3", "status": "ONLINE"}"#)
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(body[0]["username"], "supabot3");
assert_eq!(body[0]["status"], "ONLINE");
Ok(())
}
#[tokio::test]
async fn update() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("users")
.eq("status", "ONLINE")
.update(r#"{"status": "ONLINE"}"#)
.execute()
.await?;
let status = resp.status();
let body = resp.text().await?;
let body = json::parse(&body)?;
assert_eq!(status.as_u16(), 200);
assert_eq!(body[0]["status"], "ONLINE");
Ok(())
}
#[tokio::test]
async fn delete() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.from("messages")
.neq("username", "supabot")
.delete()
.execute()
.await?;
let status = resp.status();
assert_eq!(status.as_u16(), 200);
Ok(())
}
#[tokio::test]
async fn rpc() -> Result<(), Box<dyn Error>> {
let client = Postgrest::new(REST_URL);
let resp = client
.rpc("get_status", r#"{"name_param": "leroyjenkins"}"#)
.execute()
.await?;
let body = resp.text().await?;
let body = json::parse(&body)?;
assert!(body.is_null());
Ok(())
}
|
use crate::env_file::entry::Entry;
use crate::env_file::{Env, Var};
#[derive(Debug)]
pub struct EnvIterator<'a> {
env: &'a Env,
index: usize,
}
impl<'a> EnvIterator<'a> {
pub fn new(env: &'a Env) -> Self {
Self { env, index: 0 }
}
}
impl<'a> Iterator for EnvIterator<'a> {
type Item = &'a Var;
fn next(&mut self) -> Option<Self::Item> {
if let Some(var) = self.env.entries.get(self.index) {
self.index += 1;
if let Entry::Var(var) = var {
return Some(&var);
} else {
return self.next();
}
}
None
}
}
#[cfg(test)]
mod tests {
use crate::env_file::Env;
#[test]
fn env_iterator() {
let mut env = Env::new("".into());
env.add("name1", "value1");
env.add_empty_line();
env.add("name2", "value2");
let mut iter = env.iter();
if let Some(var) = iter.next() {
assert_eq!(var.name(), "name1");
assert_eq!(var.value(), "value1");
} else {
assert!(false);
}
if let Some(var) = iter.next() {
assert_eq!(var.name(), "name2");
assert_eq!(var.value(), "value2");
} else {
assert!(false);
}
assert!(iter.next().is_none());
}
}
|
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
#[cfg(test)]
mod vertex_tests {
use graphific::Vertex;
#[test]
fn new_vertex_test() {
let v1: Vertex<i32, i32> = Vertex::new(0);
let v2: Vertex<i32, i32> = Vertex::new(1);
let v3: Vertex<i32, f32> = Vertex::new(2);
assert_eq!(0, *v1.key());
assert_eq!(0, *v1.value());
assert_eq!(i32::default(), *v1.value());
assert_eq!(1, *v2.key());
assert_eq!(0, *v2.value());
assert_eq!(i32::default(), *v2.value());
assert_eq!(2, *v3.key());
assert_eq!(0.0, *v3.value());
assert_eq!(f32::default(), *v3.value());
}
#[test]
fn with_value_test() {
let v1: Vertex<i32, i32> = Vertex::with_value(0, 10);
let v2: Vertex<i32, i32> = Vertex::with_value(1, 11);
let v3: Vertex<i32, f32> = Vertex::with_value(2, 12.0);
assert_eq!(0, *v1.key());
assert_eq!(10, *v1.value());
assert_ne!(i32::default(), *v1.value());
assert_eq!(1, *v2.key());
assert_eq!(11, *v2.value());
assert_ne!(i32::default(), *v2.value());
assert_eq!(2, *v3.key());
assert_eq!(12.0, *v3.value());
assert_ne!(f32::default(), *v3.value());
}
#[test]
fn set_value_test() {
let mut v1: Vertex<i32, i32> = Vertex::new(0);
let mut v2: Vertex<i32, f32> = Vertex::new(1);
assert_eq!(0, *v1.key());
assert_eq!(0, *v1.value());
assert_eq!(i32::default(), *v1.value());
assert_eq!(1, *v2.key());
assert_eq!(0.0, *v2.value());
assert_eq!(f32::default(), *v2.value());
v1.set_value(10);
v2.set_value(11.0);
assert_eq!(10, *v1.value());
assert_ne!(i32::default(), *v1.value());
assert_eq!(11.0, *v2.value());
assert_ne!(f32::default(), *v2.value());
}
}
#[cfg(test)]
mod edges_tests {
use graphific::{Edge, Vertex};
#[test]
fn new_edge_test() {
let v1: Vertex<i32, i32> = Vertex::with_value(0, 10);
let v2: Vertex<i32, i32> = Vertex::with_value(1, 11);
let v3: Vertex<i32, f32> = Vertex::with_value(2, 12.0);
let e1: Edge<&i32> = Edge::new(v1.key(), v2.key());
let e2: Edge<&i32> = Edge::new(v2.key(), v1.key());
let e3: Edge<i32> = Edge::new(*v1.key(), *v3.key());
let e4: Edge<i32> = Edge::new(*v3.key(), *v2.key());
// test with borrow
assert_eq!(0, **e1.from());
assert_eq!(v1.key(), *e1.from());
assert_eq!(1, **e1.to());
assert_eq!(v2.key(), *e1.to());
assert_eq!(1, **e2.from());
assert_eq!(v2.key(), *e2.from());
assert_eq!(0, **e2.to());
assert_eq!(v1.key(), *e2.to());
// test with direct value
assert_eq!(0, *e3.from());
assert_eq!(v1.key(), e3.from());
assert_eq!(2, *e3.to());
assert_eq!(v3.key(), e3.to());
assert_eq!(2, *e4.from());
assert_eq!(v3.key(), e4.from());
assert_eq!(1, *e4.to());
assert_eq!(v2.key(), e4.to());
}
}
|
//! ITP1_10_Dの回答
//! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_10_D](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_10_D)
use std::io::BufRead;
/// ITP1_10_Dの回答
#[allow(dead_code)]
pub fn main() {
let dataset = Dataset::read(std::io::stdin().lock());
let answer = dataset.compute();
println!("{}", answer.p_1);
println!("{}", answer.p_2);
println!("{}", answer.p_3);
println!("{}", answer.p_inf);
}
#[derive(Debug, Eq, PartialEq)]
struct Dataset {
xs: Vec<i32>,
ys: Vec<i32>,
}
impl Dataset {
fn read<T: BufRead>(mut reader: T) -> Self {
let _n = Self::read_n(&mut reader);
let xs = Self::read_vec(&mut reader);
let ys = Self::read_vec(&mut reader);
Dataset { xs, ys }
}
fn compute(&self) -> Answer {
let mut answer = Answer::new();
for i in 0..self.xs.len() {
let x = self.xs[i] as f64;
let y = self.ys[i] as f64;
answer.add_item(x, y);
}
answer.fix();
answer
}
fn read_line<T: BufRead>(mut reader: T) -> String {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
line
}
fn read_n<T: BufRead>(mut reader: T) -> i32 {
Self::read_line(&mut reader).trim().parse().unwrap()
}
fn read_vec<T: BufRead>(mut reader: T) -> Vec<i32> {
Self::read_line(&mut reader)
.trim()
.split(' ')
.map(|x| x.parse().unwrap())
.collect()
}
}
#[derive(Debug)]
struct Answer {
p_1: f64,
p_2: f64,
p_3: f64,
p_inf: f64,
}
impl PartialEq for Answer {
fn eq(&self, other: &Self) -> bool {
let min_error = 0.0001;
(self.p_1 - other.p_1).abs() < min_error
&& (self.p_2 - other.p_2).abs() < min_error
&& (self.p_3 - other.p_3).abs() < min_error
&& (self.p_inf - other.p_inf).abs() < min_error
}
}
impl Answer {
fn new() -> Self {
Answer { p_1: 0f64, p_2: 0f64, p_3: 0f64, p_inf: 0f64 }
}
fn add_item(&mut self, x: f64, y: f64) {
let item = (x - y).abs();
self.p_1 += item;
self.p_2 += item.powi(2);
self.p_3 += item.powi(3);
self.p_inf = if self.p_inf >= item { self.p_inf } else { item };
}
fn fix(&mut self) {
self.p_2 = self.p_2.sqrt();
self.p_3 = self.p_3.powf(1f64 / 3f64);
}
}
#[cfg(test)]
mod test {
use std::io::Cursor;
use super::*;
#[test]
fn test_read_dataset() {
let dataset = Dataset::read(Cursor::new("3\n1 2 3\n2 0 4\n"));
assert_eq!(Dataset { xs: vec![1, 2, 3], ys: vec![2, 0, 4] }, dataset);
}
#[test]
fn test_compute_answer() {
let dataset = Dataset::read(Cursor::new("3\n1 2 3\n2 0 4\n"));
let answer = dataset.compute();
assert_eq!(Answer { p_1: 4f64, p_2: 2.449490, p_3: 2.154435, p_inf: 2f64 }, answer);
}
#[test]
fn test_answer_add() {
let mut answer = Answer::new();
answer.add_item(0f64, 2f64);
assert_eq!(Answer { p_1: 2f64, p_2: 4f64, p_3: 8f64, p_inf: 2f64 }, answer);
}
#[test]
fn test_answer_add_2() {
let mut answer = Answer::new();
answer.add_item(0f64, 2f64);
answer.add_item(3f64, 1f64);
assert_eq!(Answer { p_1: 4f64, p_2: 8f64, p_3: 16f64, p_inf: 2f64 }, answer);
}
#[test]
fn test_answer_fix() {
let mut answer = Answer::new();
answer.add_item(0f64, 2f64);
answer.add_item(3f64, 1f64);
answer.fix();
assert_eq!(Answer { p_1: 4f64, p_2: 8f64.sqrt(), p_3: 16f64.powf(1f64 / 3f64), p_inf: 2f64 }, answer);
}
}
|
extern crate rand;
extern crate common;
use common::*;
use common::HandEnum::*;
use common::HandCard::*;
use common::Turn::*;
use common::Participant::*;
use common::Score::*;
use common::KnockerOrWinner::*;
use std::collections::HashMap;
use rand::{StdRng, SeedableRng, Rng};
macro_rules! s {
($($expr: expr),*) => {
&format!($($expr,)*)
}
}
//NOTE(Ryan1729): debug_assertions only appears to work correctly when the
//crate is not a dylib. Assuming you make this crate *not* a dylib on release,
//these configs should work
#[cfg(debug_assertions)]
#[no_mangle]
pub fn new_state(size: Size) -> State {
//skip the title screen
println!("debug on");
let seed: &[_] = &[42];
let mut rng: StdRng = SeedableRng::from_seed(seed);
make_state(size, false, rng)
}
#[cfg(not(debug_assertions))]
#[no_mangle]
pub fn new_state(size: Size) -> State {
//show the title screen
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|dur| dur.as_secs())
.unwrap_or(42);
println!("{}", timestamp);
let seed: &[_] = &[timestamp as usize];
let rng: StdRng = SeedableRng::from_seed(seed);
make_state(size, true, rng)
}
fn deal(state: &mut State) -> Card {
deal_parts(&mut state.deck, &mut state.pile, &mut state.rng)
}
fn deal_parts(deck: &mut Vec<Card>, pile: &mut Vec<Card>, rng: &mut StdRng) -> Card {
//reshuffle if we run out of cards.
if deck.len() == 0 {
debug_assert!(pile.len() != 0, "deck was empty and so was the pile!");
for card in pile.drain(..) {
deck.push(card);
}
rng.shuffle(deck.as_mut_slice());
};
deck.pop()
.unwrap_or(Card {
suit: Suit::Spades,
value: Value::Ace,
})
}
fn make_state(size: Size, title_screen: bool, mut rng: StdRng) -> State {
let mut deck = Card::all_values();
rng.shuffle(deck.as_mut_slice());
let mut pile = Vec::new();
let player;
let mut cpu_players;
let pile_card = {
let deck_ref = &mut deck;
let pile_ref = &mut pile;
let rng_ref = &mut rng;
player = Hand(deal_parts(deck_ref, pile_ref, rng_ref),
deal_parts(deck_ref, pile_ref, rng_ref),
deal_parts(deck_ref, pile_ref, rng_ref));
let cpu_players_count = rng_ref.gen_range(1, 5);
cpu_players = Vec::new();
for _ in 0..cpu_players_count {
cpu_players.push(Hand(deal_parts(deck_ref, pile_ref, rng_ref),
deal_parts(deck_ref, pile_ref, rng_ref),
deal_parts(deck_ref, pile_ref, rng_ref)));
}
deal_parts(deck_ref, pile_ref, rng_ref)
};
pile.push(pile_card);
State {
rng,
title_screen,
deck,
pile,
player,
cpu_players,
turn: PlayerTurn(None),
turn_count: 0,
summary: String::new(),
ui_context: UIContext::new(),
}
}
#[no_mangle]
//returns true if quit requested
pub fn update_and_render(platform: &Platform, state: &mut State, events: &mut Vec<Event>) -> bool {
if state.title_screen {
for event in events {
cross_mode_event_handling(platform, state, event);
match *event {
Event::Close |
Event::KeyPressed {
key: KeyCode::Escape,
ctrl: _,
shift: _,
} => return true,
Event::KeyPressed {
key: _,
ctrl: _,
shift: _,
} => state.title_screen = false,
_ => (),
}
}
(platform.print_xy)(5, 10, "Click to start.");
false
} else {
game_update_and_render(platform, state, events)
}
}
pub fn game_update_and_render(platform: &Platform,
state: &mut State,
events: &mut Vec<Event>)
-> bool {
let mut left_mouse_pressed = false;
let mut left_mouse_released = false;
for event in events {
cross_mode_event_handling(platform, state, event);
match *event {
Event::KeyPressed {
key: KeyCode::MouseLeft,
ctrl: _,
shift: _,
} => {
left_mouse_pressed = true;
}
Event::KeyReleased {
key: KeyCode::MouseLeft,
ctrl: _,
shift: _,
} => {
left_mouse_released = true;
}
Event::Close |
Event::KeyPressed {
key: KeyCode::Escape,
ctrl: _,
shift: _,
} => return true,
_ => (),
}
}
state.ui_context.frame_init();
let redeal_spec = ButtonSpec {
x: 0,
y: 0,
w: 11,
h: 3,
text: "Redeal".to_string(),
id: 1,
};
if do_button(platform,
&mut state.ui_context,
&redeal_spec,
left_mouse_pressed,
left_mouse_released) {
*state = make_state((platform.size)(), false, state.rng);
}
let size = (platform.size)();
let hand_height = size.height - HAND_HEIGHT_OFFSET;
let mut should_draw_hand = true;
match state.turn.clone() {
PlayerTurn(possible_knocker) => {
if let Some(knocker) = possible_knocker.clone() {
if knocker == Player {
state.turn = Resolution(None);
}
} else {
let knock_spec = ButtonSpec {
x: 0,
y: 3,
w: 11,
h: 3,
text: "Knock".to_string(),
id: 4,
};
if do_button(platform,
&mut state.ui_context,
&knock_spec,
left_mouse_pressed,
left_mouse_released) {
state.turn = CpuTurn(Some(Player));
}
}
if state.deck.len() > 0 {
if do_card_back_button(platform,
&mut state.ui_context,
DECK_X,
DECK_Y,
left_mouse_pressed,
left_mouse_released,
88) {
let card = deal(state);
state.turn = PlayerSelected(card, possible_knocker.clone());
}
}
let selected_top_card = if let Some(top_card) = state.pile.last() {
do_card_button(platform,
&mut state.ui_context,
PILE_X,
PILE_Y,
top_card,
left_mouse_pressed,
left_mouse_released,
100)
} else {
false
};
if selected_top_card {
state.turn = PlayerSelected(state.pile.pop().unwrap(), possible_knocker.clone());
}
}
PlayerSelected(selected_card, possible_knocker) => {
let selection = select_returned_card(platform,
state,
&selected_card,
hand_height,
left_mouse_pressed,
left_mouse_released);
should_draw_hand = false;
match selection {
Some(FromHand(index)) => {
state.pile.push(state.player.swap(index, selected_card));
state.turn = if state.player.is_31() {
Resolution(Some(Player))
} else {
CpuTurn(possible_knocker)
};
}
Some(SelectedCard) => {
state.pile.push(selected_card);
state.turn = CpuTurn(possible_knocker);
}
None => {}
}
if let Some(top_card) = state.pile.last() {
draw_card(platform, PILE_X, PILE_Y, top_card);
}
if state.deck.len() > 0 {
draw_card_back(platform, DECK_X, DECK_Y);
}
state.turn_count += 1;
}
CpuTurn(possible_knocker) => {
let labeled = possible_knocker.clone().map(Knocker);
let turn_result = cpu_turns(state, labeled.clone());
state.turn = if possible_knocker.is_some() && labeled == turn_result {
Resolution(None)
} else {
CpuSummary(turn_result)
}
}
CpuSummary(possible_knocker_or_winner) => {
(platform.print_xy)(12, 2, &state.summary);
let ok_spec = ButtonSpec {
x: 30,
y: 18,
w: 11,
h: 3,
text: "Okay".to_string(),
id: 4,
};
if do_button(platform,
&mut state.ui_context,
&ok_spec,
left_mouse_pressed,
left_mouse_released) {
state.turn = match possible_knocker_or_winner {
Some(Winner(winner)) => Resolution(Some(winner)),
Some(Knocker(Player)) => Resolution(None),
Some(Knocker(p)) => PlayerTurn(Some(p)),
_ => PlayerTurn(None),
}
}
}
Resolution(possible_winner) => {
let mut y = 2;
(platform.print_xy)(15,
y,
s!("You have {} ({})", state.player, state.player.score()));
y += 2;
for (i, cpu_hand) in state.cpu_players.iter().enumerate() {
(platform.print_xy)(15,
y,
s!("{} has {}, ({})", Cpu(i), cpu_hand, cpu_hand.score()));
y += 2;
}
let winners = possible_winner
.map(|v| vec![v])
.unwrap_or_else(|| {
let mut who_scored = HashMap::new();
{
let player_score = state.player.score();
let e = who_scored.entry(player_score).or_insert(Vec::new());
e.push(Player);
}
for i in 0..state.cpu_players.len() {
let cpu_score = state.cpu_players[i].score();
let e = who_scored.entry(cpu_score).or_insert(Vec::new());
e.push(Cpu(i));
}
let winner_key = {
who_scored.keys().max().unwrap().clone()
};
who_scored.remove(&winner_key).unwrap()
});
let mut winner_y = 20 - (winners.len() - 1) as i32;
for winner in winners.iter() {
(platform.print_xy)(10, winner_y, s!("{} won!", winner));
winner_y += 1;
}
}
}
if should_draw_hand {
match state.player {
Hand(ref c1, ref c2, ref c3) => {
let mut x = CARD_OFFSET;
draw_card(platform, x, hand_height, c1);
x += CARD_OFFSET_DELTA;
draw_card(platform, x, hand_height, c2);
x += CARD_OFFSET_DELTA;
draw_card(platform, x, hand_height, c3);
}
}
}
false
}
fn cpu_turns(state: &mut State,
possible_knocker_or_winner: Option<KnockerOrWinner>)
-> Option<KnockerOrWinner> {
state.summary.clear();
let mut possible_result = possible_knocker_or_winner.clone();
for i in 0..state.cpu_players.len() {
possible_result = take_cpu_turn(state, i, possible_result);
match possible_result {
Some(Knocker(ref knocker)) => {
if knocker == &Cpu(i) {
break;
}
}
Some(_) => {
break;
}
None => {}
}
}
possible_result
}
fn take_cpu_turn(state: &mut State,
cpu_index: usize,
possible_knocker_or_winner: Option<KnockerOrWinner>)
-> Option<KnockerOrWinner> {
state.turn_count += 1;
if let Some(Knocker(ref p)) = possible_knocker_or_winner {
if p == &Cpu(cpu_index) {
return Some(Knocker(p.clone()));
}
}
if let Some(cpu_hand) = state.cpu_players.get_mut(cpu_index) {
if let Some(Knocker(_)) = possible_knocker_or_winner {
//don't allow knocking
} else {
if cpu_hand.score() >= Simple(25) ||
(state.turn_count <= 5 && cpu_hand.score() >= Simple(19)) {
state.summary += s!("Cpu {} knocked!\n", cpu_index);
return Some(Knocker(Cpu(cpu_index)));
}
}
let pile_card_is_worth_taking = state
.pile
.last()
.map(|card| match cpu_select_returned_card(cpu_hand, card) {
SelectedCard => false,
_ => true,
})
.unwrap_or(false);
let card = if pile_card_is_worth_taking {
let card = state.pile.pop().unwrap();
state.summary += s!("Cpu {} picked up the {} off the pile\n", cpu_index, card);
card
} else {
let card = deal_parts(&mut state.deck, &mut state.pile, &mut state.rng);
state.summary += s!("Cpu {} drew a card ", cpu_index);
card
};
let choice = cpu_select_returned_card(&cpu_hand, &card);
let returned_card = match choice {
FromHand(card_index) => cpu_hand.swap(card_index, card),
SelectedCard => card,
};
state.summary += s!("and put a {} back on the pile.\n\n", returned_card);
state.pile.push(returned_card);
if cpu_hand.is_31() {
return Some(Winner(Cpu(cpu_index)));
}
}
possible_knocker_or_winner
}
fn cpu_select_returned_card(hand: &HandEnum, card: &Card) -> ReturnSelection {
match hand {
&Hand(ref c1, ref c2, ref c3) => {
let keep = score_cards(c1, c2, c3);
let first = score_cards(card, c2, c3);
let second = score_cards(c1, card, c3);
let third = score_cards(c1, c2, card);
if let Some(max) = [&keep, &first, &second, &third]
.iter()
.max()
.map(|&r| r.clone()) {
if max == keep {
SelectedCard
} else if max == first {
FromHand(FirstCard)
} else if max == second {
FromHand(SecondCard)
} else {
FromHand(ThirdCard)
}
} else {
FromHand(FirstCard)
}
}
}
}
enum ReturnSelection {
FromHand(HandCard),
SelectedCard,
}
use ReturnSelection::*;
fn select_returned_card(platform: &Platform,
state: &mut State,
selected_card: &Card,
hand_height: i32,
left_mouse_pressed: bool,
left_mouse_released: bool)
-> Option<ReturnSelection> {
let mut id = 110;
match state.player {
Hand(ref c1, ref c2, ref c3) => {
let mut x = CARD_OFFSET;
if do_raised_card_button(platform,
&mut state.ui_context,
x,
hand_height,
c1,
left_mouse_pressed,
left_mouse_released,
id) {
return Some(FromHand(FirstCard));
}
x += CARD_OFFSET_DELTA;
id += 1;
if do_raised_card_button(platform,
&mut state.ui_context,
x,
hand_height,
c2,
left_mouse_pressed,
left_mouse_released,
id) {
return Some(FromHand(SecondCard));
}
x += CARD_OFFSET_DELTA;
id += 1;
if do_raised_card_button(platform,
&mut state.ui_context,
x,
hand_height,
c3,
left_mouse_pressed,
left_mouse_released,
id) {
return Some(FromHand(ThirdCard));
}
}
}
id += 1;
if do_card_button(platform,
&mut state.ui_context,
50,
hand_height,
selected_card,
left_mouse_pressed,
left_mouse_released,
id) {
Some(SelectedCard)
} else {
None
}
}
const PILE_X: i32 = 40;
const DECK_X: i32 = PILE_X + CARD_WIDTH + 4;
const PILE_Y: i32 = 10;
const DECK_Y: i32 = PILE_Y;
const CARD_OFFSET: i32 = 5;
const CARD_OFFSET_DELTA: i32 = 6;
const HAND_HEIGHT_OFFSET: i32 = 8;
const CARD_WIDTH: i32 = 16;
const CARD_HEIGHT: i32 = 12;
fn draw_card(platform: &Platform, x: i32, y: i32, card: &Card) {
draw_rect(platform, x, y, CARD_WIDTH, CARD_HEIGHT);
draw_card_value(platform, x + 1, y + 1, card);
}
fn draw_card_back(platform: &Platform, x: i32, y: i32) {
draw_rect(platform, x, y, CARD_WIDTH, CARD_HEIGHT);
draw_card_back_design(platform, x, y);
}
fn draw_card_value(platform: &Platform, x: i32, y: i32, card: &Card) {
(platform.print_xy)(x, y, &card.value.to_string());
(platform.print_xy)(x, y + 1, &card.suit.to_string());
}
fn draw_card_back_design(platform: &Platform, x: i32, y: i32) {
draw_rect(platform, x + 2, y + 1, CARD_WIDTH - 4, CARD_HEIGHT - 2);
}
const CARD_RAISE_OFFSET: i32 = CARD_HEIGHT / 2;
//TODO animation. Maybe put a counter on the UIContext?
fn do_raised_card_button(platform: &Platform,
context: &mut UIContext,
x: i32,
y: i32,
card: &Card,
left_mouse_pressed: bool,
left_mouse_released: bool,
id: UiId)
-> bool {
let mut result = false;
let mouse_pos = (platform.mouse_position)();
let active = context.active == id;
let hot = context.hot == id;
let raised_y = y - CARD_RAISE_OFFSET;
let inside = inside_rect(mouse_pos, x, y, CARD_WIDTH, CARD_HEIGHT) ||
(hot && inside_rect(mouse_pos, x, raised_y, CARD_WIDTH, CARD_HEIGHT));
if active {
if left_mouse_released {
result = hot && inside;
context.set_not_active();
}
} else if hot {
if left_mouse_pressed {
context.set_active(id);
}
}
if inside {
context.set_next_hot(id);
}
if active && (platform.key_pressed)(KeyCode::MouseLeft) {
draw_rect_with(platform,
x,
raised_y,
CARD_WIDTH,
CARD_HEIGHT,
["╔", "═", "╕", "║", "│", "╙", "─", "┘"]);
draw_card_value(platform, x + 1, raised_y + 1, card);
} else if context.hot == id {
draw_rect_with(platform,
x,
raised_y,
CARD_WIDTH,
CARD_HEIGHT,
["┌", "─", "╖", "│", "║", "╘", "═", "╝"]);
draw_card_value(platform, x + 1, raised_y + 1, card);
} else {
draw_card(platform, x, y, card);
}
return result;
}
fn do_card_button(platform: &Platform,
context: &mut UIContext,
x: i32,
y: i32,
card: &Card,
left_mouse_pressed: bool,
left_mouse_released: bool,
id: UiId)
-> bool {
let spec = ButtonSpec {
x,
y,
w: CARD_WIDTH,
h: CARD_HEIGHT,
text: String::new(),
id,
};
let result = do_button(platform,
context,
&spec,
left_mouse_pressed,
left_mouse_released);
draw_card_value(platform, x + 1, y + 1, card);
result
}
fn do_card_back_button(platform: &Platform,
context: &mut UIContext,
x: i32,
y: i32,
left_mouse_pressed: bool,
left_mouse_released: bool,
id: UiId)
-> bool {
let spec = ButtonSpec {
x,
y,
w: CARD_WIDTH,
h: CARD_HEIGHT,
text: String::new(),
id,
};
let result = do_button(platform,
context,
&spec,
left_mouse_pressed,
left_mouse_released);
draw_card_back_design(platform, x, y);
result
}
fn cross_mode_event_handling(platform: &Platform, state: &mut State, event: &Event) {
match *event {
Event::KeyPressed {
key: KeyCode::R,
ctrl: true,
shift: _,
} => {
println!("reset");
*state = new_state((platform.size)());
}
_ => (),
}
}
pub struct ButtonSpec {
pub x: i32,
pub y: i32,
pub w: i32,
pub h: i32,
pub text: String,
pub id: UiId,
}
//calling this once will swallow multiple clicks on the button. We could either
//pass in and return the number of clicks to fix that, or this could simply be
//called multiple times per frame (once for each click).
fn do_button(platform: &Platform,
context: &mut UIContext,
spec: &ButtonSpec,
left_mouse_pressed: bool,
left_mouse_released: bool)
-> bool {
let mut result = false;
let mouse_pos = (platform.mouse_position)();
let inside = inside_rect(mouse_pos, spec.x, spec.y, spec.w, spec.h);
let id = spec.id;
if context.active == id {
if left_mouse_released {
result = context.hot == id && inside;
context.set_not_active();
}
} else if context.hot == id {
if left_mouse_pressed {
context.set_active(id);
}
}
if inside {
context.set_next_hot(id);
}
if context.active == id && (platform.key_pressed)(KeyCode::MouseLeft) {
draw_rect_with(platform,
spec.x,
spec.y,
spec.w,
spec.h,
["╔", "═", "╕", "║", "│", "╙", "─", "┘"]);
} else if context.hot == id {
draw_rect_with(platform,
spec.x,
spec.y,
spec.w,
spec.h,
["┌", "─", "╖", "│", "║", "╘", "═", "╝"]);
} else {
draw_rect(platform, spec.x, spec.y, spec.w, spec.h);
}
print_centered_line(platform, spec.x, spec.y, spec.w, spec.h, &spec.text);
return result;
}
pub fn inside_rect(point: Point, x: i32, y: i32, w: i32, h: i32) -> bool {
x <= point.x && y <= point.y && point.x < x + w && point.y < y + h
}
fn print_centered_line(platform: &Platform, x: i32, y: i32, w: i32, h: i32, text: &str) {
let char_count = text.chars().count();
if char_count == 0 {
return;
}
let x_ = {
let rect_middle = x + (w / 2);
rect_middle - (char_count as f32 / 2.0) as i32
};
let y_ = y + (h / 2);
(platform.print_xy)(x_, y_, &text);
}
fn draw_rect(platform: &Platform, x: i32, y: i32, w: i32, h: i32) {
draw_rect_with(platform,
x,
y,
w,
h,
["┌", "─", "┐", "│", "│", "└", "─", "┘"]);
}
fn draw_rect_with(platform: &Platform, x: i32, y: i32, w: i32, h: i32, edges: [&str; 8]) {
(platform.clear)(Some(Rect::from_values(x, y, w, h)));
let right = x + w - 1;
let bottom = y + h - 1;
// top
(platform.print_xy)(x, y, edges[0]);
for i in (x + 1)..right {
(platform.print_xy)(i, y, edges[1]);
}
(platform.print_xy)(right, y, edges[2]);
// sides
for i in (y + 1)..bottom {
(platform.print_xy)(x, i, edges[3]);
(platform.print_xy)(right, i, edges[4]);
}
//bottom
(platform.print_xy)(x, bottom, edges[5]);
for i in (x + 1)..right {
(platform.print_xy)(i, bottom, edges[6]);
}
(platform.print_xy)(right, bottom, edges[7]);
}
|
use actix_files as fs;
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::Deserialize;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
#[derive(Deserialize)]
struct FormData {
fname: String,
lname: String,
city: String,
}
fn index() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
fn display_user(form: web::Form<FormData>) -> impl Responder {
if form.fname.len() > 24 || form.lname.len() > 24 || form.city.len() > 24 {
return HttpResponse::BadRequest().body("Input too long")
}
let data = format!(
"Hello, {} {}! You live in {}.",
form.fname.to_uppercase(),
form.lname.to_uppercase(),
form.city.to_uppercase(),
);
HttpResponse::Ok().content_type("text/html").body(data)
}
fn main() {
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| {
App::new()
.route("/hello", web::get().to(index))
.route("/show_user", web::post().to(display_user))
.service(fs::Files::new("/", "./static").index_file("index.html"))
})
.bind_ssl("0.0.0.0:8088", builder)
.unwrap()
.run()
.unwrap();
}
|
use crate::{format_context::FormatContext, frame::Frame, packet::Packet, tools};
use ffmpeg_sys_next::*;
use std::ptr::null_mut;
#[derive(Debug)]
pub struct AudioDecoder {
pub identifier: String,
pub stream_index: isize,
pub codec_context: *mut AVCodecContext,
}
impl AudioDecoder {
pub fn new(
identifier: String,
format: &FormatContext,
stream_index: isize,
) -> Result<Self, String> {
unsafe {
let codec = avcodec_find_decoder(format.get_codec_id(stream_index));
let mut codec_context = avcodec_alloc_context3(codec);
check_result!(
avcodec_parameters_to_context(
codec_context,
(**(*format.format_context).streams.offset(stream_index)).codecpar
),
{
avcodec_free_context(&mut codec_context);
}
);
check_result!(avcodec_open2(codec_context, codec, null_mut()), {
avcodec_free_context(&mut codec_context);
});
Ok(AudioDecoder {
identifier,
stream_index,
codec_context,
})
}
}
pub fn get_sample_rate(&self) -> i32 {
unsafe { (*self.codec_context).sample_rate }
}
pub fn get_nb_channels(&self) -> i32 {
unsafe { (*self.codec_context).channels }
}
pub fn get_channel_layout(&self) -> u64 {
unsafe { (*self.codec_context).channel_layout }
}
pub fn get_sample_fmt_name(&self) -> String {
unsafe {
let input_fmt_str = av_get_sample_fmt_name((*self.codec_context).sample_fmt);
tools::to_string(input_fmt_str)
}
}
pub fn decode(&self, packet: &Packet) -> Result<Frame, String> {
if packet.get_stream_index() != self.stream_index {
return Err("bad stream".to_string());
}
unsafe {
check_result!(avcodec_send_packet(self.codec_context, packet.packet));
let frame = av_frame_alloc();
check_result!(avcodec_receive_frame(self.codec_context, frame));
Ok(Frame {
frame,
name: Some(self.identifier.clone()),
index: self.stream_index as usize,
})
}
}
}
impl Drop for AudioDecoder {
fn drop(&mut self) {
unsafe {
if !self.codec_context.is_null() {
avcodec_close(self.codec_context);
avcodec_free_context(&mut self.codec_context);
}
}
}
}
|
#[doc = "Register `TIMCDIER` reader"]
pub type R = crate::R<TIMCDIER_SPEC>;
#[doc = "Register `TIMCDIER` writer"]
pub type W = crate::W<TIMCDIER_SPEC>;
#[doc = "Field `CMP1IE` reader - CMP1IE"]
pub type CMP1IE_R = crate::BitReader<CMP1IE_A>;
#[doc = "CMP1IE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CMP1IE_A {
#[doc = "0: Compare interrupt disabled"]
Disabled = 0,
#[doc = "1: Compare interrupt enabled"]
Enabled = 1,
}
impl From<CMP1IE_A> for bool {
#[inline(always)]
fn from(variant: CMP1IE_A) -> Self {
variant as u8 != 0
}
}
impl CMP1IE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CMP1IE_A {
match self.bits {
false => CMP1IE_A::Disabled,
true => CMP1IE_A::Enabled,
}
}
#[doc = "Compare interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CMP1IE_A::Disabled
}
#[doc = "Compare interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CMP1IE_A::Enabled
}
}
#[doc = "Field `CMP1IE` writer - CMP1IE"]
pub type CMP1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CMP1IE_A>;
impl<'a, REG, const O: u8> CMP1IE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Compare interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CMP1IE_A::Disabled)
}
#[doc = "Compare interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CMP1IE_A::Enabled)
}
}
#[doc = "Field `CMP2IE` reader - CMP2IE"]
pub use CMP1IE_R as CMP2IE_R;
#[doc = "Field `CMP3IE` reader - CMP3IE"]
pub use CMP1IE_R as CMP3IE_R;
#[doc = "Field `CMP4IE` reader - CMP4IE"]
pub use CMP1IE_R as CMP4IE_R;
#[doc = "Field `CMP2IE` writer - CMP2IE"]
pub use CMP1IE_W as CMP2IE_W;
#[doc = "Field `CMP3IE` writer - CMP3IE"]
pub use CMP1IE_W as CMP3IE_W;
#[doc = "Field `CMP4IE` writer - CMP4IE"]
pub use CMP1IE_W as CMP4IE_W;
#[doc = "Field `REPIE` reader - REPIE"]
pub type REPIE_R = crate::BitReader<REPIE_A>;
#[doc = "REPIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum REPIE_A {
#[doc = "0: Repetition interrupt disabled"]
Disabled = 0,
#[doc = "1: Repetition interrupt enabled"]
Enabled = 1,
}
impl From<REPIE_A> for bool {
#[inline(always)]
fn from(variant: REPIE_A) -> Self {
variant as u8 != 0
}
}
impl REPIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> REPIE_A {
match self.bits {
false => REPIE_A::Disabled,
true => REPIE_A::Enabled,
}
}
#[doc = "Repetition interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == REPIE_A::Disabled
}
#[doc = "Repetition interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == REPIE_A::Enabled
}
}
#[doc = "Field `REPIE` writer - REPIE"]
pub type REPIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, REPIE_A>;
impl<'a, REG, const O: u8> REPIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Repetition interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(REPIE_A::Disabled)
}
#[doc = "Repetition interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(REPIE_A::Enabled)
}
}
#[doc = "Field `UPDIE` reader - UPDIE"]
pub type UPDIE_R = crate::BitReader<UPDIE_A>;
#[doc = "UPDIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UPDIE_A {
#[doc = "0: Update interrupt disabled"]
Disabled = 0,
#[doc = "1: Update interrupt enabled"]
Enabled = 1,
}
impl From<UPDIE_A> for bool {
#[inline(always)]
fn from(variant: UPDIE_A) -> Self {
variant as u8 != 0
}
}
impl UPDIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> UPDIE_A {
match self.bits {
false => UPDIE_A::Disabled,
true => UPDIE_A::Enabled,
}
}
#[doc = "Update interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == UPDIE_A::Disabled
}
#[doc = "Update interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == UPDIE_A::Enabled
}
}
#[doc = "Field `UPDIE` writer - UPDIE"]
pub type UPDIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, UPDIE_A>;
impl<'a, REG, const O: u8> UPDIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Update interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(UPDIE_A::Disabled)
}
#[doc = "Update interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(UPDIE_A::Enabled)
}
}
#[doc = "Field `CPT1IE` reader - CPT1IE"]
pub type CPT1IE_R = crate::BitReader<CPT1IE_A>;
#[doc = "CPT1IE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CPT1IE_A {
#[doc = "0: Capture interrupt disabled"]
Disabled = 0,
#[doc = "1: Capture interrupt enabled"]
Enabled = 1,
}
impl From<CPT1IE_A> for bool {
#[inline(always)]
fn from(variant: CPT1IE_A) -> Self {
variant as u8 != 0
}
}
impl CPT1IE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CPT1IE_A {
match self.bits {
false => CPT1IE_A::Disabled,
true => CPT1IE_A::Enabled,
}
}
#[doc = "Capture interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CPT1IE_A::Disabled
}
#[doc = "Capture interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CPT1IE_A::Enabled
}
}
#[doc = "Field `CPT1IE` writer - CPT1IE"]
pub type CPT1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CPT1IE_A>;
impl<'a, REG, const O: u8> CPT1IE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Capture interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CPT1IE_A::Disabled)
}
#[doc = "Capture interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CPT1IE_A::Enabled)
}
}
#[doc = "Field `CPT2IE` reader - CPT2IE"]
pub use CPT1IE_R as CPT2IE_R;
#[doc = "Field `CPT2IE` writer - CPT2IE"]
pub use CPT1IE_W as CPT2IE_W;
#[doc = "Field `SETx1IE` reader - SET1xIE"]
pub type SETX1IE_R = crate::BitReader<SETX1IE_A>;
#[doc = "SET1xIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SETX1IE_A {
#[doc = "0: Tx output set interrupt disabled"]
Disabled = 0,
#[doc = "1: Tx output set interrupt enabled"]
Enabled = 1,
}
impl From<SETX1IE_A> for bool {
#[inline(always)]
fn from(variant: SETX1IE_A) -> Self {
variant as u8 != 0
}
}
impl SETX1IE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SETX1IE_A {
match self.bits {
false => SETX1IE_A::Disabled,
true => SETX1IE_A::Enabled,
}
}
#[doc = "Tx output set interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SETX1IE_A::Disabled
}
#[doc = "Tx output set interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SETX1IE_A::Enabled
}
}
#[doc = "Field `SETx1IE` writer - SET1xIE"]
pub type SETX1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SETX1IE_A>;
impl<'a, REG, const O: u8> SETX1IE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tx output set interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SETX1IE_A::Disabled)
}
#[doc = "Tx output set interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SETX1IE_A::Enabled)
}
}
#[doc = "Field `RSTx1IE` reader - RSTx1IE"]
pub type RSTX1IE_R = crate::BitReader<RSTX1IE_A>;
#[doc = "RSTx1IE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RSTX1IE_A {
#[doc = "0: Tx output reset interrupt disabled"]
Disabled = 0,
#[doc = "1: Tx output reset interrupt enabled"]
Enabled = 1,
}
impl From<RSTX1IE_A> for bool {
#[inline(always)]
fn from(variant: RSTX1IE_A) -> Self {
variant as u8 != 0
}
}
impl RSTX1IE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RSTX1IE_A {
match self.bits {
false => RSTX1IE_A::Disabled,
true => RSTX1IE_A::Enabled,
}
}
#[doc = "Tx output reset interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RSTX1IE_A::Disabled
}
#[doc = "Tx output reset interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RSTX1IE_A::Enabled
}
}
#[doc = "Field `RSTx1IE` writer - RSTx1IE"]
pub type RSTX1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RSTX1IE_A>;
impl<'a, REG, const O: u8> RSTX1IE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tx output reset interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTX1IE_A::Disabled)
}
#[doc = "Tx output reset interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTX1IE_A::Enabled)
}
}
#[doc = "Field `RSTx2IE` reader - RSTx2IE"]
pub use RSTX1IE_R as RSTX2IE_R;
#[doc = "Field `RSTx2IE` writer - RSTx2IE"]
pub use RSTX1IE_W as RSTX2IE_W;
#[doc = "Field `SETx2IE` reader - SETx2IE"]
pub use SETX1IE_R as SETX2IE_R;
#[doc = "Field `SETx2IE` writer - SETx2IE"]
pub use SETX1IE_W as SETX2IE_W;
#[doc = "Field `RSTIE` reader - RSTIE"]
pub type RSTIE_R = crate::BitReader<RSTIE_A>;
#[doc = "RSTIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RSTIE_A {
#[doc = "0: Timer x counter/reset roll-over interrupt disabled"]
Disabled = 0,
#[doc = "1: Timer x counter/reset roll-over interrupt enabled"]
Enabled = 1,
}
impl From<RSTIE_A> for bool {
#[inline(always)]
fn from(variant: RSTIE_A) -> Self {
variant as u8 != 0
}
}
impl RSTIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RSTIE_A {
match self.bits {
false => RSTIE_A::Disabled,
true => RSTIE_A::Enabled,
}
}
#[doc = "Timer x counter/reset roll-over interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RSTIE_A::Disabled
}
#[doc = "Timer x counter/reset roll-over interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RSTIE_A::Enabled
}
}
#[doc = "Field `RSTIE` writer - RSTIE"]
pub type RSTIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RSTIE_A>;
impl<'a, REG, const O: u8> RSTIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Timer x counter/reset roll-over interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTIE_A::Disabled)
}
#[doc = "Timer x counter/reset roll-over interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTIE_A::Enabled)
}
}
#[doc = "Field `DLYPRTIE` reader - DLYPRTIE"]
pub type DLYPRTIE_R = crate::BitReader<DLYPRTIE_A>;
#[doc = "DLYPRTIE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DLYPRTIE_A {
#[doc = "0: Delayed protection interrupt disabled"]
Disabled = 0,
#[doc = "1: Delayed protection interrupt enabled"]
Enabled = 1,
}
impl From<DLYPRTIE_A> for bool {
#[inline(always)]
fn from(variant: DLYPRTIE_A) -> Self {
variant as u8 != 0
}
}
impl DLYPRTIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DLYPRTIE_A {
match self.bits {
false => DLYPRTIE_A::Disabled,
true => DLYPRTIE_A::Enabled,
}
}
#[doc = "Delayed protection interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DLYPRTIE_A::Disabled
}
#[doc = "Delayed protection interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DLYPRTIE_A::Enabled
}
}
#[doc = "Field `DLYPRTIE` writer - DLYPRTIE"]
pub type DLYPRTIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DLYPRTIE_A>;
impl<'a, REG, const O: u8> DLYPRTIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Delayed protection interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DLYPRTIE_A::Disabled)
}
#[doc = "Delayed protection interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DLYPRTIE_A::Enabled)
}
}
#[doc = "Field `CMP1DE` reader - CMP1DE"]
pub type CMP1DE_R = crate::BitReader<CMP1DE_A>;
#[doc = "CMP1DE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CMP1DE_A {
#[doc = "0: Compare DMA request disabled"]
Disabled = 0,
#[doc = "1: Compare DMA request enabled"]
Enabled = 1,
}
impl From<CMP1DE_A> for bool {
#[inline(always)]
fn from(variant: CMP1DE_A) -> Self {
variant as u8 != 0
}
}
impl CMP1DE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CMP1DE_A {
match self.bits {
false => CMP1DE_A::Disabled,
true => CMP1DE_A::Enabled,
}
}
#[doc = "Compare DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CMP1DE_A::Disabled
}
#[doc = "Compare DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CMP1DE_A::Enabled
}
}
#[doc = "Field `CMP1DE` writer - CMP1DE"]
pub type CMP1DE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CMP1DE_A>;
impl<'a, REG, const O: u8> CMP1DE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Compare DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CMP1DE_A::Disabled)
}
#[doc = "Compare DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CMP1DE_A::Enabled)
}
}
#[doc = "Field `CMP2DE` reader - CMP2DE"]
pub use CMP1DE_R as CMP2DE_R;
#[doc = "Field `CMP3DE` reader - CMP3DE"]
pub use CMP1DE_R as CMP3DE_R;
#[doc = "Field `CMP4DE` reader - CMP4DE"]
pub use CMP1DE_R as CMP4DE_R;
#[doc = "Field `CMP2DE` writer - CMP2DE"]
pub use CMP1DE_W as CMP2DE_W;
#[doc = "Field `CMP3DE` writer - CMP3DE"]
pub use CMP1DE_W as CMP3DE_W;
#[doc = "Field `CMP4DE` writer - CMP4DE"]
pub use CMP1DE_W as CMP4DE_W;
#[doc = "Field `REPDE` reader - REPDE"]
pub type REPDE_R = crate::BitReader<REPDE_A>;
#[doc = "REPDE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum REPDE_A {
#[doc = "0: Repetition DMA request disabled"]
Disabled = 0,
#[doc = "1: Repetition DMA request enabled"]
Enabled = 1,
}
impl From<REPDE_A> for bool {
#[inline(always)]
fn from(variant: REPDE_A) -> Self {
variant as u8 != 0
}
}
impl REPDE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> REPDE_A {
match self.bits {
false => REPDE_A::Disabled,
true => REPDE_A::Enabled,
}
}
#[doc = "Repetition DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == REPDE_A::Disabled
}
#[doc = "Repetition DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == REPDE_A::Enabled
}
}
#[doc = "Field `REPDE` writer - REPDE"]
pub type REPDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, REPDE_A>;
impl<'a, REG, const O: u8> REPDE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Repetition DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(REPDE_A::Disabled)
}
#[doc = "Repetition DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(REPDE_A::Enabled)
}
}
#[doc = "Field `UPDDE` reader - UPDDE"]
pub type UPDDE_R = crate::BitReader<UPDDE_A>;
#[doc = "UPDDE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UPDDE_A {
#[doc = "0: Update DMA request disabled"]
Disabled = 0,
#[doc = "1: Update DMA request enabled"]
Enabled = 1,
}
impl From<UPDDE_A> for bool {
#[inline(always)]
fn from(variant: UPDDE_A) -> Self {
variant as u8 != 0
}
}
impl UPDDE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> UPDDE_A {
match self.bits {
false => UPDDE_A::Disabled,
true => UPDDE_A::Enabled,
}
}
#[doc = "Update DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == UPDDE_A::Disabled
}
#[doc = "Update DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == UPDDE_A::Enabled
}
}
#[doc = "Field `UPDDE` writer - UPDDE"]
pub type UPDDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, UPDDE_A>;
impl<'a, REG, const O: u8> UPDDE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Update DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(UPDDE_A::Disabled)
}
#[doc = "Update DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(UPDDE_A::Enabled)
}
}
#[doc = "Field `CPT1DE` reader - CPT1DE"]
pub type CPT1DE_R = crate::BitReader<CPT1DE_A>;
#[doc = "CPT1DE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CPT1DE_A {
#[doc = "0: Capture DMA request disabled"]
Disabled = 0,
#[doc = "1: Capture DMA request enabled"]
Enabled = 1,
}
impl From<CPT1DE_A> for bool {
#[inline(always)]
fn from(variant: CPT1DE_A) -> Self {
variant as u8 != 0
}
}
impl CPT1DE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CPT1DE_A {
match self.bits {
false => CPT1DE_A::Disabled,
true => CPT1DE_A::Enabled,
}
}
#[doc = "Capture DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CPT1DE_A::Disabled
}
#[doc = "Capture DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CPT1DE_A::Enabled
}
}
#[doc = "Field `CPT1DE` writer - CPT1DE"]
pub type CPT1DE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CPT1DE_A>;
impl<'a, REG, const O: u8> CPT1DE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Capture DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CPT1DE_A::Disabled)
}
#[doc = "Capture DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CPT1DE_A::Enabled)
}
}
#[doc = "Field `CPT2DE` reader - CPT2DE"]
pub use CPT1DE_R as CPT2DE_R;
#[doc = "Field `CPT2DE` writer - CPT2DE"]
pub use CPT1DE_W as CPT2DE_W;
#[doc = "Field `SETx1DE` reader - SET1xDE"]
pub type SETX1DE_R = crate::BitReader<SETX1DE_A>;
#[doc = "SET1xDE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SETX1DE_A {
#[doc = "0: Tx output set DMA request disabled"]
Disabled = 0,
#[doc = "1: Tx output set DMA request enabled"]
Enabled = 1,
}
impl From<SETX1DE_A> for bool {
#[inline(always)]
fn from(variant: SETX1DE_A) -> Self {
variant as u8 != 0
}
}
impl SETX1DE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SETX1DE_A {
match self.bits {
false => SETX1DE_A::Disabled,
true => SETX1DE_A::Enabled,
}
}
#[doc = "Tx output set DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SETX1DE_A::Disabled
}
#[doc = "Tx output set DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SETX1DE_A::Enabled
}
}
#[doc = "Field `SETx1DE` writer - SET1xDE"]
pub type SETX1DE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SETX1DE_A>;
impl<'a, REG, const O: u8> SETX1DE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tx output set DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SETX1DE_A::Disabled)
}
#[doc = "Tx output set DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SETX1DE_A::Enabled)
}
}
#[doc = "Field `RSTx1DE` reader - RSTx1DE"]
pub type RSTX1DE_R = crate::BitReader<RSTX1DE_A>;
#[doc = "RSTx1DE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RSTX1DE_A {
#[doc = "0: Tx output reset DMA request disabled"]
Disabled = 0,
#[doc = "1: Tx output reset DMA request enabled"]
Enabled = 1,
}
impl From<RSTX1DE_A> for bool {
#[inline(always)]
fn from(variant: RSTX1DE_A) -> Self {
variant as u8 != 0
}
}
impl RSTX1DE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RSTX1DE_A {
match self.bits {
false => RSTX1DE_A::Disabled,
true => RSTX1DE_A::Enabled,
}
}
#[doc = "Tx output reset DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RSTX1DE_A::Disabled
}
#[doc = "Tx output reset DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RSTX1DE_A::Enabled
}
}
#[doc = "Field `RSTx1DE` writer - RSTx1DE"]
pub type RSTX1DE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RSTX1DE_A>;
impl<'a, REG, const O: u8> RSTX1DE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tx output reset DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTX1DE_A::Disabled)
}
#[doc = "Tx output reset DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTX1DE_A::Enabled)
}
}
#[doc = "Field `RSTx2DE` reader - RSTx2DE"]
pub use RSTX1DE_R as RSTX2DE_R;
#[doc = "Field `RSTx2DE` writer - RSTx2DE"]
pub use RSTX1DE_W as RSTX2DE_W;
#[doc = "Field `SETx2DE` reader - SETx2DE"]
pub use SETX1DE_R as SETX2DE_R;
#[doc = "Field `SETx2DE` writer - SETx2DE"]
pub use SETX1DE_W as SETX2DE_W;
#[doc = "Field `RSTDE` reader - RSTDE"]
pub type RSTDE_R = crate::BitReader<RSTDE_A>;
#[doc = "RSTDE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RSTDE_A {
#[doc = "0: Timer x counter reset/roll-over DMA request disabled"]
Disabled = 0,
#[doc = "1: Timer x counter reset/roll-over DMA request enabled"]
Enabled = 1,
}
impl From<RSTDE_A> for bool {
#[inline(always)]
fn from(variant: RSTDE_A) -> Self {
variant as u8 != 0
}
}
impl RSTDE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RSTDE_A {
match self.bits {
false => RSTDE_A::Disabled,
true => RSTDE_A::Enabled,
}
}
#[doc = "Timer x counter reset/roll-over DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RSTDE_A::Disabled
}
#[doc = "Timer x counter reset/roll-over DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RSTDE_A::Enabled
}
}
#[doc = "Field `RSTDE` writer - RSTDE"]
pub type RSTDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RSTDE_A>;
impl<'a, REG, const O: u8> RSTDE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Timer x counter reset/roll-over DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTDE_A::Disabled)
}
#[doc = "Timer x counter reset/roll-over DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RSTDE_A::Enabled)
}
}
#[doc = "Field `DLYPRTDE` reader - DLYPRTDE"]
pub type DLYPRTDE_R = crate::BitReader<DLYPRTDE_A>;
#[doc = "DLYPRTDE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DLYPRTDE_A {
#[doc = "0: Delayed protection DMA request disabled"]
Disabled = 0,
#[doc = "1: Delayed protection DMA request enabled"]
Enabled = 1,
}
impl From<DLYPRTDE_A> for bool {
#[inline(always)]
fn from(variant: DLYPRTDE_A) -> Self {
variant as u8 != 0
}
}
impl DLYPRTDE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DLYPRTDE_A {
match self.bits {
false => DLYPRTDE_A::Disabled,
true => DLYPRTDE_A::Enabled,
}
}
#[doc = "Delayed protection DMA request disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DLYPRTDE_A::Disabled
}
#[doc = "Delayed protection DMA request enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DLYPRTDE_A::Enabled
}
}
#[doc = "Field `DLYPRTDE` writer - DLYPRTDE"]
pub type DLYPRTDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DLYPRTDE_A>;
impl<'a, REG, const O: u8> DLYPRTDE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Delayed protection DMA request disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DLYPRTDE_A::Disabled)
}
#[doc = "Delayed protection DMA request enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DLYPRTDE_A::Enabled)
}
}
impl R {
#[doc = "Bit 0 - CMP1IE"]
#[inline(always)]
pub fn cmp1ie(&self) -> CMP1IE_R {
CMP1IE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - CMP2IE"]
#[inline(always)]
pub fn cmp2ie(&self) -> CMP2IE_R {
CMP2IE_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - CMP3IE"]
#[inline(always)]
pub fn cmp3ie(&self) -> CMP3IE_R {
CMP3IE_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - CMP4IE"]
#[inline(always)]
pub fn cmp4ie(&self) -> CMP4IE_R {
CMP4IE_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - REPIE"]
#[inline(always)]
pub fn repie(&self) -> REPIE_R {
REPIE_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 6 - UPDIE"]
#[inline(always)]
pub fn updie(&self) -> UPDIE_R {
UPDIE_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - CPT1IE"]
#[inline(always)]
pub fn cpt1ie(&self) -> CPT1IE_R {
CPT1IE_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - CPT2IE"]
#[inline(always)]
pub fn cpt2ie(&self) -> CPT2IE_R {
CPT2IE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - SET1xIE"]
#[inline(always)]
pub fn setx1ie(&self) -> SETX1IE_R {
SETX1IE_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - RSTx1IE"]
#[inline(always)]
pub fn rstx1ie(&self) -> RSTX1IE_R {
RSTX1IE_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - SETx2IE"]
#[inline(always)]
pub fn setx2ie(&self) -> SETX2IE_R {
SETX2IE_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - RSTx2IE"]
#[inline(always)]
pub fn rstx2ie(&self) -> RSTX2IE_R {
RSTX2IE_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - RSTIE"]
#[inline(always)]
pub fn rstie(&self) -> RSTIE_R {
RSTIE_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - DLYPRTIE"]
#[inline(always)]
pub fn dlyprtie(&self) -> DLYPRTIE_R {
DLYPRTIE_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 16 - CMP1DE"]
#[inline(always)]
pub fn cmp1de(&self) -> CMP1DE_R {
CMP1DE_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - CMP2DE"]
#[inline(always)]
pub fn cmp2de(&self) -> CMP2DE_R {
CMP2DE_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - CMP3DE"]
#[inline(always)]
pub fn cmp3de(&self) -> CMP3DE_R {
CMP3DE_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - CMP4DE"]
#[inline(always)]
pub fn cmp4de(&self) -> CMP4DE_R {
CMP4DE_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - REPDE"]
#[inline(always)]
pub fn repde(&self) -> REPDE_R {
REPDE_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 22 - UPDDE"]
#[inline(always)]
pub fn updde(&self) -> UPDDE_R {
UPDDE_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - CPT1DE"]
#[inline(always)]
pub fn cpt1de(&self) -> CPT1DE_R {
CPT1DE_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - CPT2DE"]
#[inline(always)]
pub fn cpt2de(&self) -> CPT2DE_R {
CPT2DE_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - SET1xDE"]
#[inline(always)]
pub fn setx1de(&self) -> SETX1DE_R {
SETX1DE_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - RSTx1DE"]
#[inline(always)]
pub fn rstx1de(&self) -> RSTX1DE_R {
RSTX1DE_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - SETx2DE"]
#[inline(always)]
pub fn setx2de(&self) -> SETX2DE_R {
SETX2DE_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - RSTx2DE"]
#[inline(always)]
pub fn rstx2de(&self) -> RSTX2DE_R {
RSTX2DE_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - RSTDE"]
#[inline(always)]
pub fn rstde(&self) -> RSTDE_R {
RSTDE_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - DLYPRTDE"]
#[inline(always)]
pub fn dlyprtde(&self) -> DLYPRTDE_R {
DLYPRTDE_R::new(((self.bits >> 30) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - CMP1IE"]
#[inline(always)]
#[must_use]
pub fn cmp1ie(&mut self) -> CMP1IE_W<TIMCDIER_SPEC, 0> {
CMP1IE_W::new(self)
}
#[doc = "Bit 1 - CMP2IE"]
#[inline(always)]
#[must_use]
pub fn cmp2ie(&mut self) -> CMP2IE_W<TIMCDIER_SPEC, 1> {
CMP2IE_W::new(self)
}
#[doc = "Bit 2 - CMP3IE"]
#[inline(always)]
#[must_use]
pub fn cmp3ie(&mut self) -> CMP3IE_W<TIMCDIER_SPEC, 2> {
CMP3IE_W::new(self)
}
#[doc = "Bit 3 - CMP4IE"]
#[inline(always)]
#[must_use]
pub fn cmp4ie(&mut self) -> CMP4IE_W<TIMCDIER_SPEC, 3> {
CMP4IE_W::new(self)
}
#[doc = "Bit 4 - REPIE"]
#[inline(always)]
#[must_use]
pub fn repie(&mut self) -> REPIE_W<TIMCDIER_SPEC, 4> {
REPIE_W::new(self)
}
#[doc = "Bit 6 - UPDIE"]
#[inline(always)]
#[must_use]
pub fn updie(&mut self) -> UPDIE_W<TIMCDIER_SPEC, 6> {
UPDIE_W::new(self)
}
#[doc = "Bit 7 - CPT1IE"]
#[inline(always)]
#[must_use]
pub fn cpt1ie(&mut self) -> CPT1IE_W<TIMCDIER_SPEC, 7> {
CPT1IE_W::new(self)
}
#[doc = "Bit 8 - CPT2IE"]
#[inline(always)]
#[must_use]
pub fn cpt2ie(&mut self) -> CPT2IE_W<TIMCDIER_SPEC, 8> {
CPT2IE_W::new(self)
}
#[doc = "Bit 9 - SET1xIE"]
#[inline(always)]
#[must_use]
pub fn setx1ie(&mut self) -> SETX1IE_W<TIMCDIER_SPEC, 9> {
SETX1IE_W::new(self)
}
#[doc = "Bit 10 - RSTx1IE"]
#[inline(always)]
#[must_use]
pub fn rstx1ie(&mut self) -> RSTX1IE_W<TIMCDIER_SPEC, 10> {
RSTX1IE_W::new(self)
}
#[doc = "Bit 11 - SETx2IE"]
#[inline(always)]
#[must_use]
pub fn setx2ie(&mut self) -> SETX2IE_W<TIMCDIER_SPEC, 11> {
SETX2IE_W::new(self)
}
#[doc = "Bit 12 - RSTx2IE"]
#[inline(always)]
#[must_use]
pub fn rstx2ie(&mut self) -> RSTX2IE_W<TIMCDIER_SPEC, 12> {
RSTX2IE_W::new(self)
}
#[doc = "Bit 13 - RSTIE"]
#[inline(always)]
#[must_use]
pub fn rstie(&mut self) -> RSTIE_W<TIMCDIER_SPEC, 13> {
RSTIE_W::new(self)
}
#[doc = "Bit 14 - DLYPRTIE"]
#[inline(always)]
#[must_use]
pub fn dlyprtie(&mut self) -> DLYPRTIE_W<TIMCDIER_SPEC, 14> {
DLYPRTIE_W::new(self)
}
#[doc = "Bit 16 - CMP1DE"]
#[inline(always)]
#[must_use]
pub fn cmp1de(&mut self) -> CMP1DE_W<TIMCDIER_SPEC, 16> {
CMP1DE_W::new(self)
}
#[doc = "Bit 17 - CMP2DE"]
#[inline(always)]
#[must_use]
pub fn cmp2de(&mut self) -> CMP2DE_W<TIMCDIER_SPEC, 17> {
CMP2DE_W::new(self)
}
#[doc = "Bit 18 - CMP3DE"]
#[inline(always)]
#[must_use]
pub fn cmp3de(&mut self) -> CMP3DE_W<TIMCDIER_SPEC, 18> {
CMP3DE_W::new(self)
}
#[doc = "Bit 19 - CMP4DE"]
#[inline(always)]
#[must_use]
pub fn cmp4de(&mut self) -> CMP4DE_W<TIMCDIER_SPEC, 19> {
CMP4DE_W::new(self)
}
#[doc = "Bit 20 - REPDE"]
#[inline(always)]
#[must_use]
pub fn repde(&mut self) -> REPDE_W<TIMCDIER_SPEC, 20> {
REPDE_W::new(self)
}
#[doc = "Bit 22 - UPDDE"]
#[inline(always)]
#[must_use]
pub fn updde(&mut self) -> UPDDE_W<TIMCDIER_SPEC, 22> {
UPDDE_W::new(self)
}
#[doc = "Bit 23 - CPT1DE"]
#[inline(always)]
#[must_use]
pub fn cpt1de(&mut self) -> CPT1DE_W<TIMCDIER_SPEC, 23> {
CPT1DE_W::new(self)
}
#[doc = "Bit 24 - CPT2DE"]
#[inline(always)]
#[must_use]
pub fn cpt2de(&mut self) -> CPT2DE_W<TIMCDIER_SPEC, 24> {
CPT2DE_W::new(self)
}
#[doc = "Bit 25 - SET1xDE"]
#[inline(always)]
#[must_use]
pub fn setx1de(&mut self) -> SETX1DE_W<TIMCDIER_SPEC, 25> {
SETX1DE_W::new(self)
}
#[doc = "Bit 26 - RSTx1DE"]
#[inline(always)]
#[must_use]
pub fn rstx1de(&mut self) -> RSTX1DE_W<TIMCDIER_SPEC, 26> {
RSTX1DE_W::new(self)
}
#[doc = "Bit 27 - SETx2DE"]
#[inline(always)]
#[must_use]
pub fn setx2de(&mut self) -> SETX2DE_W<TIMCDIER_SPEC, 27> {
SETX2DE_W::new(self)
}
#[doc = "Bit 28 - RSTx2DE"]
#[inline(always)]
#[must_use]
pub fn rstx2de(&mut self) -> RSTX2DE_W<TIMCDIER_SPEC, 28> {
RSTX2DE_W::new(self)
}
#[doc = "Bit 29 - RSTDE"]
#[inline(always)]
#[must_use]
pub fn rstde(&mut self) -> RSTDE_W<TIMCDIER_SPEC, 29> {
RSTDE_W::new(self)
}
#[doc = "Bit 30 - DLYPRTDE"]
#[inline(always)]
#[must_use]
pub fn dlyprtde(&mut self) -> DLYPRTDE_W<TIMCDIER_SPEC, 30> {
DLYPRTDE_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "TIMxDIER5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timcdier::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`timcdier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TIMCDIER_SPEC;
impl crate::RegisterSpec for TIMCDIER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`timcdier::R`](R) reader structure"]
impl crate::Readable for TIMCDIER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`timcdier::W`](W) writer structure"]
impl crate::Writable for TIMCDIER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets TIMCDIER to value 0"]
impl crate::Resettable for TIMCDIER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Base stats
// IMports
use crate::{Ability, BodyColor, EggGroup, GrowthRate, Item, Type};
/// Stats
#[derive(PartialEq, Clone, Copy, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct Stats {
/// Hp
pub hp: u8,
/// Attack
pub atk: u8,
/// Defense
pub def: u8,
/// Speed
pub speed: u8,
/// Special attack
pub sp_atk: u8,
/// Special defense
pub sp_def: u8,
}
/// Base stats
#[derive(PartialEq, Clone, Copy, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct BaseStats {
// Base stats
pub stats: Stats,
/// Types
pub types: [Type; 2],
/// Catch rate
pub catch_rate: u8,
/// Exp yield
pub exp_yield: u8,
// Ev yield
pub ev_yield: Stats,
/// Items
pub items: [Option<Item>; 2],
/// Gender
pub gender: Gender,
/// Egg cycles
pub egg_cycles: u8,
/// Friendship
pub friendship: u8,
/// Growth Rate
pub growth_rate: GrowthRate,
/// Egg groups
pub egg_groups: [EggGroup; 2],
/// Abilities
pub abilities: [Option<Ability>; 2],
/// Safari zone flee rate
pub safari_zone_flee_rate: u8,
/// Body color
pub body_color: BodyColor,
/// No flip
pub no_flip: bool,
}
/// Pokemon gender
#[derive(PartialEq, Clone, Copy, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(tag = "type")]
pub enum Gender {
PercentFemale { p: f32 },
AlwaysMale,
AlwaysFemale,
Genderless,
}
|
use sdl2::pixels::PixelFormatEnum;
use ted_interface::*;
use self::rand::Rng;
use *;
const TERRAIN_IMAGE_ROWS:u32=10;
const TERRAIN_WIDTH: u32=40;
const CHUNK_WIDTH_SQUARES: u32=10;
const CHUNK_WIDTH_PIXELS: u32=CHUNK_WIDTH_SQUARES*TERRAIN_WIDTH;
const PARTICLE_COUNT: usize=10;
const PARTICLE_TURN_SPEED: f64=0.1;
const PARTICLE_CORRECTION_SPEED: f64=PARTICLE_SPEED;
const PARTICLE_CORRECTION_THRESHOLD: f64=CHUNK_WIDTH_PIXELS as f64/4.0;
const PARTICLE_SPEED: f64=1.5;
const FLOWER_CHANCE: usize=15;
const FLOWER_SPRITE: u32=13;
const FLOWER_SPRITE_END: u32=14; //end of flower variants, inclusive
const LONG_GRASS_CHANCE: usize=15;
const LONG_GRASS_SPRITE: u32=16;
const LONG_GRASS_SPRITE_END: u32=16;
pub fn direction(x1: f64, y1: f64, x2: f64, y2: f64)->f64{
let dx=x2-x1;
let dy=y2-y1;
match dx{
_ if dx==0.0=>{
if dy>0.0 {std::f64::consts::PI/2.0}
else {3.0*std::f64::consts::PI/2.0}
},
_=>{
let div=dy/dx;
let mut ac=div.atan();
ac+=if dx<0.0 {
std::f64::consts::PI
} else {0.0};
ac+if ac<0.0 {std::f64::consts::PI*2.0} else {0.0}
}
}
}
pub fn distance(x1: f64, y1: f64, x2: f64, y2: f64)->f64{
((x1-x2).powi(2)+(y1-y2).powi(2)).sqrt()
}
pub struct Particle{
pub x: f64,
pub y: f64,
pub direction: f64
}
pub struct GrassBiome{
pub particles: Vec<Particle>
}
pub enum ChunkEffect{
NoEffects,
GrassBiome(GrassBiome)
}
pub struct Chunk<'a>{
pub static_image: Texture<'a>, //non animated
pub image: Texture<'a>, //whole thing
pub default_square: TerrainSprite,
pub specific_effects: ChunkEffect //effects based on biome type
}
pub fn draw_terrain_image(canvas: &mut Canvas<sdl2::video::Window>, image_loader: &ImageLoader, sprite: TerrainSprite, x: i32, y:i32){
let sprite=sprite.sprite;
let src_rect=Rect::new( ((sprite%TERRAIN_IMAGE_ROWS)*TERRAIN_WIDTH) as i32,
((sprite/TERRAIN_IMAGE_ROWS)*TERRAIN_WIDTH) as i32,
TERRAIN_WIDTH,TERRAIN_WIDTH);
let dst_rect=Rect::new( x,
y,
TERRAIN_WIDTH,TERRAIN_WIDTH);
canvas.copy(&image_loader.terrain_images,Some(src_rect),Some(dst_rect)).expect("Could not draw terrain image");
}
pub fn process_update_frame(canvas: &mut Canvas<sdl2::video::Window>, frame_state: &mut FrameState, image_loader: &mut ImageLoader, mut terrain_update_frame: TerrainUpdateFrame){
for (x,y,mut sprites) in terrain_update_frame.0.drain(..){
let cx=if x>=0 {x/(CHUNK_WIDTH_SQUARES as i64)} else {(x+1)/(CHUNK_WIDTH_SQUARES as i64)-1};//-1 is because rust rounds towards zero, +1 because zero is positive.
let cy=if y>=0 {y/(CHUNK_WIDTH_SQUARES as i64)} else {(y+1)/(CHUNK_WIDTH_SQUARES as i64)-1};
let chunk=frame_state.chunks.get_mut(&(cx,cy));
if chunk.is_none(){
continue;
}
let chunk=chunk.unwrap();
let sx=x as i32%(CHUNK_WIDTH_SQUARES as i32);//Rust mod is also weird
let sx=if sx>=0 {sx} else {sx+CHUNK_WIDTH_SQUARES as i32};
let sy=y as i32%(CHUNK_WIDTH_SQUARES as i32);
let sy=if sy>=0 {sy} else {sy+CHUNK_WIDTH_SQUARES as i32};
let default_square=&chunk.default_square;
canvas.with_texture_canvas(&mut chunk.static_image,|canvas|{
for sprite in Some(default_square).into_iter().map(|x|x.clone()).chain(sprites.drain(..)){
draw_terrain_image(canvas,
image_loader,
sprite,
sx*(TERRAIN_WIDTH as i32),
sy*(TERRAIN_WIDTH as i32));
}
}).expect("Unable to draw to chunk static image for update");
}
}
pub fn create_grass_effects(frame: &mut TerrainFrame)->GrassBiome{
let mut rng=rand::thread_rng();
let mut particles=Vec::new();
for _ in 0..PARTICLE_COUNT{
particles.push(
Particle{
x: rng.gen_range(0.0,CHUNK_WIDTH_PIXELS as f64),
y: rng.gen_range(0.0,CHUNK_WIDTH_PIXELS as f64),
direction: rng.gen_range(0.0, 6.28)
}
)
}
for square in frame.terrains.iter_mut(){
if square.len()==0{
if rng.gen_range(0,FLOWER_CHANCE)==0{
square.push(TerrainSprite{sprite: rng.gen_range(FLOWER_SPRITE, FLOWER_SPRITE_END+1)});
}
else if rng.gen_range(0, LONG_GRASS_CHANCE)==0{
square.push(TerrainSprite{sprite: rng.gen_range(LONG_GRASS_SPRITE, LONG_GRASS_SPRITE_END+1)});
}
}
}
GrassBiome{
particles: particles
}
}
pub fn create_effects(frame: &mut TerrainFrame)->ChunkEffect{
match frame.biome_type{
BiomeType::GrassBiome=>ChunkEffect::GrassBiome(create_grass_effects(frame)),
_=>ChunkEffect::NoEffects
}
}
pub fn process_terrain_frame<'a>(
canvas: &mut Canvas<sdl2::video::Window>,
texture_creator: &'a TextureCreator<sdl2::video::WindowContext>,
frame_state: &mut FrameState<'a>,
image_loader: &mut ImageLoader,
mut terrain_frame: TerrainFrame){
let effects=create_effects(&mut terrain_frame);
let mut static_image=texture_creator.create_texture_target(
PixelFormatEnum::ARGB4444,
CHUNK_WIDTH_PIXELS,
CHUNK_WIDTH_PIXELS
).expect("Unable to create static image");
canvas.with_texture_canvas(&mut static_image,|canvas|{
let s=terrain_frame.terrains.len() as u32;
for (square,i) in terrain_frame.terrains.iter().zip(0..s){
for sprite in Some(terrain_frame.base).iter().chain(square.iter()){
let x=(i%CHUNK_WIDTH_SQUARES)*TERRAIN_WIDTH;//sends in rows
let y=(i/CHUNK_WIDTH_SQUARES)*TERRAIN_WIDTH;
draw_terrain_image(canvas, image_loader, sprite.clone(), x as i32, y as i32);
}
}
}).expect("Unable to draw terrain frame");
let image=texture_creator.create_texture_target(
PixelFormatEnum::ARGB4444,
CHUNK_WIDTH_PIXELS,
CHUNK_WIDTH_PIXELS
).expect("could not create empty terrain frame image");
frame_state.chunks.insert(
(terrain_frame.x,terrain_frame.y),
Chunk{
static_image: static_image,
image: image,
default_square: terrain_frame.base,
specific_effects: effects
}
);
}
pub fn step_particle(particle: &mut Particle){
let mut rng=rand::thread_rng();
particle.direction+=rng.gen_range(0.0,PARTICLE_TURN_SPEED)*2.0-PARTICLE_TURN_SPEED;
particle.direction%=std::f64::consts::PI*2.0;
particle.x+=particle.direction.cos()*rng.gen_range(0.0, PARTICLE_SPEED);
particle.y+=particle.direction.sin()*rng.gen_range(0.0, PARTICLE_SPEED);
let direction_to_center=direction(particle.x, particle.y, (CHUNK_WIDTH_PIXELS as f64)/2.0, (CHUNK_WIDTH_PIXELS as f64)/2.0);
let distance_to_center=distance(particle.x, particle.y, (CHUNK_WIDTH_PIXELS as f64)/2.0, (CHUNK_WIDTH_PIXELS as f64)/2.0);
let pull_speed=PARTICLE_CORRECTION_SPEED*((distance_to_center-PARTICLE_CORRECTION_THRESHOLD)/(CHUNK_WIDTH_PIXELS as f64/2.0));
particle.x+=pull_speed*direction_to_center.cos();
particle.y+=pull_speed*direction_to_center.sin();
}
pub fn draw_particle(canvas: &mut Canvas<sdl2::video::Window>, particle: &mut Particle){
canvas.set_draw_color(Color::RGB(255,255,255));
let rect=Rect::new(
particle.x as i32,
particle.y as i32,
2,
2
);
canvas.fill_rect(rect).expect("Unable to draw a particle");
}
pub fn animate_grass(canvas: &mut Canvas<sdl2::video::Window>, grass: &mut GrassBiome){
for particle in grass.particles.iter_mut(){
step_particle(particle);
draw_particle(canvas, particle);
}
}
pub fn animate_specific(canvas: &mut Canvas<sdl2::video::Window>, effect: &mut ChunkEffect){
match effect{
&mut ChunkEffect::GrassBiome(ref mut grass)=>animate_grass(canvas, grass),
&mut ChunkEffect::NoEffects=>{}
}
}
pub fn animate(canvas: &mut Canvas<sdl2::video::Window>, _image_loader: &ImageLoader, frame_state: &mut FrameState){
for (_,chunk) in frame_state.chunks.iter_mut(){
let static_image=&chunk.static_image;
let specific_effects=&mut chunk.specific_effects;
canvas.with_texture_canvas(&mut chunk.image,|canvas|{
canvas.copy(static_image, None, None).
expect("Unable to draw static image as part of animate");
animate_specific(canvas,specific_effects);
}).expect("Unable to animate chunk");
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// HostListResponse : Response with Host information from Datadog.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostListResponse {
/// Array of hosts.
#[serde(rename = "host_list", skip_serializing_if = "Option::is_none")]
pub host_list: Option<Vec<crate::models::Host>>,
/// Number of host matching the query.
#[serde(rename = "total_matching", skip_serializing_if = "Option::is_none")]
pub total_matching: Option<i64>,
/// Number of host returned.
#[serde(rename = "total_returned", skip_serializing_if = "Option::is_none")]
pub total_returned: Option<i64>,
}
impl HostListResponse {
/// Response with Host information from Datadog.
pub fn new() -> HostListResponse {
HostListResponse {
host_list: None,
total_matching: None,
total_returned: None,
}
}
}
|
// Copyright 2016 The Fancy Regex Authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! A regex parser yielding an AST.
use bit_set::BitSet;
use regex::escape;
use std::collections::HashMap;
use std::str::FromStr;
use std::usize;
use crate::codepoint_len;
use crate::CompileError;
use crate::Error;
use crate::Expr;
use crate::LookAround::*;
use crate::ParseError;
use crate::Result;
use crate::MAX_RECURSION;
const FLAG_CASEI: u32 = 1;
const FLAG_MULTI: u32 = 1 << 1;
const FLAG_DOTNL: u32 = 1 << 2;
const FLAG_SWAP_GREED: u32 = 1 << 3;
const FLAG_IGNORE_SPACE: u32 = 1 << 4;
const FLAG_UNICODE: u32 = 1 << 5;
pub(crate) type NamedGroups = HashMap<String, usize>;
#[derive(Debug)]
pub struct ExprTree {
pub expr: Expr,
pub backrefs: BitSet,
pub named_groups: NamedGroups,
}
#[derive(Debug)]
pub(crate) struct Parser<'a> {
re: &'a str, // source
backrefs: BitSet,
flags: u32,
named_groups: NamedGroups,
numeric_backrefs: bool,
curr_group: usize, // need to keep track of which group number we're parsing
}
impl<'a> Parser<'a> {
/// Parse the regex and return an expression (AST) and a bit set with the indexes of groups
/// that are referenced by backrefs.
pub(crate) fn parse(re: &str) -> Result<ExprTree> {
let mut p = Parser::new(re);
let (ix, expr) = p.parse_re(0, 0)?;
if ix < re.len() {
return Err(Error::ParseError(
ix,
ParseError::GeneralParseError("end of string not reached".to_string()),
));
}
Ok(ExprTree {
expr,
backrefs: Default::default(),
named_groups: p.named_groups,
})
}
fn new(re: &str) -> Parser<'_> {
Parser {
re,
backrefs: Default::default(),
named_groups: Default::default(),
numeric_backrefs: false,
flags: FLAG_UNICODE,
curr_group: 0,
}
}
fn parse_re(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
let (ix, child) = self.parse_branch(ix, depth)?;
let mut ix = self.optional_whitespace(ix)?;
if self.re[ix..].starts_with('|') {
let mut children = vec![child];
while self.re[ix..].starts_with('|') {
ix += 1;
let (next, child) = self.parse_branch(ix, depth)?;
children.push(child);
ix = self.optional_whitespace(next)?;
}
return Ok((ix, Expr::Alt(children)));
}
// can't have numeric backrefs and named backrefs
if self.numeric_backrefs && !self.named_groups.is_empty() {
return Err(Error::CompileError(CompileError::NamedBackrefOnly));
}
Ok((ix, child))
}
fn parse_branch(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
let mut children = Vec::new();
let mut ix = ix;
while ix < self.re.len() {
let (next, child) = self.parse_piece(ix, depth)?;
if next == ix {
break;
}
if child != Expr::Empty {
children.push(child);
}
ix = next;
}
match children.len() {
0 => Ok((ix, Expr::Empty)),
1 => Ok((ix, children.pop().unwrap())),
_ => Ok((ix, Expr::Concat(children))),
}
}
fn parse_piece(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
let (ix, child) = self.parse_atom(ix, depth)?;
let mut ix = self.optional_whitespace(ix)?;
if ix < self.re.len() {
// fail when child is empty?
let (lo, hi) = match self.re.as_bytes()[ix] {
b'?' => (0, 1),
b'*' => (0, usize::MAX),
b'+' => (1, usize::MAX),
b'{' => {
match self.parse_repeat(ix) {
Ok((next, lo, hi)) => {
ix = next - 1;
(lo, hi)
}
Err(_) => {
// Invalid repeat syntax, which results in `{` being treated as a literal
return Ok((ix, child));
}
}
}
_ => return Ok((ix, child)),
};
if !self.is_repeatable(&child) {
return Err(Error::ParseError(ix, ParseError::TargetNotRepeatable));
}
ix += 1;
ix = self.optional_whitespace(ix)?;
let mut greedy = true;
if ix < self.re.len() && self.re.as_bytes()[ix] == b'?' {
greedy = false;
ix += 1;
}
greedy ^= self.flag(FLAG_SWAP_GREED);
let mut node = Expr::Repeat {
child: Box::new(child),
lo,
hi,
greedy,
};
if ix < self.re.len() && self.re.as_bytes()[ix] == b'+' {
ix += 1;
node = Expr::AtomicGroup(Box::new(node));
}
return Ok((ix, node));
}
Ok((ix, child))
}
fn is_repeatable(&self, child: &Expr) -> bool {
match child {
Expr::LookAround(_, _) => false,
Expr::Empty => false,
Expr::StartText => false,
Expr::EndText => false,
Expr::StartLine => false,
Expr::EndLine => false,
_ => true,
}
}
// ix, lo, hi
fn parse_repeat(&self, ix: usize) -> Result<(usize, usize, usize)> {
let ix = self.optional_whitespace(ix + 1)?; // skip opening '{'
let bytes = self.re.as_bytes();
if ix == self.re.len() {
return Err(Error::ParseError(ix, ParseError::InvalidRepeat));
}
let mut end = ix;
let lo = if bytes[ix] == b',' {
0
} else if let Some((next, lo)) = parse_decimal(self.re, ix) {
end = next;
lo
} else {
return Err(Error::ParseError(ix, ParseError::InvalidRepeat));
};
let ix = self.optional_whitespace(end)?; // past lo number
if ix == self.re.len() {
return Err(Error::ParseError(ix, ParseError::InvalidRepeat));
}
end = ix;
let hi = match bytes[ix] {
b'}' => lo,
b',' => {
end = self.optional_whitespace(ix + 1)?; // past ','
if let Some((next, hi)) = parse_decimal(self.re, end) {
end = next;
hi
} else {
usize::MAX
}
}
_ => return Err(Error::ParseError(ix, ParseError::InvalidRepeat)),
};
let ix = self.optional_whitespace(end)?; // past hi number
if ix == self.re.len() || bytes[ix] != b'}' {
return Err(Error::ParseError(ix, ParseError::InvalidRepeat));
}
Ok((ix + 1, lo, hi))
}
fn parse_atom(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
let ix = self.optional_whitespace(ix)?;
if ix == self.re.len() {
return Ok((ix, Expr::Empty));
}
match self.re.as_bytes()[ix] {
b'.' => Ok((
ix + 1,
Expr::Any {
newline: self.flag(FLAG_DOTNL),
},
)),
b'^' => Ok((
ix + 1,
if self.flag(FLAG_MULTI) {
Expr::StartLine
} else {
Expr::StartText
},
)),
b'$' => Ok((
ix + 1,
if self.flag(FLAG_MULTI) {
Expr::EndLine
} else {
Expr::EndText
},
)),
b'(' => self.parse_group(ix, depth),
b'\\' => {
let (next, expr) = self.parse_escape(ix)?;
if let Expr::Backref(group) = expr {
self.backrefs.insert(group);
}
Ok((next, expr))
}
b'+' | b'*' | b'?' | b'|' | b')' => Ok((ix, Expr::Empty)),
b'[' => self.parse_class(ix),
b => {
// TODO: maybe want to match multiple codepoints?
let next = ix + codepoint_len(b);
Ok((
next,
Expr::Literal {
val: String::from(&self.re[ix..next]),
casei: self.flag(FLAG_CASEI),
},
))
}
}
}
fn parse_named_backref(&self, ix: usize, open: &str, close: &str) -> Result<(usize, Expr)> {
if let Some((id, skip)) = parse_id(&self.re[ix..], open, close) {
let group = if let Some(group) = self.named_groups.get(id) {
Some(*group)
} else if let Ok(group) = id.parse() {
Some(group)
} else {
None
};
if let Some(group) = group {
return Ok((ix + skip, Expr::Backref(group)));
}
// here the name is parsed but it is invalid
Err(Error::ParseError(
ix,
ParseError::InvalidGroupNameBackref(id.to_string()),
))
} else {
// in this case the name can't be parsed
Err(Error::ParseError(ix, ParseError::InvalidGroupName))
}
}
fn parse_numbered_backref(&mut self, ix: usize) -> Result<(usize, Expr)> {
if let Some((end, group)) = parse_decimal(self.re, ix) {
// protect BitSet against unreasonably large value
if group < self.re.len() / 2 {
self.numeric_backrefs = true;
return Ok((end, Expr::Backref(group)));
}
}
return Err(Error::ParseError(ix, ParseError::InvalidBackref));
}
// ix points to \ character
fn parse_escape(&mut self, ix: usize) -> Result<(usize, Expr)> {
if ix + 1 == self.re.len() {
return Err(Error::ParseError(ix, ParseError::TrailingBackslash));
}
let bytes = self.re.as_bytes();
let b = bytes[ix + 1];
let mut end = ix + 1 + codepoint_len(b);
let mut size = 1;
if is_digit(b) {
return self.parse_numbered_backref(ix + 1);
} else if b == b'k' {
// Named backref: \k<name>
return self.parse_named_backref(ix + 2, "<", ">");
} else if b == b'A' || b == b'z' || b == b'b' || b == b'B' {
size = 0;
} else if (b | 32) == b'd'
|| (b | 32) == b's'
|| (b | 32) == b'w'
|| b == b'a'
|| b == b'f'
|| b == b'n'
|| b == b'r'
|| b == b't'
|| b == b'v'
{
// size = 1
} else if b == b'e' {
let inner = String::from(r"\x1B");
return Ok((
end,
Expr::Delegate {
inner,
size,
casei: false,
},
));
} else if (b | 32) == b'h' {
let s = if b == b'h' {
"[0-9A-Fa-f]"
} else {
"[^0-9A-Fa-f]"
};
let inner = String::from(s);
return Ok((
end,
Expr::Delegate {
inner,
size,
casei: false,
},
));
} else if b == b'x' {
return self.parse_hex(end, 2);
} else if b == b'u' {
return self.parse_hex(end, 4);
} else if b == b'U' {
return self.parse_hex(end, 8);
} else if (b | 32) == b'p' {
// allow whitespace?
if end == self.re.len() {
return Err(Error::ParseError(
ix,
ParseError::InvalidEscape("\\p must be followed by a unicode name".to_string()),
));
}
let b = bytes[end];
end += codepoint_len(b);
if b == b'{' {
loop {
if end == self.re.len() {
return Err(Error::ParseError(ix, ParseError::UnclosedUnicodeName));
}
let b = bytes[end];
if b == b'}' {
end += 1;
break;
}
end += codepoint_len(b);
}
}
} else if b == b'K' {
return Ok((end, Expr::KeepOut));
} else if b == b'G' {
return Ok((end, Expr::ContinueFromPreviousMatchEnd));
} else if b'a' <= (b | 32) && (b | 32) <= b'z' {
return Err(Error::ParseError(
ix,
ParseError::InvalidEscape(format!("\\{}", &self.re[ix + 1..end])),
));
} else if 0x20 <= b && b <= 0x7f {
// printable ASCII (including space, see issue #29)
return Ok((end, make_literal(&self.re[ix + 1..end])));
}
// what to do with characters outside printable ASCII?
let inner = String::from(&self.re[ix..end]);
Ok((
end,
Expr::Delegate {
inner,
size,
casei: self.flag(FLAG_CASEI),
},
))
}
// ix points after '\x', eg to 'A0' or '{12345}', or after `\u` or `\U`
fn parse_hex(&self, ix: usize, digits: usize) -> Result<(usize, Expr)> {
if ix >= self.re.len() {
// Incomplete escape sequence
return Err(Error::ParseError(ix, ParseError::InvalidHex));
}
let bytes = self.re.as_bytes();
let b = bytes[ix];
let (end, s) = if ix + digits <= self.re.len()
&& bytes[ix..ix + digits].iter().all(|&b| is_hex_digit(b))
{
let end = ix + digits;
(end, &self.re[ix..end])
} else if b == b'{' {
let starthex = ix + 1;
let mut endhex = starthex;
loop {
if endhex == self.re.len() {
return Err(Error::ParseError(ix, ParseError::InvalidHex));
}
let b = bytes[endhex];
if endhex > starthex && b == b'}' {
break;
}
if is_hex_digit(b) && endhex < starthex + 8 {
endhex += 1;
} else {
return Err(Error::ParseError(ix, ParseError::InvalidHex));
}
}
(endhex + 1, &self.re[starthex..endhex])
} else {
return Err(Error::ParseError(ix, ParseError::InvalidHex));
};
let codepoint = u32::from_str_radix(s, 16).unwrap();
if let Some(c) = ::std::char::from_u32(codepoint) {
let mut inner = String::with_capacity(4);
inner.push(c);
Ok((
end,
Expr::Literal {
val: inner,
casei: self.flag(FLAG_CASEI),
},
))
} else {
Err(Error::ParseError(ix, ParseError::InvalidCodepointValue))
}
}
fn parse_class(&mut self, ix: usize) -> Result<(usize, Expr)> {
let bytes = self.re.as_bytes();
let mut ix = ix + 1; // skip opening '['
let mut class = String::new();
let mut nest = 1;
class.push('[');
// Negated character class
if ix < self.re.len() && bytes[ix] == b'^' {
class.push('^');
ix += 1;
}
// `]` does not have to be escaped after opening `[` or `[^`
if ix < self.re.len() && bytes[ix] == b']' {
class.push(']');
ix += 1;
}
loop {
if ix == self.re.len() {
return Err(Error::ParseError(ix, ParseError::InvalidClass));
}
let end = match bytes[ix] {
b'\\' => {
if ix + 1 == self.re.len() {
return Err(Error::ParseError(ix, ParseError::InvalidClass));
}
// We support more escapes than regex, so parse it ourselves before delegating.
let (end, expr) = self.parse_escape(ix)?;
match expr {
Expr::Literal { val, .. } => {
class.push_str(&escape(&val));
}
Expr::Delegate { inner, .. } => {
class.push_str(&inner);
}
_ => {
return Err(Error::ParseError(ix, ParseError::InvalidClass));
}
}
end
}
b'[' => {
nest += 1;
class.push('[');
ix + 1
}
b']' => {
nest -= 1;
if nest == 0 {
break;
}
class.push(']');
ix + 1
}
b => {
let end = ix + codepoint_len(b);
class.push_str(&self.re[ix..end]);
end
}
};
ix = end;
}
class.push(']');
let ix = ix + 1; // skip closing ']'
Ok((
ix,
Expr::Delegate {
inner: class,
size: 1,
casei: self.flag(FLAG_CASEI),
},
))
}
fn parse_group(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
let depth = depth + 1;
if depth >= MAX_RECURSION {
return Err(Error::ParseError(ix, ParseError::RecursionExceeded));
}
let ix = self.optional_whitespace(ix + 1)?;
let (la, skip) = if self.re[ix..].starts_with("?=") {
(Some(LookAhead), 2)
} else if self.re[ix..].starts_with("?!") {
(Some(LookAheadNeg), 2)
} else if self.re[ix..].starts_with("?<=") {
(Some(LookBehind), 3)
} else if self.re[ix..].starts_with("?<!") {
(Some(LookBehindNeg), 3)
} else if self.re[ix..].starts_with("?<") {
// Named capture group using Oniguruma syntax: (?<name>...)
self.curr_group += 1;
if let Some((id, skip)) = parse_id(&self.re[ix + 1..], "<", ">") {
self.named_groups.insert(id.to_string(), self.curr_group);
(None, skip + 1)
} else {
return Err(Error::ParseError(ix, ParseError::InvalidGroupName));
}
} else if self.re[ix..].starts_with("?P<") {
// Named capture group using Python syntax: (?P<name>...)
self.curr_group += 1; // this is a capture group
if let Some((id, skip)) = parse_id(&self.re[ix + 2..], "<", ">") {
self.named_groups.insert(id.to_string(), self.curr_group);
(None, skip + 2)
} else {
return Err(Error::ParseError(ix, ParseError::InvalidGroupName));
}
} else if self.re[ix..].starts_with("?P=") {
// Backref using Python syntax: (?P=name)
return self.parse_named_backref(ix + 3, "", ")");
} else if self.re[ix..].starts_with("?>") {
(None, 2)
} else if self.re[ix..].starts_with("?(") {
return self.parse_conditional(ix + 2, depth);
} else if self.re[ix..].starts_with('?') {
return self.parse_flags(ix, depth);
} else {
self.curr_group += 1; // this is a capture group
(None, 0)
};
let ix = ix + skip;
let (ix, child) = self.parse_re(ix, depth)?;
let ix = self.check_for_close_paren(ix)?;
let result = match (la, skip) {
(Some(la), _) => Expr::LookAround(Box::new(child), la),
(None, 2) => Expr::AtomicGroup(Box::new(child)),
_ => Expr::Group(Box::new(child)),
};
Ok((ix, result))
}
fn check_for_close_paren(&self, ix: usize) -> Result<usize> {
let ix = self.optional_whitespace(ix)?;
if ix == self.re.len() {
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen));
} else if self.re.as_bytes()[ix] != b')' {
return Err(Error::ParseError(
ix,
ParseError::GeneralParseError("expected close paren".to_string()),
));
}
Ok(ix + 1)
}
// ix points to `?` in `(?`
fn parse_flags(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
let start = ix + 1;
fn unknown_flag(re: &str, start: usize, end: usize) -> Error {
let after_end = end + codepoint_len(re.as_bytes()[end]);
let s = format!("(?{}", &re[start..after_end]);
Error::ParseError(start, ParseError::UnknownFlag(s))
}
let mut ix = start;
let mut neg = false;
let oldflags = self.flags;
loop {
ix = self.optional_whitespace(ix)?;
if ix == self.re.len() {
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen));
}
let b = self.re.as_bytes()[ix];
match b {
b'i' => self.update_flag(FLAG_CASEI, neg),
b'm' => self.update_flag(FLAG_MULTI, neg),
b's' => self.update_flag(FLAG_DOTNL, neg),
b'U' => self.update_flag(FLAG_SWAP_GREED, neg),
b'x' => self.update_flag(FLAG_IGNORE_SPACE, neg),
b'u' => {
if neg {
return Err(Error::ParseError(ix, ParseError::NonUnicodeUnsupported));
}
}
b'-' => {
if neg {
return Err(unknown_flag(self.re, start, ix));
}
neg = true;
}
b')' => {
if ix == start || neg && ix == start + 1 {
return Err(unknown_flag(self.re, start, ix));
}
return Ok((ix + 1, Expr::Empty));
}
b':' => {
if neg && ix == start + 1 {
return Err(unknown_flag(self.re, start, ix));
}
ix += 1;
let (ix, child) = self.parse_re(ix, depth)?;
if ix == self.re.len() {
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen));
} else if self.re.as_bytes()[ix] != b')' {
return Err(Error::ParseError(
ix,
ParseError::GeneralParseError("expected close paren".to_string()),
));
};
self.flags = oldflags;
return Ok((ix + 1, child));
}
_ => return Err(unknown_flag(self.re, start, ix)),
}
ix += 1;
}
}
// ix points to after the last ( in (?(
fn parse_conditional(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> {
if ix >= self.re.len() {
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen));
}
let bytes = self.re.as_bytes();
// get the character after the open paren
let b = bytes[ix];
let (mut next, condition) = if is_digit(b) {
self.parse_numbered_backref(ix)?
} else if b == b'\'' {
self.parse_named_backref(ix, "'", "'")?
} else if b == b'<' {
self.parse_named_backref(ix, "<", ">")?
} else {
self.parse_re(ix, depth)?
};
next = self.check_for_close_paren(next)?;
let (end, child) = self.parse_re(next, depth)?;
if end == next {
// Backreference validity checker
if let Expr::Backref(group) = condition {
return Ok((end + 1, Expr::BackrefExistsCondition(group)));
} else {
return Err(Error::ParseError(
end,
ParseError::GeneralParseError(
"expected conditional to be a backreference or at least an expression for when the condition is true".to_string()
)
));
}
}
let if_true: Expr;
let mut if_false: Expr = Expr::Empty;
if let Expr::Alt(mut alternatives) = child {
// the truth branch will be the first alternative
if_true = alternatives.remove(0);
// if there is only one alternative left, take it out the Expr::Alt
if alternatives.len() == 1 {
if_false = alternatives.pop().expect("expected 2 alternatives");
} else {
// otherwise the remaining branches become the false branch
if_false = Expr::Alt(alternatives);
}
} else {
// there is only one branch - the truth branch. i.e. "if" without "else"
if_true = child;
}
let inner_condition = if let Expr::Backref(group) = condition {
Expr::BackrefExistsCondition(group)
} else {
condition
};
Ok((
end + 1,
if if_true == Expr::Empty && if_false == Expr::Empty {
inner_condition
} else {
Expr::Conditional {
condition: Box::new(inner_condition),
true_branch: Box::new(if_true),
false_branch: Box::new(if_false),
}
},
))
}
fn flag(&self, flag: u32) -> bool {
(self.flags & flag) != 0
}
fn update_flag(&mut self, flag: u32, neg: bool) {
if neg {
self.flags &= !flag;
} else {
self.flags |= flag;
}
}
fn optional_whitespace(&self, mut ix: usize) -> Result<usize> {
let bytes = self.re.as_bytes();
loop {
if ix == self.re.len() {
return Ok(ix);
}
match bytes[ix] {
b'#' if self.flag(FLAG_IGNORE_SPACE) => {
match bytes[ix..].iter().position(|&c| c == b'\n') {
Some(x) => ix += x + 1,
None => return Ok(self.re.len()),
}
}
b' ' | b'\r' | b'\n' | b'\t' if self.flag(FLAG_IGNORE_SPACE) => ix += 1,
b'(' if bytes[ix..].starts_with(b"(?#") => {
ix += 3;
loop {
if ix >= self.re.len() {
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen));
}
match bytes[ix] {
b')' => {
ix += 1;
break;
}
b'\\' => ix += 2,
_ => ix += 1,
}
}
}
_ => return Ok(ix),
}
}
}
}
// return (ix, value)
pub(crate) fn parse_decimal(s: &str, ix: usize) -> Option<(usize, usize)> {
let mut end = ix;
while end < s.len() && is_digit(s.as_bytes()[end]) {
end += 1;
}
usize::from_str(&s[ix..end]).ok().map(|val| (end, val))
}
/// Attempts to parse an identifier between the specified opening and closing
/// delimiters. On success, returns `Some((id, skip))`, where `skip` is how much
/// of the string was used.
pub(crate) fn parse_id<'a>(s: &'a str, open: &'_ str, close: &'_ str) -> Option<(&'a str, usize)> {
debug_assert!(!close.starts_with(is_id_char));
if !s.starts_with(open) {
return None;
}
let id_start = open.len();
let id_len = match s[id_start..].find(|c: char| !is_id_char(c)) {
Some(id_len) if s[id_start + id_len..].starts_with(close) => Some(id_len),
None if close.is_empty() => Some(s.len()),
_ => None,
};
match id_len {
Some(0) => None,
Some(id_len) => {
let id_end = id_start + id_len;
Some((&s[id_start..id_end], id_end + close.len()))
}
_ => None,
}
}
fn is_id_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
fn is_digit(b: u8) -> bool {
b'0' <= b && b <= b'9'
}
fn is_hex_digit(b: u8) -> bool {
is_digit(b) || (b'a' <= (b | 32) && (b | 32) <= b'f')
}
pub(crate) fn make_literal(s: &str) -> Expr {
Expr::Literal {
val: String::from(s),
casei: false,
}
}
#[cfg(test)]
mod tests {
use crate::parse::{make_literal, parse_id};
use crate::Expr;
use crate::LookAround::*;
use std::usize;
fn p(s: &str) -> Expr {
Expr::parse_tree(s).unwrap().expr
}
#[cfg_attr(feature = "track_caller", track_caller)]
fn fail(s: &str) {
assert!(Expr::parse_tree(s).is_err());
}
#[cfg_attr(feature = "track_caller", track_caller)]
fn assert_error(re: &str, expected_error: &str) {
let result = Expr::parse_tree(re);
assert!(result.is_err());
assert_eq!(&format!("{}", result.err().unwrap()), expected_error);
}
#[test]
fn empty() {
assert_eq!(p(""), Expr::Empty);
}
#[test]
fn any() {
assert_eq!(p("."), Expr::Any { newline: false });
assert_eq!(p("(?s:.)"), Expr::Any { newline: true });
}
#[test]
fn start_text() {
assert_eq!(p("^"), Expr::StartText);
}
#[test]
fn end_text() {
assert_eq!(p("$"), Expr::EndText);
}
#[test]
fn literal() {
assert_eq!(p("a"), make_literal("a"));
}
#[test]
fn literal_special() {
assert_eq!(p("}"), make_literal("}"));
assert_eq!(p("]"), make_literal("]"));
}
#[test]
fn parse_id_test() {
assert_eq!(parse_id("foo.", "", ""), Some(("foo", 3)));
assert_eq!(parse_id("{foo}", "{", "}"), Some(("foo", 5)));
assert_eq!(parse_id("{foo.", "{", "}"), None);
assert_eq!(parse_id("{foo", "{", "}"), None);
assert_eq!(parse_id("{}", "{", "}"), None);
assert_eq!(parse_id("", "", ""), None);
}
#[test]
fn literal_unescaped_opening_curly() {
// `{` in position where quantifier is not allowed results in literal `{`
assert_eq!(p("{"), make_literal("{"));
assert_eq!(p("({)"), Expr::Group(Box::new(make_literal("{"),)));
assert_eq!(
p("a|{"),
Expr::Alt(vec![make_literal("a"), make_literal("{"),])
);
assert_eq!(
p("{{2}"),
Expr::Repeat {
child: Box::new(make_literal("{")),
lo: 2,
hi: 2,
greedy: true
}
);
}
#[test]
fn literal_escape() {
assert_eq!(p("\\'"), make_literal("'"));
assert_eq!(p("\\\""), make_literal("\""));
assert_eq!(p("\\ "), make_literal(" "));
assert_eq!(p("\\xA0"), make_literal("\u{A0}"));
assert_eq!(p("\\x{1F4A9}"), make_literal("\u{1F4A9}"));
assert_eq!(p("\\x{000000B7}"), make_literal("\u{B7}"));
assert_eq!(p("\\u21D2"), make_literal("\u{21D2}"));
assert_eq!(p("\\u{21D2}"), make_literal("\u{21D2}"));
assert_eq!(p("\\u21D2x"), p("\u{21D2}x"));
assert_eq!(p("\\U0001F60A"), make_literal("\u{1F60A}"));
assert_eq!(p("\\U{0001F60A}"), make_literal("\u{1F60A}"));
}
#[test]
fn hex_escape() {
assert_eq!(
p("\\h"),
Expr::Delegate {
inner: String::from("[0-9A-Fa-f]"),
size: 1,
casei: false
}
);
assert_eq!(
p("\\H"),
Expr::Delegate {
inner: String::from("[^0-9A-Fa-f]"),
size: 1,
casei: false
}
);
}
#[test]
fn invalid_escape() {
assert_error(
"\\",
"Parsing error at position 0: Backslash without following character",
);
assert_error("\\q", "Parsing error at position 0: Invalid escape: \\q");
assert_error("\\xAG", "Parsing error at position 2: Invalid hex escape");
assert_error("\\xA", "Parsing error at position 2: Invalid hex escape");
assert_error("\\x{}", "Parsing error at position 2: Invalid hex escape");
assert_error("\\x{AG}", "Parsing error at position 2: Invalid hex escape");
assert_error("\\x{42", "Parsing error at position 2: Invalid hex escape");
assert_error(
"\\x{D800}",
"Parsing error at position 2: Invalid codepoint for hex or unicode escape",
);
assert_error(
"\\x{110000}",
"Parsing error at position 2: Invalid codepoint for hex or unicode escape",
);
assert_error("\\u123", "Parsing error at position 2: Invalid hex escape");
assert_error("\\u123x", "Parsing error at position 2: Invalid hex escape");
assert_error("\\u{}", "Parsing error at position 2: Invalid hex escape");
assert_error(
"\\U1234567",
"Parsing error at position 2: Invalid hex escape",
);
assert_error("\\U{}", "Parsing error at position 2: Invalid hex escape");
}
#[test]
fn concat() {
assert_eq!(
p("ab"),
Expr::Concat(vec![make_literal("a"), make_literal("b"),])
);
}
#[test]
fn alt() {
assert_eq!(
p("a|b"),
Expr::Alt(vec![make_literal("a"), make_literal("b"),])
);
}
#[test]
fn group() {
assert_eq!(p("(a)"), Expr::Group(Box::new(make_literal("a"),)));
}
#[test]
fn group_repeat() {
assert_eq!(
p("(a){2}"),
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("a")))),
lo: 2,
hi: 2,
greedy: true
}
);
}
#[test]
fn repeat() {
assert_eq!(
p("a{2,42}"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 2,
hi: 42,
greedy: true
}
);
assert_eq!(
p("a{2,}"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 2,
hi: usize::MAX,
greedy: true
}
);
assert_eq!(
p("a{2}"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 2,
hi: 2,
greedy: true
}
);
assert_eq!(
p("a{,2}"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 0,
hi: 2,
greedy: true
}
);
assert_eq!(
p("a{2,42}?"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 2,
hi: 42,
greedy: false
}
);
assert_eq!(
p("a{2,}?"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 2,
hi: usize::MAX,
greedy: false
}
);
assert_eq!(
p("a{2}?"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 2,
hi: 2,
greedy: false
}
);
assert_eq!(
p("a{,2}?"),
Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 0,
hi: 2,
greedy: false
}
);
}
#[test]
fn invalid_repeat() {
// Invalid repeat syntax results in literal
assert_eq!(
p("a{"),
Expr::Concat(vec![make_literal("a"), make_literal("{"),])
);
assert_eq!(
p("a{6"),
Expr::Concat(vec![
make_literal("a"),
make_literal("{"),
make_literal("6"),
])
);
assert_eq!(
p("a{6,"),
Expr::Concat(vec![
make_literal("a"),
make_literal("{"),
make_literal("6"),
make_literal(","),
])
);
}
#[test]
fn delegate_zero() {
assert_eq!(
p("\\b"),
Expr::Delegate {
inner: String::from("\\b"),
size: 0,
casei: false
}
);
assert_eq!(
p("\\B"),
Expr::Delegate {
inner: String::from("\\B"),
size: 0,
casei: false
}
);
}
#[test]
fn delegate_named_group() {
assert_eq!(
p("\\p{Greek}"),
Expr::Delegate {
inner: String::from("\\p{Greek}"),
size: 1,
casei: false
}
);
assert_eq!(
p("\\pL"),
Expr::Delegate {
inner: String::from("\\pL"),
size: 1,
casei: false
}
);
assert_eq!(
p("\\P{Greek}"),
Expr::Delegate {
inner: String::from("\\P{Greek}"),
size: 1,
casei: false
}
);
assert_eq!(
p("\\PL"),
Expr::Delegate {
inner: String::from("\\PL"),
size: 1,
casei: false
}
);
assert_eq!(
p("(?i)\\p{Ll}"),
Expr::Delegate {
inner: String::from("\\p{Ll}"),
size: 1,
casei: true
}
);
}
#[test]
fn backref() {
assert_eq!(
p("(.)\\1"),
Expr::Concat(vec![
Expr::Group(Box::new(Expr::Any { newline: false })),
Expr::Backref(1),
])
);
}
#[test]
fn named_backref() {
assert_eq!(
p("(?<i>.)\\k<i>"),
Expr::Concat(vec![
Expr::Group(Box::new(Expr::Any { newline: false })),
Expr::Backref(1),
])
);
}
#[test]
fn lookaround() {
assert_eq!(
p("(?=a)"),
Expr::LookAround(Box::new(make_literal("a")), LookAhead)
);
assert_eq!(
p("(?!a)"),
Expr::LookAround(Box::new(make_literal("a")), LookAheadNeg)
);
assert_eq!(
p("(?<=a)"),
Expr::LookAround(Box::new(make_literal("a")), LookBehind)
);
assert_eq!(
p("(?<!a)"),
Expr::LookAround(Box::new(make_literal("a")), LookBehindNeg)
);
}
#[test]
fn shy_group() {
assert_eq!(
p("(?:ab)c"),
Expr::Concat(vec![
Expr::Concat(vec![make_literal("a"), make_literal("b"),]),
make_literal("c"),
])
);
}
#[test]
fn flag_state() {
assert_eq!(p("(?s)."), Expr::Any { newline: true });
assert_eq!(p("(?s:(?-s:.))"), Expr::Any { newline: false });
assert_eq!(
p("(?s:.)."),
Expr::Concat(vec![
Expr::Any { newline: true },
Expr::Any { newline: false },
])
);
assert_eq!(
p("(?:(?s).)."),
Expr::Concat(vec![
Expr::Any { newline: true },
Expr::Any { newline: false },
])
);
}
#[test]
fn flag_multiline() {
assert_eq!(p("^"), Expr::StartText);
assert_eq!(p("(?m:^)"), Expr::StartLine);
assert_eq!(p("$"), Expr::EndText);
assert_eq!(p("(?m:$)"), Expr::EndLine);
}
#[test]
fn flag_swap_greed() {
assert_eq!(p("a*"), p("(?U:a*?)"));
assert_eq!(p("a*?"), p("(?U:a*)"));
}
#[test]
fn invalid_flags() {
assert!(Expr::parse_tree("(?").is_err());
assert!(Expr::parse_tree("(?)").is_err());
assert!(Expr::parse_tree("(?-)").is_err());
assert!(Expr::parse_tree("(?-:a)").is_err());
assert!(Expr::parse_tree("(?q:a)").is_err());
}
#[test]
fn lifetime() {
assert_eq!(
p("\\'[a-zA-Z_][a-zA-Z0-9_]*(?!\\')\\b"),
Expr::Concat(vec![
make_literal("'"),
Expr::Delegate {
inner: String::from("[a-zA-Z_]"),
size: 1,
casei: false
},
Expr::Repeat {
child: Box::new(Expr::Delegate {
inner: String::from("[a-zA-Z0-9_]"),
size: 1,
casei: false
}),
lo: 0,
hi: usize::MAX,
greedy: true
},
Expr::LookAround(Box::new(make_literal("'")), LookAheadNeg),
Expr::Delegate {
inner: String::from("\\b"),
size: 0,
casei: false
}
])
);
}
#[test]
fn ignore_whitespace() {
assert_eq!(p("(?x: )"), p(""));
assert_eq!(p("(?x) | "), p("|"));
assert_eq!(p("(?x: a )"), p("a"));
assert_eq!(p("(?x: a # ) bobby tables\n b )"), p("ab"));
assert_eq!(p("(?x: a | b )"), p("a|b"));
assert_eq!(p("(?x: ( a b ) )"), p("(ab)"));
assert_eq!(p("(?x: a + )"), p("a+"));
assert_eq!(p("(?x: a {2} )"), p("a{2}"));
assert_eq!(p("(?x: a { 2 } )"), p("a{2}"));
assert_eq!(p("(?x: a { 2 , } )"), p("a{2,}"));
assert_eq!(p("(?x: a { , 2 } )"), p("a{,2}"));
assert_eq!(p("(?x: a { 2 , 3 } )"), p("a{2,3}"));
assert_eq!(p("(?x: a { 2 , 3 } ? )"), p("a{2,3}?"));
assert_eq!(p("(?x: ( ? i : . ) )"), p("(?i:.)"));
assert_eq!(p("(?x: ( ?= a ) )"), p("(?=a)"));
assert_eq!(p("(?x: [ ] )"), p("[ ]"));
assert_eq!(p("(?x: [ ^] )"), p("[ ^]"));
assert_eq!(p("(?x: [a - z] )"), p("[a - z]"));
assert_eq!(p("(?x: [ \\] \\\\] )"), p("[ \\] \\\\]"));
assert_eq!(p("(?x: a\\ b )"), p("a b"));
assert_eq!(p("(?x: a (?-x:#) b )"), p("a#b"));
}
#[test]
fn comments() {
assert_eq!(p(r"ab(?# comment)"), p("ab"));
assert_eq!(p(r"ab(?#)"), p("ab"));
assert_eq!(p(r"(?# comment 1)(?# comment 2)ab"), p("ab"));
assert_eq!(p(r"ab(?# comment \))c"), p("abc"));
assert_eq!(p(r"ab(?# comment \\)c"), p("abc"));
assert_eq!(p(r"ab(?# comment ()c"), p("abc"));
assert_eq!(p(r"ab(?# comment)*"), p("ab*"));
fail(r"ab(?# comment");
fail(r"ab(?# comment\");
}
#[test]
fn atomic_group() {
assert_eq!(p("(?>a)"), Expr::AtomicGroup(Box::new(make_literal("a"))));
}
#[test]
fn possessive() {
assert_eq!(
p("a++"),
Expr::AtomicGroup(Box::new(Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 1,
hi: usize::MAX,
greedy: true
}))
);
assert_eq!(
p("a*+"),
Expr::AtomicGroup(Box::new(Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 0,
hi: usize::MAX,
greedy: true
}))
);
assert_eq!(
p("a?+"),
Expr::AtomicGroup(Box::new(Expr::Repeat {
child: Box::new(make_literal("a")),
lo: 0,
hi: 1,
greedy: true
}))
);
}
#[test]
fn invalid_backref() {
// only syntactic tests; see similar test in analyze module
fail(".\\12345678"); // unreasonably large number
fail(".\\c"); // not decimal
}
#[test]
fn invalid_group_name_backref() {
assert_error(
"\\k<id>(?<id>.)",
"Parsing error at position 2: Invalid group name in back reference: id",
);
}
#[test]
fn named_backref_only() {
assert_error("(?<id>.)\\1", "Error compiling regex: Numbered backref/call not allowed because named group was used, use a named backref instead");
assert_error("(a)\\1(?<name>b)", "Error compiling regex: Numbered backref/call not allowed because named group was used, use a named backref instead");
}
#[test]
fn invalid_group_name() {
assert_error(
"(?<id)",
"Parsing error at position 1: Could not parse group name",
);
assert_error(
"(?<>)",
"Parsing error at position 1: Could not parse group name",
);
assert_error(
"(?<#>)",
"Parsing error at position 1: Could not parse group name",
);
assert_error(
"\\kxxx<id>",
"Parsing error at position 2: Could not parse group name",
);
}
#[test]
fn unknown_flag() {
assert_error(
"(?-:a)",
"Parsing error at position 2: Unknown group flag: (?-:",
);
assert_error(
"(?)",
"Parsing error at position 2: Unknown group flag: (?)",
);
assert_error(
"(?--)",
"Parsing error at position 2: Unknown group flag: (?--",
);
// Check that we don't split on char boundary
assert_error(
"(?\u{1F60A})",
"Parsing error at position 2: Unknown group flag: (?\u{1F60A}",
);
}
#[test]
fn no_quantifiers_on_lookarounds() {
assert_error(
"(?=hello)+",
"Parsing error at position 9: Target of repeat operator is invalid",
);
assert_error(
"(?<!hello)*",
"Parsing error at position 10: Target of repeat operator is invalid",
);
assert_error(
"(?<=hello){2,3}",
"Parsing error at position 14: Target of repeat operator is invalid",
);
assert_error(
"(?!hello)?",
"Parsing error at position 9: Target of repeat operator is invalid",
);
assert_error(
"^?",
"Parsing error at position 1: Target of repeat operator is invalid",
);
assert_error(
"${2}",
"Parsing error at position 3: Target of repeat operator is invalid",
);
assert_error(
"(?m)^?",
"Parsing error at position 5: Target of repeat operator is invalid",
);
assert_error(
"(?m)${2}",
"Parsing error at position 7: Target of repeat operator is invalid",
);
assert_error(
"(a|b|?)",
"Parsing error at position 5: Target of repeat operator is invalid",
);
}
#[test]
fn keepout() {
assert_eq!(
p("a\\Kb"),
Expr::Concat(vec![make_literal("a"), Expr::KeepOut, make_literal("b"),])
);
}
#[test]
fn backref_exists_condition() {
assert_eq!(
p("(h)?(?(1))"),
Expr::Concat(vec![
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("h")))),
lo: 0,
hi: 1,
greedy: true
},
Expr::BackrefExistsCondition(1)
])
);
assert_eq!(
p("(?<h>h)?(?('h'))"),
Expr::Concat(vec![
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("h")))),
lo: 0,
hi: 1,
greedy: true
},
Expr::BackrefExistsCondition(1)
])
);
}
#[test]
fn conditional_non_backref_validity_check_without_branches() {
assert_error(
"(?(foo))",
"Parsing error at position 7: General parsing error: expected conditional to be a backreference or at least an expression for when the condition is true",
);
}
#[test]
fn conditional_invalid_target_of_repeat_operator() {
assert_error(
r"(?(?=\d)\w|!)",
"Parsing error at position 3: Target of repeat operator is invalid",
);
}
#[test]
fn backref_condition_with_one_two_or_three_branches() {
assert_eq!(
p("(h)?(?(1)i|x)"),
Expr::Concat(vec![
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("h")))),
lo: 0,
hi: 1,
greedy: true
},
Expr::Conditional {
condition: Box::new(Expr::BackrefExistsCondition(1)),
true_branch: Box::new(make_literal("i")),
false_branch: Box::new(make_literal("x")),
},
])
);
assert_eq!(
p("(h)?(?(1)i)"),
Expr::Concat(vec![
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("h")))),
lo: 0,
hi: 1,
greedy: true
},
Expr::Conditional {
condition: Box::new(Expr::BackrefExistsCondition(1)),
true_branch: Box::new(make_literal("i")),
false_branch: Box::new(Expr::Empty),
},
])
);
assert_eq!(
p("(h)?(?(1)ii|xy|z)"),
Expr::Concat(vec![
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("h")))),
lo: 0,
hi: 1,
greedy: true
},
Expr::Conditional {
condition: Box::new(Expr::BackrefExistsCondition(1)),
true_branch: Box::new(Expr::Concat(
vec![make_literal("i"), make_literal("i"),]
)),
false_branch: Box::new(Expr::Alt(vec![
Expr::Concat(vec![make_literal("x"), make_literal("y"),]),
make_literal("z"),
])),
},
])
);
assert_eq!(
p("(?<cap>h)?(?(<cap>)ii|xy|z)"),
Expr::Concat(vec![
Expr::Repeat {
child: Box::new(Expr::Group(Box::new(make_literal("h")))),
lo: 0,
hi: 1,
greedy: true
},
Expr::Conditional {
condition: Box::new(Expr::BackrefExistsCondition(1)),
true_branch: Box::new(Expr::Concat(
vec![make_literal("i"), make_literal("i"),]
)),
false_branch: Box::new(Expr::Alt(vec![
Expr::Concat(vec![make_literal("x"), make_literal("y"),]),
make_literal("z"),
])),
},
])
);
}
#[test]
fn conditional() {
assert_eq!(
p("((?(a)b|c))(\\1)"),
Expr::Concat(vec![
Expr::Group(Box::new(Expr::Conditional {
condition: Box::new(make_literal("a")),
true_branch: Box::new(make_literal("b")),
false_branch: Box::new(make_literal("c"))
})),
Expr::Group(Box::new(Expr::Backref(1)))
])
);
assert_eq!(
p(r"^(?(\d)abc|\d!)$"),
Expr::Concat(vec![
Expr::StartText,
Expr::Conditional {
condition: Box::new(Expr::Delegate {
inner: "\\d".to_string(),
size: 1,
casei: false,
}),
true_branch: Box::new(Expr::Concat(vec![
make_literal("a"),
make_literal("b"),
make_literal("c"),
])),
false_branch: Box::new(Expr::Concat(vec![
Expr::Delegate {
inner: "\\d".to_string(),
size: 1,
casei: false,
},
make_literal("!"),
])),
},
Expr::EndText,
])
);
assert_eq!(
p(r"(?((?=\d))\w|!)"),
Expr::Conditional {
condition: Box::new(Expr::LookAround(
Box::new(Expr::Delegate {
inner: "\\d".to_string(),
size: 1,
casei: false
}),
LookAhead
)),
true_branch: Box::new(Expr::Delegate {
inner: "\\w".to_string(),
size: 1,
casei: false,
}),
false_branch: Box::new(make_literal("!")),
},
);
assert_eq!(
p(r"(?((ab))c|d)"),
Expr::Conditional {
condition: Box::new(Expr::Group(Box::new(Expr::Concat(vec![
make_literal("a"),
make_literal("b"),
]),))),
true_branch: Box::new(make_literal("c")),
false_branch: Box::new(make_literal("d")),
},
);
}
// found by cargo fuzz, then minimized
#[test]
fn fuzz_1() {
p(r"\ä");
}
#[test]
fn fuzz_2() {
p(r"\pä");
}
}
|
pub struct IsClosed {
pub in_arrow: bool,
pub in_cond: bool,
recent: Vec<TOCLOSE>,
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum TOCLOSE {
BRACKETS,
PARENS,
QUOTES,
}
impl IsClosed {
pub fn new() -> IsClosed {
IsClosed {
recent: Vec::new(),
in_arrow: false,
in_cond: false,
}
}
pub fn check(&mut self, sym: &str) {
let a;
if self.recent.len() == 0 {
a = true;
} else {
a = self.recent[self.recent.len() - 1] != TOCLOSE::QUOTES;
};
if a {
match sym {
"(" => {
self.recent.push(TOCLOSE::BRACKETS);
}
"{" => {
self.recent.push(TOCLOSE::PARENS);
}
"}" => {
if self.recent[self.recent.len() - 1] == TOCLOSE::PARENS {
self.recent.pop();
} else {
panic!("close {:?} first", self.recent[self.recent.len() - 1]);
}
}
")" => {
if self.recent[self.recent.len() - 1] == TOCLOSE::BRACKETS {
self.recent.pop();
} else {
panic!("close {:?} first", self.recent[self.recent.len() - 1]);
}
}
"\"" => {
self.recent.push(TOCLOSE::QUOTES);
}
_ => {}
}
} else if sym == "\"" {
self.recent.pop();
}
}
pub fn is(&self) -> bool {
self.recent.len() == 0
}
pub fn unclosed(&self) -> TOCLOSE {
self.recent[self.recent.len() - 1]
}
}
|
use std::ops::{Index, IndexMut};
fn main() {
let mut puzzle = input();
println!("First solution: {}", puzzle.solve());
let mut puzzle = input();
puzzle.expand();
println!("Second solution: {}", puzzle.solve());
}
type Position = (usize, usize);
#[derive(Debug, Clone)]
struct Node {
visited: bool,
distance: u32,
value: u32,
}
impl From<u32> for Node {
fn from(v: u32) -> Self {
Self {
visited: false,
distance: u32::MAX,
value: v,
}
}
}
#[derive(Debug)]
struct Puzzle(Vec<Vec<Node>>);
impl Puzzle {
/// Solve the puzzle with Dijsktra
fn solve(&mut self) -> u32 {
let mut stack: Vec<Position> = [(0, 0)].into_iter().collect();
self[(0, 0)].distance = 0;
while !stack.is_empty() {
// Pop position with smallest distance, we will work on that node next.
let mut smallest_idx = 0;
let mut smallest_dist = u32::MAX;
for (i, p) in stack.iter().enumerate() {
if self[*p].distance < smallest_dist {
smallest_dist = self[*p].distance;
smallest_idx = i;
}
}
let pos = stack.remove(smallest_idx);
if self[pos].visited {
continue;
} else {
self[pos].visited = true;
}
// Update neighbors and add them to the stack
for next in self.neighbors(pos) {
let new_dist = self[next].value + self[pos].distance;
if new_dist < self[next].distance {
self[next].distance = new_dist;
}
stack.push(next);
}
}
self.0.last().unwrap().last().unwrap().distance
}
/// Only returns unvisited neighbors
fn neighbors(&self, p: Position) -> Vec<Position> {
let mut result = Vec::new();
if p.0 > 0 {
result.push((p.0 - 1, p.1));
}
if p.1 > 0 {
result.push((p.0, p.1 - 1));
}
if p.0 < self.0.len() - 1 {
result.push((p.0 + 1, p.1));
}
if p.1 < self.0[0].len() - 1 {
result.push((p.0, p.1 + 1));
}
result
.into_iter()
.filter(|p| !self.0[p.0][p.1].visited)
.collect()
}
// Prepare the puzzle for part 2
fn expand(&mut self) {
let small_height = self.0.len();
let small_width = self.0[0].len();
let new_height = small_height * 5;
let new_width = small_width * 5;
let mut field = Vec::new();
for row in 0..new_height {
let mut row_values = Vec::new();
for col in 0..new_width {
let small_row = row % small_height;
let small_col = col % small_width;
let add = (row / small_height) + (col / small_width);
let value = self[(small_row, small_col)].value;
row_values.push((((value + add as u32) - 1) % 9) + 1);
}
field.push(row_values.into_iter().map(Node::from).collect());
}
self.0 = field;
}
}
impl Index<Position> for Puzzle {
type Output = Node;
fn index(&self, index: Position) -> &Self::Output {
&self.0[index.0][index.1]
}
}
impl IndexMut<Position> for Puzzle {
fn index_mut(&mut self, index: Position) -> &mut Self::Output {
&mut self.0[index.0][index.1]
}
}
fn input() -> Puzzle {
Puzzle(
include_str!("../../input/15.txt")
.lines()
.map(|l| {
l.chars()
.map(|c| c.to_digit(10).unwrap())
.map(Node::from)
.collect()
})
.collect(),
)
}
|
use std::error::Error;
use std::fs;
#[derive(Debug)]
pub struct Conf {
pub cpn: String,
pub asno: String,
pub tag: String,
}
impl Conf {
pub fn new(args: Vec<&str>) -> Result<Conf, &'static str> {
if args.len() < 2 {
return Err("not enough arguments");
}
let tag = if args.len() > 2 {
args[2].to_owned()
} else {
"VPN".to_owned()
};
let cpn = args[0].to_owned();
let asno = args[1].to_owned();
Ok(Conf { cpn, asno, tag })
}
}
pub fn read_conf(file: &str) -> Result<Vec<Conf>, Box<dyn Error>> {
let mut result = Vec::new();
let contents = fs::read_to_string(format!("{}.txt", file))?;
for line in contents.lines() {
if line.contains(" ") {
if let Ok(conf) = Conf::new(line.split(" ").collect()) {
result.push(conf);
}
}
}
Ok(result)
}
pub fn run(file: &str) -> Result<Vec<String>, Box<dyn Error>> {
let mut result = Vec::new();
let ass = read_conf(file)?;
for as_ in ass {
let ips = read_as_ips(&as_);
if let Ok(list) = ips {
let mut first = true;
for tmp in list {
let sip = if first {
first = false;
format!(
"add list={} comment={}.{} address={}",
as_.tag, as_.cpn, as_.asno, tmp
)
} else {
format!("add list={} address={}", as_.tag, tmp)
};
result.push(sip);
//println!("{}", sip);
}
}
// println!("{:?}", as_);
}
Ok(result)
}
pub fn read_as_ips(conf: &Conf) -> Result<Vec<String>, Box<dyn Error>> {
let contents = fs::read_to_string(format!("{}.txt", conf.asno))?;
Ok(contents
.trim()
.split(" ")
.filter(|ip| ip.len() >= 7)
.map(|ip| ip.trim().to_owned())
.collect())
}
|
#[doc = "Register `AHB2SMENR` reader"]
pub type R = crate::R<AHB2SMENR_SPEC>;
#[doc = "Register `AHB2SMENR` writer"]
pub type W = crate::W<AHB2SMENR_SPEC>;
#[doc = "Field `GPIOASMEN` reader - IO port A clocks enable during Sleep and Stop modes"]
pub type GPIOASMEN_R = crate::BitReader;
#[doc = "Field `GPIOASMEN` writer - IO port A clocks enable during Sleep and Stop modes"]
pub type GPIOASMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOBSMEN` reader - IO port B clocks enable during Sleep and Stop modes"]
pub type GPIOBSMEN_R = crate::BitReader;
#[doc = "Field `GPIOBSMEN` writer - IO port B clocks enable during Sleep and Stop modes"]
pub type GPIOBSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOCSMEN` reader - IO port C clocks enable during Sleep and Stop modes"]
pub type GPIOCSMEN_R = crate::BitReader;
#[doc = "Field `GPIOCSMEN` writer - IO port C clocks enable during Sleep and Stop modes"]
pub type GPIOCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIODSMEN` reader - IO port D clocks enable during Sleep and Stop modes"]
pub type GPIODSMEN_R = crate::BitReader;
#[doc = "Field `GPIODSMEN` writer - IO port D clocks enable during Sleep and Stop modes"]
pub type GPIODSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOESMEN` reader - IO port E clocks enable during Sleep and Stop modes"]
pub type GPIOESMEN_R = crate::BitReader;
#[doc = "Field `GPIOESMEN` writer - IO port E clocks enable during Sleep and Stop modes"]
pub type GPIOESMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOFSMEN` reader - IO port F clocks enable during Sleep and Stop modes"]
pub type GPIOFSMEN_R = crate::BitReader;
#[doc = "Field `GPIOFSMEN` writer - IO port F clocks enable during Sleep and Stop modes"]
pub type GPIOFSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOGSMEN` reader - IO port G clocks enable during Sleep and Stop modes"]
pub type GPIOGSMEN_R = crate::BitReader;
#[doc = "Field `GPIOGSMEN` writer - IO port G clocks enable during Sleep and Stop modes"]
pub type GPIOGSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOHSMEN` reader - IO port H clocks enable during Sleep and Stop modes"]
pub type GPIOHSMEN_R = crate::BitReader;
#[doc = "Field `GPIOHSMEN` writer - IO port H clocks enable during Sleep and Stop modes"]
pub type GPIOHSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM2SMEN` reader - SRAM2 interface clocks enable during Sleep and Stop modes"]
pub type SRAM2SMEN_R = crate::BitReader;
#[doc = "Field `SRAM2SMEN` writer - SRAM2 interface clocks enable during Sleep and Stop modes"]
pub type SRAM2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OTGFSSMEN` reader - OTG full speed clocks enable during Sleep and Stop modes"]
pub type OTGFSSMEN_R = crate::BitReader;
#[doc = "Field `OTGFSSMEN` writer - OTG full speed clocks enable during Sleep and Stop modes"]
pub type OTGFSSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADCFSSMEN` reader - ADC clocks enable during Sleep and Stop modes"]
pub type ADCFSSMEN_R = crate::BitReader;
#[doc = "Field `ADCFSSMEN` writer - ADC clocks enable during Sleep and Stop modes"]
pub type ADCFSSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AESSMEN` reader - AES accelerator clocks enable during Sleep and Stop modes"]
pub type AESSMEN_R = crate::BitReader;
#[doc = "Field `AESSMEN` writer - AES accelerator clocks enable during Sleep and Stop modes"]
pub type AESSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RNGSMEN` reader - Random Number Generator clocks enable during Sleep and Stop modes"]
pub type RNGSMEN_R = crate::BitReader;
#[doc = "Field `RNGSMEN` writer - Random Number Generator clocks enable during Sleep and Stop modes"]
pub type RNGSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - IO port A clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpioasmen(&self) -> GPIOASMEN_R {
GPIOASMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - IO port B clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiobsmen(&self) -> GPIOBSMEN_R {
GPIOBSMEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - IO port C clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiocsmen(&self) -> GPIOCSMEN_R {
GPIOCSMEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - IO port D clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiodsmen(&self) -> GPIODSMEN_R {
GPIODSMEN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - IO port E clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpioesmen(&self) -> GPIOESMEN_R {
GPIOESMEN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - IO port F clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiofsmen(&self) -> GPIOFSMEN_R {
GPIOFSMEN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - IO port G clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiogsmen(&self) -> GPIOGSMEN_R {
GPIOGSMEN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - IO port H clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiohsmen(&self) -> GPIOHSMEN_R {
GPIOHSMEN_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 9 - SRAM2 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sram2smen(&self) -> SRAM2SMEN_R {
SRAM2SMEN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 12 - OTG full speed clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn otgfssmen(&self) -> OTGFSSMEN_R {
OTGFSSMEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - ADC clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn adcfssmen(&self) -> ADCFSSMEN_R {
ADCFSSMEN_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 16 - AES accelerator clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn aessmen(&self) -> AESSMEN_R {
AESSMEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 18 - Random Number Generator clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn rngsmen(&self) -> RNGSMEN_R {
RNGSMEN_R::new(((self.bits >> 18) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - IO port A clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpioasmen(&mut self) -> GPIOASMEN_W<AHB2SMENR_SPEC, 0> {
GPIOASMEN_W::new(self)
}
#[doc = "Bit 1 - IO port B clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiobsmen(&mut self) -> GPIOBSMEN_W<AHB2SMENR_SPEC, 1> {
GPIOBSMEN_W::new(self)
}
#[doc = "Bit 2 - IO port C clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiocsmen(&mut self) -> GPIOCSMEN_W<AHB2SMENR_SPEC, 2> {
GPIOCSMEN_W::new(self)
}
#[doc = "Bit 3 - IO port D clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiodsmen(&mut self) -> GPIODSMEN_W<AHB2SMENR_SPEC, 3> {
GPIODSMEN_W::new(self)
}
#[doc = "Bit 4 - IO port E clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpioesmen(&mut self) -> GPIOESMEN_W<AHB2SMENR_SPEC, 4> {
GPIOESMEN_W::new(self)
}
#[doc = "Bit 5 - IO port F clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiofsmen(&mut self) -> GPIOFSMEN_W<AHB2SMENR_SPEC, 5> {
GPIOFSMEN_W::new(self)
}
#[doc = "Bit 6 - IO port G clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiogsmen(&mut self) -> GPIOGSMEN_W<AHB2SMENR_SPEC, 6> {
GPIOGSMEN_W::new(self)
}
#[doc = "Bit 7 - IO port H clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiohsmen(&mut self) -> GPIOHSMEN_W<AHB2SMENR_SPEC, 7> {
GPIOHSMEN_W::new(self)
}
#[doc = "Bit 9 - SRAM2 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sram2smen(&mut self) -> SRAM2SMEN_W<AHB2SMENR_SPEC, 9> {
SRAM2SMEN_W::new(self)
}
#[doc = "Bit 12 - OTG full speed clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn otgfssmen(&mut self) -> OTGFSSMEN_W<AHB2SMENR_SPEC, 12> {
OTGFSSMEN_W::new(self)
}
#[doc = "Bit 13 - ADC clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn adcfssmen(&mut self) -> ADCFSSMEN_W<AHB2SMENR_SPEC, 13> {
ADCFSSMEN_W::new(self)
}
#[doc = "Bit 16 - AES accelerator clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn aessmen(&mut self) -> AESSMEN_W<AHB2SMENR_SPEC, 16> {
AESSMEN_W::new(self)
}
#[doc = "Bit 18 - Random Number Generator clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn rngsmen(&mut self) -> RNGSMEN_W<AHB2SMENR_SPEC, 18> {
RNGSMEN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "AHB2 peripheral clocks enable in Sleep and Stop modes register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2smenr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ahb2smenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB2SMENR_SPEC;
impl crate::RegisterSpec for AHB2SMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb2smenr::R`](R) reader structure"]
impl crate::Readable for AHB2SMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb2smenr::W`](W) writer structure"]
impl crate::Writable for AHB2SMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB2SMENR to value 0x0005_32ff"]
impl crate::Resettable for AHB2SMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x0005_32ff;
}
|
use std::io::stdin;
pub fn get_name() -> String {
let mut name = String::new();
println!("Please enter your name");
stdin().read_line(&mut name).unwrap();
name
}
|
fn main() {
let input: &str = include_str!("input.txt");
let mut sections = input.split("\n\n");
let grid_string = sections.next().unwrap();
let fold_instructions = sections.next().unwrap();
let highest_coords = get_highest_coord(grid_string);
let mut grid = vec![vec![false; highest_coords.x as usize + 1]; highest_coords.y as usize + 1];
update_grid_from_coords(grid_string, &mut grid);
process_fold_instructions(fold_instructions, &mut grid);
// Part 2
print_grid(&grid);
// Part 1
//println!("{:?}", count_trues(&grid));
}
struct Coord {
x: u16,
y: u16,
}
impl Coord {
fn from(x: u16, y: u16) -> Coord {
Coord { x, y }
}
}
fn process_fold_instructions(fold_instructions: &str, grid: &mut Vec<Vec<bool>>) {
for line in fold_instructions.lines() {
if line.starts_with("fold along y=") {
let num = line.replace("fold along y=", "");
let num = num.parse::<u16>().unwrap();
for y in num as usize..grid.len() {
let new_y = num as usize - (y - num as usize);
for x in 0..grid[0].len() {
if grid[y][x] {
grid[new_y][x] = true;
}
}
}
grid.resize(num as usize, vec![false; 0]);
}
if line.starts_with("fold along x=") {
let num = line.replace("fold along x=", "");
let num = num.parse::<u16>().unwrap();
for y in 0..grid.len() {
for x in num as usize..grid[y].len() {
let new_x = num as usize - (x - num as usize);
if grid[y][x] {
grid[y][new_x] = true;
}
}
grid[y].resize(num as usize, false);
}
}
// Part 1 - add the break
//break;
}
}
fn count_trues(list: &Vec<Vec<bool>>) -> u32 {
let mut count = 0;
for y in 0..list.len() {
for x in 0..list[0].len() {
if list[y][x] {
count += 1;
}
}
}
count
}
fn print_grid(grid: &Vec<Vec<bool>>) {
for y in 0..grid.len() {
for x in 0..grid[0].len() {
if grid[y][x] { print!("#"); } else { print!(" "); }
}
println!();
}
}
fn update_grid_from_coords(str: &str, grid: &mut Vec<Vec<bool>>) {
str.lines()
.map(get_coord_from_line)
.for_each(|item| grid[item.y as usize][item.x as usize] = true);
}
fn get_coord_from_line(ll: &str) -> Coord {
let xy: Vec<&str> = ll.split(',').collect();
let x = str::parse::<u16>(xy[0]).unwrap();
let y = str::parse::<u16>(xy[1]).unwrap();
Coord::from(x, y)
}
fn get_highest_coord(string: &str) -> Coord {
let mut x = 0;
let mut y = 0;
let mut lines = string.lines();
loop {
let l = lines.next();
if l == None { break; }
let c = get_coord_from_line(l.unwrap());
if c.x > x { x = c.x; }
if c.y > y { y = c.y; }
}
Coord::from(x, y)
} |
use clockwork::Modules;
use clockwork::routes::{self, Routes, UriParams, BodyParams, RouteModel};
use clockwork_handlebars::ViewRenderer;
use models::NewSubmit;
pub fn register(routes: &mut Routes) {
routes.get("/projects/new", new);
routes.post("/projects/new", routes::model_handler(new_submit));
}
fn new(modules: &Modules, _: UriParams, _: BodyParams) -> Vec<u8> {
let views: &ViewRenderer = modules.get().unwrap();
views.render("projects/new", &()).into()
}
fn new_submit(modules: &Modules, params: NewModel) -> Vec<u8> {
let views: &ViewRenderer = modules.get().unwrap();
views.render("projects/new_submit", &NewSubmit {title: params.title}).into()
}
pub struct NewModel {
pub title: String,
}
impl RouteModel for NewModel {
fn from(_url: UriParams, body: BodyParams) -> Self {
let body = body.as_form();
NewModel {
title: body.get("title").unwrap()
}
}
}
|
// Copyright 2015-2016 Joe Neeman.
//
// 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.
use dfa::{Dfa, RetTrait};
use dfa::trie::Trie;
use nfa::{Accept, StateIdx};
use std::cmp::{Ordering, PartialOrd};
use std::collections::{HashSet, VecDeque};
use std::mem::swap;
// TODO: These limits are pretty arbitrary (copied from the regex crate).
const NUM_PREFIX_LIMIT: usize = 30;
const PREFIX_LEN_LIMIT: usize = 15;
/// A pair of a byte sequence and the index of the state that we are in after encountering that
/// sequence.
#[derive(Clone, Debug, PartialEq)]
pub struct PrefixPart(pub Vec<u8>, pub StateIdx);
pub struct PrefixSearcher {
active: VecDeque<PrefixPart>,
current: PrefixPart,
suffixes: Trie,
finished: Vec<PrefixPart>,
// The set of prefixes is complete if:
// - we're done with active prefixes before we go over any of our limits, and
// - we didn't encounter any states that accept conditionally.
complete: bool,
max_prefixes: usize,
max_len: usize,
}
impl PrefixSearcher {
pub fn extract<T: RetTrait>(dfa: &Dfa<T>, state: StateIdx) -> Vec<PrefixPart> {
let mut searcher = PrefixSearcher::new();
searcher.search(dfa, state);
searcher.finished
}
fn new() -> PrefixSearcher {
PrefixSearcher {
active: VecDeque::new(),
current: PrefixPart(Vec::new(), 0),
suffixes: Trie::new(),
finished: Vec::new(),
complete: true,
max_prefixes: NUM_PREFIX_LIMIT,
max_len: PREFIX_LEN_LIMIT,
}
}
fn bail_out(&mut self) {
let mut current = PrefixPart(Vec::new(), 0);
let mut active = VecDeque::new();
swap(&mut current, &mut self.current);
swap(&mut active, &mut self.active);
self.finished.extend(active.into_iter());
self.finished.push(current);
self.complete = false;
}
fn add(&mut self, new_prefs: Vec<PrefixPart>) {
debug_assert!(new_prefs.len() + self.active.len() + self.finished.len() <= self.max_prefixes);
for p in new_prefs.into_iter() {
if p.0.len() >= self.max_len {
self.finished.push(p);
} else {
self.active.push_back(p);
}
}
}
fn too_many(&mut self, more: usize) -> bool {
self.active.len() + self.finished.len() + more > self.max_prefixes
}
fn search<T: RetTrait>(&mut self, dfa: &Dfa<T>, state: StateIdx) {
self.active.push_back(PrefixPart(Vec::new(), state));
self.suffixes.insert(vec![].into_iter(), state);
while !self.active.is_empty() {
self.current = self.active.pop_front().unwrap();
let trans = dfa.transitions(self.current.1);
let mut next_prefs = Vec::new();
for (ch, next_state) in trans.keys_values() {
let mut next_pref = self.current.0.clone();
next_pref.push(ch);
next_prefs.push(PrefixPart(next_pref, *next_state));
}
// Discard any new prefix that is the suffix of some existing prefix.
next_prefs.retain(|pref| {
let rev_bytes = pref.0.iter().cloned().rev();
!self.suffixes
.prefixes(rev_bytes)
.any(|s| s == pref.1)
});
for pref in &next_prefs {
self.suffixes.insert(pref.0.iter().cloned().rev(), pref.1);
}
// Stop searching if we have too many prefixes already, or if we've run into an accept
// state. In principle, we could continue expanding the other prefixes even after we
// run into an accept state, but there doesn't seem much point in having some short
// prefixes and other long prefixes.
if self.too_many(next_prefs.len())
|| *dfa.accept(self.current.1) != Accept::Never {
self.bail_out();
break;
}
self.add(next_prefs);
}
}
}
// A critical segment is a sequence of bytes that we must match if we want to get to a particular
// state. That sequence need not necessarily correspond to a unique path in the DFA, however.
// Therefore, we store the sequence of bytes and also a set of possible paths that we might have
// traversed while reading those bytes.
#[derive(Clone, Debug, PartialEq)]
pub struct CriticalSegment {
bytes: Vec<u8>,
paths: HashSet<Vec<StateIdx>>,
}
// The stdlib seems to have searching functions for &str, but not for &[u8]. If they get added, we
// can remove this.
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len())
.enumerate()
.find(|x| x.1 == needle)
.map(|y| y.0)
}
// For two critical segments a and b, we say a <= b if it is more specific than b: either a's
// byte sequence contains b's byte sequence or else the byte sequences are the same and a's set of
// paths is a subset of b's set of paths.
// TODO: not sure if this is necessary
impl PartialOrd for CriticalSegment {
fn partial_cmp(&self, other: &CriticalSegment) -> Option<Ordering> {
fn less(a: &CriticalSegment, b: &CriticalSegment) -> bool {
let a_len = a.bytes.len();
let b_len = b.bytes.len();
(a_len > b_len && find(&a.bytes, &b.bytes).is_some())
|| (a.bytes == b.bytes && a.paths.is_subset(&b.paths))
}
if less(self, other) {
Some(Ordering::Less)
} else if less(other, self) {
Some(Ordering::Greater)
} else {
None
}
}
}
/*
impl CriticalSegment {
pub fn intersection(xs: &[CriticalSegment], ys: &[CriticalSegment]) -> Vec<CriticalSegment> {
let common = maximal_common_substrings(
xs.iter().map(|x| &x.bytes[..]),
ys.iter().map(|y| &y.bytes[..]));
let mut ret = Vec::new();
for s in common {
let mut paths = HashSet::new();
for x in xs.iter().chain(ys.iter()) {
// We look for only the first occurence of the substring in x.
if let Some(pos) = find(&x.bytes, &s) {
paths.extend(x.paths.iter().map(|p| p[pos..(pos + s.len())].to_vec()));
}
}
ret.push(CriticalSegment { bytes: s, paths: paths });
}
ret
}
}
// Finds all strings that are
// - a substring of some element of xs,
// - a substring of some element of ys, and
// - maximal among all strings satisfying the first two conditions.
//
// Note that this implementation is *extremely* naive -- an efficient implementation would probably
// want to use a generalized suffix tree. But since the strings we deal with here are small, we can
// sort of get away with it.
fn maximal_common_substrings<'a, I, J>(xs: I, ys: J) -> HashSet<Vec<u8>>
where I: Iterator<Item=&'a [u8]>, J: Iterator<Item=&'a [u8]> {
let mut ys_substrings = HashSet::new();
let mut common_substrings = HashSet::new();
for y in ys {
let len = y.len();
for i in 0..len {
for j in i..len {
ys_substrings.insert(&y[i..(j + 1)]);
}
}
}
for x in xs {
let len = x.len();
for i in 0..len {
for j in i..len {
if ys_substrings.contains(&x[i..(j + 1)]) {
common_substrings.insert(x[i..(j + 1)].to_vec());
}
}
}
}
// Now prune out anything that isn't maximal.
let mut ret = common_substrings.clone();
for s in &common_substrings {
let len = s.len();
for i in 0..len {
for j in i..len {
// Make sure we're only looking at proper substrings of s.
if i > 0 || j < len - 1 {
ret.remove(&s[i..(j + 1)]);
}
}
}
}
ret
}
*/
#[cfg(test)]
mod tests {
use dfa;
use look::Look;
use quickcheck::{QuickCheck, quickcheck, StdGen, TestResult};
use rand;
use super::*;
//use super::{find, maximal_common_substrings};
fn qc(size: usize) -> QuickCheck<StdGen<rand::ThreadRng>> {
QuickCheck::new().gen(StdGen::new(rand::thread_rng(), size))
}
macro_rules! test_prefix {
($name:ident, $re_str:expr, $answer:expr, $max_num:expr, $max_len:expr) => {
#[test]
fn $name() {
let dfa = dfa::tests::make_dfa($re_str).unwrap();
println!("{:?}", dfa);
let mut pref = PrefixSearcher::new();
pref.max_prefixes = $max_num;
pref.max_len = $max_len;
pref.search(&dfa, dfa.init_state(Look::Full).unwrap());
let mut prefs = pref.finished.into_iter().map(|x| x.0).collect::<Vec<_>>();
prefs.sort();
let answer: Vec<Vec<u8>> = $answer.iter()
.map(|s| s.as_bytes().to_owned())
.collect();
assert_eq!(prefs, answer);
}
};
}
test_prefix!(long,
"[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ",
vec!["XABCDEFGHIJKLMNOPQRSTUVWXYZ",
"YABCDEFGHIJKLMNOPQRSTUVWXYZ",
"ZABCDEFGHIJKLMNOPQRSTUVWXYZ",],
3, 30);
test_prefix!(case_insensitive,
"(?i)abc[a-z]",
vec!["ABC", "ABc", "AbC", "Abc", "aBC", "aBc", "abC", "abc"],
30, 5);
test_prefix!(byte_set,
"[ac]",
vec!["a", "c"],
30, 5);
test_prefix!(pruned_repetition,
"a+bc",
vec!["abc"],
10, 10);
test_prefix!(pruned_empty_repetition,
"[a-zA-Z]*bc",
vec!["bc"],
10, 10);
/*
#[test]
fn common_substrings() {
fn sound(xs: Vec<Vec<u8>>, ys: Vec<Vec<u8>>) -> bool {
let result = maximal_common_substrings(xs.iter().map(|x| &x[..]), ys.iter().map(|y| &y[..]));
// Everything in the result should be a substring of something in xs.
result.iter().all(|x| xs.iter().any(|y| find(&y, &x).is_some()))
// Everything in the result should be a substring of something in xs.
&& result.iter().all(|x| ys.iter().any(|y| find(&y, &x).is_some()))
// Nothing in the result should be a strict substring of anything else.
&& result.iter().all(
|x| !result.iter().any(|y| y.len() > x.len() && find(&y, &x).is_some()))
}
// If z is a substring of something in xs and something in ys then it must be a substring
// of something in result.
fn complete(xs: Vec<Vec<u8>>, ys: Vec<Vec<u8>>, z: Vec<u8>) -> TestResult {
if z.is_empty()
|| !xs.iter().any(|x| find(&x, &z).is_some())
|| !ys.iter().any(|y| find(&y, &z).is_some()) {
return TestResult::discard();
}
let result = maximal_common_substrings(xs.iter().map(|x| &x[..]), ys.iter().map(|y| &y[..]));
TestResult::from_bool(result.iter().any(|x| find(&x, &z).is_some()))
}
qc(10).quickcheck(sound as fn(_, _) -> _);
qc(10).quickcheck(complete as fn(_, _, _) -> _);
}
*/
}
|
use image;
use image::{GenericImage, Rgb, Rgba};
use texture::{Pixel, Texture};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel = P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimensions().1
}
fn get(&self, x: u32, y: u32) -> Option<I::Pixel> {
if self.in_bounds(x, y) {
Some(self.get_pixel(x, y))
} else {
None
}
}
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn outline() -> Rgba<u8> {
Rgba([255, 0, 0, 255])
}
}
impl Pixel for Rgb<u8> {
fn is_transparent(&self) -> bool {
false
}
fn transparency() -> Option<Rgb<u8>> {
None
}
fn outline() -> Rgb<u8> {
Rgb([255, 0, 0])
}
}
|
use crate::{
grid::{
config::{ColoredConfig, Entity},
dimension::CompleteDimensionVecRecords,
records::{ExactRecords, PeekableRecords, Records, RecordsMut},
util::string::{count_lines, get_lines},
},
settings::{measurement::Measurement, peaker::Peaker, CellOption, Height, TableOption},
};
use super::table_height_limit::TableHeightLimit;
/// A modification for cell/table to increase its height.
///
/// If used for a [`Table`] [`PriorityNone`] is used.
///
/// [`PriorityNone`]: crate::settings::peaker::PriorityNone
/// [`Table`]: crate::Table
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CellHeightLimit<W = usize> {
height: W,
}
impl<W> CellHeightLimit<W> {
/// Constructs a new object.
pub fn new(height: W) -> Self
where
W: Measurement<Height>,
{
Self { height }
}
/// Set's a priority by which the limit logic will be applied.
pub fn priority<P>(self) -> TableHeightLimit<W, P>
where
P: Peaker,
W: Measurement<Height>,
{
TableHeightLimit::new(self.height).priority::<P>()
}
}
impl<W, R> CellOption<R, ColoredConfig> for CellHeightLimit<W>
where
W: Measurement<Height>,
R: Records + ExactRecords + PeekableRecords + RecordsMut<String>,
for<'a> &'a R: Records,
{
fn change(self, records: &mut R, cfg: &mut ColoredConfig, entity: Entity) {
let height = self.height.measure(&*records, cfg);
let count_rows = records.count_rows();
let count_columns = records.count_columns();
for pos in entity.iter(count_rows, count_columns) {
let is_valid_pos = pos.0 < count_rows && pos.1 < count_columns;
if !is_valid_pos {
continue;
}
let text = records.get_text(pos);
let count_lines = count_lines(text);
if count_lines <= height {
continue;
}
let content = limit_lines(text, height);
records.set(pos, content);
}
}
}
impl<R, W> TableOption<R, CompleteDimensionVecRecords<'_>, ColoredConfig> for CellHeightLimit<W>
where
W: Measurement<Height>,
R: Records + ExactRecords + PeekableRecords + RecordsMut<String>,
for<'a> &'a R: Records,
{
fn change(
self,
records: &mut R,
cfg: &mut ColoredConfig,
dims: &mut CompleteDimensionVecRecords<'_>,
) {
let height = self.height.measure(&*records, cfg);
TableHeightLimit::new(height).change(records, cfg, dims)
}
}
fn limit_lines(s: &str, n: usize) -> String {
let mut text = String::new();
for (i, line) in get_lines(s).take(n).enumerate() {
if i > 0 {
text.push('\n');
}
text.push_str(&line);
}
text
}
|
use nom::types::CompleteStr;
use uuid::Uuid;
use std::fmt;
use std::str::FromStr;
use topic::{Reversible, Topic};
use version::Version;
named!(pub topic<CompleteStr, Topic>,
do_parse!(
tag_s!("agents/") >>
agent_id: map_res!(take_until_s!("/"), |s: CompleteStr| FromStr::from_str(s.0)) >>
tag_s!("/") >>
kind: alt!(map!(tag_s!("in"), |_| AgentTopicKind::In) | map!(tag_s!("out"), |_| AgentTopicKind::Out)) >>
tag_s!("/signals.netology-group.services/api/") >>
version: map!(tag_s!("v1"), |_| Version::V1) >>
opt!(tag_s!("/")) >>
eof!() >>
(Topic::Agent(AgentTopic { kind, agent_id, version }))
)
);
#[derive(Debug, PartialEq)]
pub struct AgentTopic {
pub kind: AgentTopicKind,
pub agent_id: Uuid,
pub version: Version,
}
impl AgentTopic {
pub fn new_in(agent_id: Uuid) -> AgentTopic {
AgentTopic {
kind: AgentTopicKind::In,
agent_id,
version: Version::V1,
}
}
}
impl fmt::Display for AgentTopic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"agents/{}/{}/signals.netology-group.services/api/{}",
self.agent_id, self.kind, self.version
)
}
}
impl Reversible for AgentTopic {
type Topic = AgentTopic;
fn get_reverse(&self) -> AgentTopic {
let kind = match self.kind {
AgentTopicKind::In => AgentTopicKind::Out,
AgentTopicKind::Out => AgentTopicKind::In,
};
AgentTopic {
kind,
agent_id: self.agent_id,
version: self.version,
}
}
}
#[derive(Debug, PartialEq)]
pub enum AgentTopicKind {
In,
Out,
}
impl fmt::Display for AgentTopicKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let value = format!("{:?}", self).to_lowercase();
f.write_str(&value)
}
}
#[cfg(test)]
mod tests {
use super::*;
use nom::types::CompleteStr;
use nom::Err::Error as NomError;
use nom::ErrorKind::*;
#[test]
fn parse_topic() {
let t = topic(CompleteStr("agents/e19c94cf-53eb-4048-9c94-7ae74ff6d912/out/signals.netology-group.services/api/v1"));
let topic_exp = Topic::Agent(AgentTopic {
kind: AgentTopicKind::Out,
agent_id: Uuid::parse_str("e19c94cf-53eb-4048-9c94-7ae74ff6d912").unwrap(),
version: Version::V1,
});
assert_eq!(t, Ok((CompleteStr(""), topic_exp)));
let t = topic(CompleteStr("agents/e19c94cf-53eb-4048-9c94-7ae74ff6d912/out/signals.netology-group.services/api/v1/"));
let topic_exp = Topic::Agent(AgentTopic {
kind: AgentTopicKind::Out,
agent_id: Uuid::parse_str("e19c94cf-53eb-4048-9c94-7ae74ff6d912").unwrap(),
version: Version::V1,
});
assert_eq!(t, Ok((CompleteStr(""), topic_exp)));
}
#[test]
fn parse_topic_with_wrong_uuid() {
let topic = topic(CompleteStr(
"agents/e19c94cf-53eb-4048-9c94-7ae74ff6d91/out/signals.netology-group.services/api/v1",
));
assert_eq!(topic, Err(NomError(error_position!(CompleteStr("e19c94cf-53eb-4048-9c94-7ae74ff6d91/out/signals.netology-group.services/api/v1"), MapRes))));
}
#[test]
fn parse_topic_with_extra_words() {
let topic = topic(CompleteStr("agents/e19c94cf-53eb-4048-9c94-7ae74ff6d912/out/signals.netology-group.services/api/v1/rooms"));
assert_eq!(
topic,
Err(NomError(error_position!(CompleteStr("rooms"), Eof)))
);
}
#[test]
fn get_reverse_topic() {
let out_topic = AgentTopic {
kind: AgentTopicKind::Out,
agent_id: Uuid::parse_str("e19c94cf-53eb-4048-9c94-7ae74ff6d912").unwrap(),
version: Version::V1,
};
let expected = AgentTopic {
kind: AgentTopicKind::In,
agent_id: Uuid::parse_str("e19c94cf-53eb-4048-9c94-7ae74ff6d912").unwrap(),
version: Version::V1,
};
assert_eq!(out_topic.get_reverse(), expected);
}
#[test]
fn display_topic() {
let topic = Topic::Agent(AgentTopic {
kind: AgentTopicKind::Out,
agent_id: Uuid::parse_str("e19c94cf-53eb-4048-9c94-7ae74ff6d912").unwrap(),
version: Version::V1,
});
let expected = "agents/e19c94cf-53eb-4048-9c94-7ae74ff6d912/out/signals.netology-group.services/api/v1";
assert_eq!(topic.to_string(), expected);
}
}
|
pub struct PasswordEncoder {}
impl PasswordEncoder {
pub fn encode(raw_password: &str) -> String {
let digest = md5::compute(raw_password);
format!("{:x}", digest)
}
pub fn verify(password: &str, raw_password: &str) -> bool {
if password.eq(raw_password) {
return true;
}
let hashed = PasswordEncoder::encode(raw_password);
password.eq(&hashed)
}
}
///测试模块
#[cfg(test)]
mod test {
use crate::util::password_encoder::PasswordEncoder;
///测试密码 编码和解码
#[test]
fn test_encode() {
let s = PasswordEncoder::encode("123456");
println!("{}", s);
assert_eq!(
PasswordEncoder::encode("123456"),
PasswordEncoder::encode("123456")
)
}
#[test]
fn test_verify() {
let password = "12345";
let raw_password = "12345";
assert!(PasswordEncoder::verify(password, raw_password));
let encode_password = PasswordEncoder::encode(password);
assert!(PasswordEncoder::verify(&encode_password, password));
}
}
|
use std::time::Duration;
use actix::prelude::*;
use actix_broker::{BrokerIssue, SystemBroker};
use actix_web::client::Client;
use futures::{compat::Future01CompatExt, FutureExt, TryFutureExt};
use crate::caltrain_status::CaltrainStatus;
use crate::station::Station;
pub struct CStatusFetcher {
station: Station,
duration: Duration,
}
impl CStatusFetcher {
pub fn new(station: Station, duration: Duration) -> Self {
CStatusFetcher { station, duration }
}
async fn update_status(station: Station) -> Result<CaltrainStatus, String> {
let result = Client::default()
.get(station.get_url())
.send()
.compat()
.await;
let mut resp = match result {
Ok(resp) => resp,
Err(e) => {
return Err(format!("error making request to caltrain: {}", e));
}
};
let bytes = match resp.body().compat().await {
Ok(bytes) => bytes,
Err(e) => {
return Err(format!("invalid payload from caltrain: {}", e));
}
};
let text = match String::from_utf8(bytes.to_vec()) {
Ok(text) => text,
Err(e) => {
return Err(format!(
"error while parsing resposne from caltrain as utf-8: {}",
e
));
}
};
match CaltrainStatus::from_html(text) {
Ok(cstatus) => Ok(cstatus),
Err(e) => Err(format!("error parsing caltrain xml: {}", e)),
}
}
fn run_status_update(&mut self, ctx: &mut <CStatusFetcher as Actor>::Context) {
let status_update_future = CStatusFetcher::update_status(self.station)
.unit_error()
.boxed_local()
.compat();
let wrapped = actix::fut::wrap_future::<_, Self>(status_update_future);
let emitted = wrapped.map(|result, actor, _| match result {
Ok(cstatus) => actor.issue_async::<SystemBroker, _>(cstatus),
Err(msg) => eprintln!("{}", msg),
});
ctx.spawn(emitted);
}
}
impl Actor for CStatusFetcher {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
ctx.run_interval(self.duration, |csf: &mut Self, ctx: &mut Self::Context| {
csf.run_status_update(ctx)
});
self.run_status_update(ctx);
}
}
|
extern crate rocket_contrib;
extern crate sl_lib;
extern crate tera;
use diesel::prelude::*;
use rocket_contrib::Template;
use tera::Context;
// use sl_lib::models::{Post, User};
use sl_lib::models::Post;
use sl_lib::*;
// use sl_lib::markdown::markdown_to_html; // use it for filter later instead of writing html to database
#[get("/blog/read/<post_title>")]
fn read(connection: DbConn, post_title: String) -> Template {
use schema::posts::dsl::*;
// use schema::users::dsl::*;
let mut context = Context::new();
// println!("GET Request to blog with title {}", post_title);
// let pattern = format!("%{}%", post_title);
// equals to? http://docs.diesel.rs/diesel/query_dsl/trait.RunQueryDsl.html#method.first
let pattern = format!("{}%", post_title.replace("-", " "));
// https://www.postgresql.org/docs/9.3/static/functions-matching.html
let result_post = posts
.filter(title.like(pattern))
.first::<Post>(&*connection) // equals to .limit(1), .load::<Post>(&*connection)
.expect(&format!("Error loading a post with title {}", post_title));
// let user_list = users
// .load::<User>(&*connection)
// .expect("Error loading users");
// println!("test {:?}", &post);
// serialize?
context.insert("post", &result_post);
// context.insert("users", &user_list);
// context.insert("content", &"**bold** and `beautiful`");
Template::render("posts/read_post", &context)
}
|
use crate::{prelude::*, utils::*};
use arrow::record_batch::RecordBatch;
use itertools::Itertools;
use log::debug;
use owning_ref::OwningHandle;
use rayon::prelude::*;
use std::marker::PhantomData;
type SourceParserHandle<'a, S> = OwningHandle<
Box<<S as Source>::Partition>,
DummyBox<<<S as Source>::Partition as SourcePartition>::Parser<'a>>,
>;
/// The iterator that returns arrow in `RecordBatch`
pub struct ArrowBatchIter<'a, S, TP>
where
S: Source + 'a,
TP: Transport<TSS = S::TypeSystem, TSD = ArrowTypeSystem, S = S, D = ArrowDestination>,
{
dst: ArrowDestination,
dst_parts: Vec<ArrowPartitionWriter>,
src_parts: Option<Vec<S::Partition>>,
src_parsers: Vec<SourceParserHandle<'a, S>>,
dorder: DataOrder,
src_schema: Vec<S::TypeSystem>,
dst_schema: Vec<ArrowTypeSystem>,
batch_size: usize,
_phantom: PhantomData<TP>,
}
impl<'a, S, TP> ArrowBatchIter<'a, S, TP>
where
S: Source + 'a,
TP: Transport<TSS = S::TypeSystem, TSD = ArrowTypeSystem, S = S, D = ArrowDestination>,
{
pub fn new(
src: S,
mut dst: ArrowDestination,
origin_query: Option<String>,
queries: &[CXQuery<String>],
batch_size: usize,
) -> Result<Self, TP::Error> {
let dispatcher = Dispatcher::<_, _, TP>::new(src, &mut dst, queries, origin_query);
let (dorder, src_parts, dst_parts, src_schema, dst_schema) = dispatcher.prepare()?;
Ok(Self {
dst,
dst_parts,
src_parts: Some(src_parts),
src_parsers: vec![],
dorder,
src_schema,
dst_schema,
batch_size,
_phantom: PhantomData,
})
}
fn run_batch(&mut self) -> Result<(), TP::Error> {
let schemas: Vec<_> = self
.src_schema
.iter()
.zip_eq(&self.dst_schema)
.map(|(&src_ty, &dst_ty)| (src_ty, dst_ty))
.collect();
debug!("Start writing");
let dorder = self.dorder;
let batch_size = self.batch_size;
// parse and write
self.dst_parts
.par_iter_mut()
.zip_eq(self.src_parsers.par_iter_mut())
.enumerate()
.try_for_each(|(i, (dst, src))| -> Result<(), TP::Error> {
let parser: &mut <S::Partition as crate::sources::SourcePartition>::Parser<'_> =
&mut *src;
let mut processed_rows = 0;
match dorder {
DataOrder::RowMajor => loop {
let (mut n, is_last) = parser.fetch_next()?;
n = std::cmp::min(n, batch_size - processed_rows); // only process until batch size is reached
processed_rows += n;
dst.aquire_row(n)?;
for _ in 0..n {
#[allow(clippy::needless_range_loop)]
for col in 0..dst.ncols() {
{
let (s1, s2) = schemas[col];
TP::process(s1, s2, parser, dst)?;
}
}
}
if is_last || processed_rows >= batch_size {
break;
}
},
DataOrder::ColumnMajor => loop {
let (mut n, is_last) = parser.fetch_next()?;
n = std::cmp::min(n, batch_size - processed_rows);
processed_rows += n;
dst.aquire_row(n)?;
#[allow(clippy::needless_range_loop)]
for col in 0..dst.ncols() {
for _ in 0..n {
{
let (s1, s2) = schemas[col];
TP::process(s1, s2, parser, dst)?;
}
}
}
if is_last || processed_rows >= batch_size {
break;
}
},
}
debug!("Finalize partition {}", i);
dst.finalize()?;
debug!("Partition {} finished", i);
Ok(())
})?;
Ok(())
}
}
impl<'a, S, TP> Iterator for ArrowBatchIter<'a, S, TP>
where
S: Source + 'a,
TP: Transport<TSS = S::TypeSystem, TSD = ArrowTypeSystem, S = S, D = ArrowDestination>,
{
type Item = RecordBatch;
fn next(&mut self) -> Option<Self::Item> {
let res = self.dst.record_batch().unwrap();
if res.is_some() {
return res;
}
self.run_batch().unwrap();
self.dst.record_batch().unwrap()
}
}
// impl<'a, S, TP> Iterator for ArrowBatchIter<'a, S, TP>
// where
// S: Source + 'a,
// TP: Transport<TSS = S::TypeSystem, TSD = ArrowTypeSystem, S = S, D = ArrowDestination>,
// {
// type Item = Result<RecordBatch, TP::Error>;
// fn next(&mut self) -> Option<Self::Item> {
// match self.dst.record_batch() {
// Ok(Some(res)) => return Some(Ok(res)),
// Ok(None) => {}
// Err(e) => return Some(Err(e.into())),
// }
// match self.run_batch() {
// Err(e) => return Some(Err(e)),
// Ok(()) => {}
// }
// match self.dst.record_batch() {
// Err(e) => Some(Err(e.into())),
// Ok(Some(res)) => Some(Ok(res)),
// Ok(None) => None,
// }
// }
// }
pub trait RecordBatchIterator {
fn get_schema(&self) -> (RecordBatch, &[String]);
fn prepare(&mut self);
fn next_batch(&mut self) -> Option<RecordBatch>;
}
impl<'a, S, TP> RecordBatchIterator for ArrowBatchIter<'a, S, TP>
where
S: Source + 'a,
TP: Transport<TSS = S::TypeSystem, TSD = ArrowTypeSystem, S = S, D = ArrowDestination>,
{
fn get_schema(&self) -> (RecordBatch, &[String]) {
(self.dst.empty_batch(), self.dst.names())
}
fn prepare(&mut self) {
let src_parts = self.src_parts.take().unwrap();
self.src_parsers = src_parts
.into_par_iter()
.map(|part| {
OwningHandle::new_with_fn(Box::new(part), |part: *const S::Partition| unsafe {
DummyBox((*(part as *mut S::Partition)).parser().unwrap())
})
})
.collect();
}
fn next_batch(&mut self) -> Option<RecordBatch> {
self.next()
}
}
|
#[doc = "Register `DMAMR` reader"]
pub type R = crate::R<DMAMR_SPEC>;
#[doc = "Register `DMAMR` writer"]
pub type W = crate::W<DMAMR_SPEC>;
#[doc = "Field `SWR` reader - Software Reset When this bit is set, the MAC and the DMA controller reset the logic and all internal registers of the DMA, MTL, and MAC. This bit is automatically cleared after the reset operation is complete in all clock domains. Before reprogramming any register, a value of zero should be read in this bit. Note: The reset operation is complete only when all resets in all active clock domains are deasserted. Therefore, it is essential that all PHY inputs clocks (applicable for the selected PHY interface) are present for software reset completion. The time to complete the software reset operation depends on the frequency of the slowest active clock."]
pub type SWR_R = crate::BitReader;
#[doc = "Field `SWR` writer - Software Reset When this bit is set, the MAC and the DMA controller reset the logic and all internal registers of the DMA, MTL, and MAC. This bit is automatically cleared after the reset operation is complete in all clock domains. Before reprogramming any register, a value of zero should be read in this bit. Note: The reset operation is complete only when all resets in all active clock domains are deasserted. Therefore, it is essential that all PHY inputs clocks (applicable for the selected PHY interface) are present for software reset completion. The time to complete the software reset operation depends on the frequency of the slowest active clock."]
pub type SWR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DA` reader - DMA Tx or Rx Arbitration Scheme This bit specifies the arbitration scheme between the Transmit and Receive paths of all channels: The priority between the paths is according to the priority specified in Bits\\[14:12\\]
and the priority weight is specified in the TXPR bit. The Tx path has priority over the Rx path when the TXPR bit is set. Otherwise, the Rx path has priority over the Tx path."]
pub type DA_R = crate::BitReader;
#[doc = "Field `DA` writer - DMA Tx or Rx Arbitration Scheme This bit specifies the arbitration scheme between the Transmit and Receive paths of all channels: The priority between the paths is according to the priority specified in Bits\\[14:12\\]
and the priority weight is specified in the TXPR bit. The Tx path has priority over the Rx path when the TXPR bit is set. Otherwise, the Rx path has priority over the Tx path."]
pub type DA_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TXPR` reader - Transmit priority When set, this bit indicates that the Tx DMA has higher priority than the Rx DMA during arbitration for the system-side bus."]
pub type TXPR_R = crate::BitReader;
#[doc = "Field `TXPR` writer - Transmit priority When set, this bit indicates that the Tx DMA has higher priority than the Rx DMA during arbitration for the system-side bus."]
pub type TXPR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PR` reader - Priority ratio These bits control the priority ratio in weighted round-robin arbitration between the Rx DMA and Tx DMA. These bits are valid only when the DA bit is reset. The priority ratio is Rx:Tx or Tx:Rx depending on whether the TXPR bit is reset or set."]
pub type PR_R = crate::FieldReader;
#[doc = "Field `PR` writer - Priority ratio These bits control the priority ratio in weighted round-robin arbitration between the Rx DMA and Tx DMA. These bits are valid only when the DA bit is reset. The priority ratio is Rx:Tx or Tx:Rx depending on whether the TXPR bit is reset or set."]
pub type PR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `INTM` reader - Interrupt Mode This field defines the interrupt mode of the Ethernet peripheral. The behavior of the interrupt signal and of the RI/TI bits in the ETH_DMACSR register changes depending on the INTM value (refer to Table�651: Transfer complete interrupt behavior)."]
pub type INTM_R = crate::FieldReader;
#[doc = "Field `INTM` writer - Interrupt Mode This field defines the interrupt mode of the Ethernet peripheral. The behavior of the interrupt signal and of the RI/TI bits in the ETH_DMACSR register changes depending on the INTM value (refer to Table�651: Transfer complete interrupt behavior)."]
pub type INTM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bit 0 - Software Reset When this bit is set, the MAC and the DMA controller reset the logic and all internal registers of the DMA, MTL, and MAC. This bit is automatically cleared after the reset operation is complete in all clock domains. Before reprogramming any register, a value of zero should be read in this bit. Note: The reset operation is complete only when all resets in all active clock domains are deasserted. Therefore, it is essential that all PHY inputs clocks (applicable for the selected PHY interface) are present for software reset completion. The time to complete the software reset operation depends on the frequency of the slowest active clock."]
#[inline(always)]
pub fn swr(&self) -> SWR_R {
SWR_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - DMA Tx or Rx Arbitration Scheme This bit specifies the arbitration scheme between the Transmit and Receive paths of all channels: The priority between the paths is according to the priority specified in Bits\\[14:12\\]
and the priority weight is specified in the TXPR bit. The Tx path has priority over the Rx path when the TXPR bit is set. Otherwise, the Rx path has priority over the Tx path."]
#[inline(always)]
pub fn da(&self) -> DA_R {
DA_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 11 - Transmit priority When set, this bit indicates that the Tx DMA has higher priority than the Rx DMA during arbitration for the system-side bus."]
#[inline(always)]
pub fn txpr(&self) -> TXPR_R {
TXPR_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bits 12:14 - Priority ratio These bits control the priority ratio in weighted round-robin arbitration between the Rx DMA and Tx DMA. These bits are valid only when the DA bit is reset. The priority ratio is Rx:Tx or Tx:Rx depending on whether the TXPR bit is reset or set."]
#[inline(always)]
pub fn pr(&self) -> PR_R {
PR_R::new(((self.bits >> 12) & 7) as u8)
}
#[doc = "Bits 16:17 - Interrupt Mode This field defines the interrupt mode of the Ethernet peripheral. The behavior of the interrupt signal and of the RI/TI bits in the ETH_DMACSR register changes depending on the INTM value (refer to Table�651: Transfer complete interrupt behavior)."]
#[inline(always)]
pub fn intm(&self) -> INTM_R {
INTM_R::new(((self.bits >> 16) & 3) as u8)
}
}
impl W {
#[doc = "Bit 0 - Software Reset When this bit is set, the MAC and the DMA controller reset the logic and all internal registers of the DMA, MTL, and MAC. This bit is automatically cleared after the reset operation is complete in all clock domains. Before reprogramming any register, a value of zero should be read in this bit. Note: The reset operation is complete only when all resets in all active clock domains are deasserted. Therefore, it is essential that all PHY inputs clocks (applicable for the selected PHY interface) are present for software reset completion. The time to complete the software reset operation depends on the frequency of the slowest active clock."]
#[inline(always)]
#[must_use]
pub fn swr(&mut self) -> SWR_W<DMAMR_SPEC, 0> {
SWR_W::new(self)
}
#[doc = "Bit 1 - DMA Tx or Rx Arbitration Scheme This bit specifies the arbitration scheme between the Transmit and Receive paths of all channels: The priority between the paths is according to the priority specified in Bits\\[14:12\\]
and the priority weight is specified in the TXPR bit. The Tx path has priority over the Rx path when the TXPR bit is set. Otherwise, the Rx path has priority over the Tx path."]
#[inline(always)]
#[must_use]
pub fn da(&mut self) -> DA_W<DMAMR_SPEC, 1> {
DA_W::new(self)
}
#[doc = "Bit 11 - Transmit priority When set, this bit indicates that the Tx DMA has higher priority than the Rx DMA during arbitration for the system-side bus."]
#[inline(always)]
#[must_use]
pub fn txpr(&mut self) -> TXPR_W<DMAMR_SPEC, 11> {
TXPR_W::new(self)
}
#[doc = "Bits 12:14 - Priority ratio These bits control the priority ratio in weighted round-robin arbitration between the Rx DMA and Tx DMA. These bits are valid only when the DA bit is reset. The priority ratio is Rx:Tx or Tx:Rx depending on whether the TXPR bit is reset or set."]
#[inline(always)]
#[must_use]
pub fn pr(&mut self) -> PR_W<DMAMR_SPEC, 12> {
PR_W::new(self)
}
#[doc = "Bits 16:17 - Interrupt Mode This field defines the interrupt mode of the Ethernet peripheral. The behavior of the interrupt signal and of the RI/TI bits in the ETH_DMACSR register changes depending on the INTM value (refer to Table�651: Transfer complete interrupt behavior)."]
#[inline(always)]
#[must_use]
pub fn intm(&mut self) -> INTM_W<DMAMR_SPEC, 16> {
INTM_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "DMA mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmamr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dmamr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DMAMR_SPEC;
impl crate::RegisterSpec for DMAMR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dmamr::R`](R) reader structure"]
impl crate::Readable for DMAMR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dmamr::W`](W) writer structure"]
impl crate::Writable for DMAMR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DMAMR to value 0"]
impl crate::Resettable for DMAMR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::ptr::null_mut;
use bincode;
use flate2;
use libc::c_void;
use bw;
use entity_serialize::{self, deserialize_entity, entity_serializable, EntitySerializable};
use units::{unit_to_id, unit_from_id};
use save::{fread, fwrite, fread_num, fwrite_num, SaveError, LoadError, print_text};
use save::{SaveMapping, LoadMapping};
use send_pointer::SendPtr;
ome2_thread_local! {
BULLETS: RefCell<HashSet<SendPtr<bw::Bullet>>> =
all_bullets(RefCell::new(HashSet::new()));
}
const BULLET_SAVE_MAGIC: u16 = 0xffed;
// 8 megabytes, should be more than enough, both compressed and without.
const BULLET_SAVE_MAX_SIZE: u32 = 0x800000;
impl entity_serialize::SaveEntityPointer for SaveMapping<bw::Bullet> {
type Pointer = bw::Bullet;
fn pointer_to_id(&self, val: *mut bw::Bullet) -> Result<u32, SaveError> {
self.id(val)
}
}
impl entity_serialize::LoadEntityPointer for LoadMapping<bw::Bullet> {
type Pointer = bw::Bullet;
fn id_to_pointer(&self, val: u32) -> Result<*mut bw::Bullet, LoadError> {
self.pointer(val)
}
}
pub unsafe fn create_bullet(
parent: *mut bw::Unit,
bullet_id: u32,
x: u32,
y: u32,
player: u32,
direction: u32,
orig: unsafe extern fn(*mut bw::Unit, u32, u32, u32, u32, u32) -> *mut bw::Bullet,
) -> *mut bw::Bullet {
// Bullet count is only used to limit valkyries, so faking it to be 0 is fine
*bw::bullet_count = 0;
// Could set spread seed so it's not always 0
let bullet = Box::new(bw::Bullet {
..mem::zeroed()
});
let bullet = Box::into_raw(bullet);
*bw::first_free_bullet = bullet;
*bw::last_free_bullet = bullet;
let actual_bullet = orig(parent, bullet_id, x, y, player, direction);
*bw::first_free_bullet = null_mut();
*bw::last_free_bullet = null_mut();
if actual_bullet == null_mut() {
info!(
"Couldn't create bullet {:x} at {:x}.{:x} facing {:x}", bullet_id, x, y, direction
);
let _ = Box::from_raw(bullet);
return null_mut();
} else if actual_bullet != bullet {
error!(
"Created a different bullet from what was expected: {:p} {:p}",
bullet,
actual_bullet
);
}
let mut bullets = all_bullets().borrow_mut();
bullets.insert(bullet.into());
bullet
}
pub unsafe fn delete_bullet(bullet: *mut bw::Bullet, orig: unsafe extern fn(*mut bw::Bullet)) {
if (*bullet).entity.sprite == null_mut() {
// Have to call orig to remove the bullet from active bullet list
*bw::first_free_bullet = null_mut();
*bw::last_free_bullet = null_mut();
orig(bullet);
let _ = Box::from_raw(bullet);
let mut bullets = all_bullets().borrow_mut();
bullets.remove(&bullet.into());
}
}
pub unsafe fn delete_all() {
let mut bullets = all_bullets().borrow_mut();
for bullet in bullets.iter() {
let _ = Box::from_raw(**bullet);
}
bullets.clear();
// Not sure if these are necessary, but doing this won't hurt either
*bw::first_active_bullet = null_mut();
*bw::last_active_bullet = null_mut();
*bw::first_free_bullet = null_mut();
*bw::last_free_bullet = null_mut();
}
#[derive(Serialize, Deserialize)]
struct SaveGlobals {
first_bullet: u32,
last_bullet: u32,
bullet_count: u32,
}
#[derive(Serialize, Deserialize)]
struct BulletSerializable {
entity: EntitySerializable,
weapon_id: u8,
death_timer: u8,
flags: u8,
bounces_remaining: u8,
parent: u16,
previous_bounce_target: u16,
spread_seed: u8,
}
pub unsafe fn save_bullet_chunk(file: *mut c_void) -> u32 {
if let Err(e) = save_bullets(file) {
error!("Couldn't save bullets: {}", e);
print_text(&format!("Unable to save the game: {}", e));
return 0;
}
1
}
unsafe fn save_bullets(file: *mut c_void) -> Result<(), SaveError> {
let data = serialize_bullets()?;
fwrite_num(file, BULLET_SAVE_MAGIC)?;
fwrite_num(file, 1u32)?;
fwrite_num(file, data.len() as u32)?;
fwrite(file, &data)?;
Ok(())
}
unsafe fn serialize_bullets() -> Result<Vec<u8>, SaveError> {
let ptr_to_id_map = bullet_pointer_to_id_map();
let buf = Vec::with_capacity(0x10000);
let mut writer = flate2::write::DeflateEncoder::new(buf, flate2::Compression::Default);
let size_limit = bincode::Bounded(BULLET_SAVE_MAX_SIZE as u64);
let globals = SaveGlobals {
first_bullet: ptr_to_id_map.id(*bw::first_active_bullet)?,
last_bullet: ptr_to_id_map.id(*bw::last_active_bullet)?,
bullet_count: ptr_to_id_map.len() as u32,
};
bincode::serialize_into(&mut writer, &globals, size_limit)?;
let mut bullet = *bw::first_active_bullet;
while bullet != null_mut() {
let serializable = bullet_serializable(bullet, &ptr_to_id_map)?;
bincode::serialize_into(&mut writer, &serializable, size_limit)?;
bullet = (*bullet).entity.next as *mut bw::Bullet;
if writer.total_in() > BULLET_SAVE_MAX_SIZE as u64{
return Err(SaveError::SizeLimit(writer.total_in()));
}
// Could also check total out but it should be lower..
}
Ok(writer.finish()?)
}
unsafe fn bullet_serializable(
bullet: *const bw::Bullet,
mapping: &SaveMapping<bw::Bullet>,
) -> Result<BulletSerializable, SaveError> {
let bw::Bullet {
ref entity,
weapon_id,
death_timer,
flags,
bounces_remaining,
parent,
previous_bounce_target,
spread_seed,
padding6d: _,
} = *bullet;
Ok(BulletSerializable {
entity: entity_serializable(entity, mapping)?,
weapon_id,
death_timer,
flags,
bounces_remaining,
parent: unit_to_id(parent),
previous_bounce_target: unit_to_id(previous_bounce_target),
spread_seed,
})
}
fn deserialize_bullet(
bullet: &BulletSerializable,
mapping: &LoadMapping<bw::Bullet>,
) -> Result<bw::Bullet, LoadError> {
let BulletSerializable {
ref entity,
weapon_id,
death_timer,
flags,
bounces_remaining,
parent,
previous_bounce_target,
spread_seed,
} = *bullet;
Ok(bw::Bullet {
entity: deserialize_entity(entity, mapping)?,
weapon_id,
death_timer,
flags,
bounces_remaining,
parent: unit_from_id(parent)?,
previous_bounce_target: unit_from_id(previous_bounce_target)?,
spread_seed,
padding6d: [0; 3],
})
}
unsafe fn bullet_pointer_to_id_map() -> SaveMapping<bw::Bullet> {
let mut id = 1;
let mut bullet = *bw::first_active_bullet;
let mut ret = HashMap::new();
while bullet != null_mut() {
let old = ret.insert(bullet.into(), id);
assert!(old.is_none());
bullet = (*bullet).entity.next as *mut bw::Bullet;
id += 1;
}
SaveMapping(ret)
}
pub unsafe fn load_bullet_chunk(file: *mut c_void, save_version: u32) -> u32 {
if save_version != 3 {
error!("Unusupported save version: {}", save_version);
return 0;
}
if let Err(e) = load_bullets(file) {
info!("Couldn't load a save: {}", e);
return 0;
}
1
}
unsafe fn load_bullets(file: *mut c_void) -> Result<(), LoadError> {
let magic = fread_num::<u16>(file)?;
if magic != BULLET_SAVE_MAGIC {
return Err(LoadError::WrongMagic(magic));
}
let version = fread_num::<u32>(file)?;
if version != 1 {
return Err(LoadError::Version(version));
}
let size = fread_num::<u32>(file)?;
if size > BULLET_SAVE_MAX_SIZE {
return Err(LoadError::Corrupted(format!("Bullet chunk size {} is too large", size)));
}
let data = fread(file, size)?;
let mut reader = flate2::read::DeflateDecoder::new(&data[..]);
let size_limit = bincode::Bounded(BULLET_SAVE_MAX_SIZE as u64);
let globals: SaveGlobals = bincode::deserialize_from(&mut reader, size_limit)?;
let (mut bullets, mapping) = allocate_bullets(globals.bullet_count);
for bullet in &mut bullets {
let serialized = bincode::deserialize_from(&mut reader, size_limit)?;
**bullet = deserialize_bullet(&serialized, &mapping)?;
if reader.total_out() > BULLET_SAVE_MAX_SIZE as u64 {
return Err(LoadError::SizeLimit)
}
}
let mut bullet_set = all_bullets().borrow_mut();
for bullet in bullets {
bullet_set.insert(Box::into_raw(bullet).into());
}
*bw::first_active_bullet = mapping.pointer(globals.first_bullet)?;
*bw::last_active_bullet = mapping.pointer(globals.last_bullet)?;
Ok(())
}
// Returning the pointer vector isn't really necessary, just simpler. Could also create a
// vector abstraction that allows reading addresses of any Bullet while holding a &mut reference
// to one of them.
fn allocate_bullets(count: u32) -> (Vec<Box<bw::Bullet>>, LoadMapping<bw::Bullet>) {
(0..count).map(|_| {
let mut bullet = Box::new(unsafe { mem::zeroed() });
let pointer: *mut bw::Bullet = &mut *bullet;
(bullet, pointer)
}).unzip()
}
|
#[doc = "Prunes branches of the document tree that contain no documentation"];
export mk_pass;
fn mk_pass() -> pass {
run
}
type ctxt = {
mutable have_docs: bool
};
fn run(
_srv: astsrv::srv,
doc: doc::cratedoc
) -> doc::cratedoc {
let ctxt = {
mutable have_docs: true
};
let fold = fold::fold({
fold_mod: fold_mod,
fold_fn: fold_fn,
fold_const: fold_const,
fold_modlist: fold_modlist,
fold_fnlist: fold_fnlist,
fold_constlist: fold_constlist
with *fold::default_seq_fold(ctxt)
});
fold.fold_crate(fold, doc)
}
fn fold_mod(
fold: fold::fold<ctxt>,
doc: doc::moddoc
) -> doc::moddoc {
let doc = fold::default_seq_fold_mod(fold, doc);
fold.ctxt.have_docs =
doc.brief != none
|| doc.desc != none
|| vec::is_not_empty(*doc.mods)
|| vec::is_not_empty(*doc.fns);
ret doc;
}
fn fold_fn(
fold: fold::fold<ctxt>,
doc: doc::fndoc
) -> doc::fndoc {
let have_arg_docs = false;
let doc = ~{
args: vec::filter_map(doc.args) {|doc|
if option::is_some(doc.desc) {
have_arg_docs = true;
some(doc)
} else {
none
}
},
return: {
ty: if option::is_some(doc.return.desc) {
doc.return.ty
} else {
none
}
with doc.return
}
with *doc
};
fold.ctxt.have_docs =
doc.brief != none
|| doc.desc != none
|| have_arg_docs
|| doc.return.desc != none
|| doc.failure != none;
ret doc;
}
#[test]
fn should_elide_undocumented_arguments() {
let source = "#[doc = \"hey\"] fn a(b: int) { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = attr_pass::mk_pass()(srv, doc);
let doc = run(srv, doc);
assert vec::is_empty(doc.topmod.fns[0].args);
}
#[test]
fn should_not_elide_fns_with_documented_arguments() {
let source = "#[doc(args(a = \"b\"))] fn a(a: int) { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = attr_pass::mk_pass()(srv, doc);
let doc = run(srv, doc);
assert vec::is_not_empty(*doc.topmod.fns);
}
#[test]
fn should_elide_undocumented_return_values() {
let source = "#[doc = \"fonz\"] fn a() -> int { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = tystr_pass::mk_pass()(srv, doc);
let doc = attr_pass::mk_pass()(srv, doc);
let doc = run(srv, doc);
assert doc.topmod.fns[0].return.ty == none;
}
#[test]
fn should_not_elide_fns_with_documented_failure_conditions() {
let source = "#[doc(failure = \"yup\")] fn a() { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = attr_pass::mk_pass()(srv, doc);
let doc = run(srv, doc);
assert vec::is_not_empty(*doc.topmod.fns);
}
fn fold_modlist(
fold: fold::fold<ctxt>,
list: doc::modlist
) -> doc::modlist {
doc::modlist(vec::filter_map(*list) {|doc|
let doc = fold.fold_mod(fold, doc);
if fold.ctxt.have_docs {
some(doc)
} else {
none
}
})
}
#[test]
fn should_elide_undocumented_mods() {
let source = "mod a { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert vec::is_empty(*doc.topmod.mods);
}
#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
let source = "mod a { #[doc = \"b\"] mod b { } }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = attr_pass::mk_pass()(srv, doc);
let doc = run(srv, doc);
assert vec::is_not_empty(*doc.topmod.mods);
}
#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
let source = "mod a { #[doc = \"b\"] fn b() { } }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = attr_pass::mk_pass()(srv, doc);
let doc = run(srv, doc);
assert vec::is_not_empty(*doc.topmod.mods);
}
fn fold_fnlist(
fold: fold::fold<ctxt>,
list: doc::fnlist
) -> doc::fnlist {
doc::fnlist(vec::filter_map(*list) {|doc|
let doc = fold.fold_fn(fold, doc);
if fold.ctxt.have_docs {
some(doc)
} else {
none
}
})
}
#[test]
fn should_elide_undocumented_fns() {
let source = "fn a() { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert vec::is_empty(*doc.topmod.fns);
}
fn fold_const(
fold: fold::fold<ctxt>,
doc: doc::constdoc
) -> doc::constdoc {
let doc = fold::default_seq_fold_const(fold, doc);
fold.ctxt.have_docs =
doc.brief != none
|| doc.desc != none;
ret doc;
}
fn fold_constlist(
fold: fold::fold<ctxt>,
list: doc::constlist
) -> doc::constlist {
doc::constlist(vec::filter_map(*list) {|doc|
let doc = fold.fold_const(fold, doc);
if fold.ctxt.have_docs {
some(doc)
} else {
none
}
})
}
#[test]
fn should_elide_undocumented_consts() {
let source = "const a: bool = true;";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert vec::is_empty(*doc.topmod.consts);
}
|
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::{
state_machine::{Core, Ended, InGame},
Connection,
};
use futures::{future::Either, ready, sink::Sink, stream::Stream};
use rsc2_pb::protocol::{self, Status};
pub struct InGameLoop<'sm, 'b> {
state: Option<InGame<'sm>>,
framed: Pin<&'b mut Connection>,
}
impl<'sm, 'b> InGameLoop<'sm, 'b> {
pub fn new(state: InGame<'sm>, framed: Pin<&'b mut Connection>) -> Self {
Self {
state: Some(state),
framed,
}
}
}
impl<'sm, 'b> Stream for InGameLoop<'sm, 'b> {
type Item = Either<<Connection as Stream>::Item, Ended<'sm>>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.state.is_none() {
return Poll::Ready(None);
}
let resp = ready!(self.framed.as_mut().poll_next(cx));
if let Some(Ok(Status::Ended)) = resp.as_ref().map(|r| r.as_ref().map(|r| r.status())) {
let res = self.state.take().map(|mut state| {
state.core().replace(Core::Ended {});
Either::Right(Ended::from(state))
});
Poll::Ready(res)
} else {
Poll::Ready(resp.map(Either::Left))
}
}
}
impl<'sm, 'b> Sink<protocol::Request> for InGameLoop<'sm, 'b> {
type Error = <Connection as Sink<protocol::Request>>::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::<protocol::Request>::poll_ready(self.framed.as_mut(), cx)
}
fn start_send(mut self: Pin<&mut Self>, item: protocol::Request) -> Result<(), Self::Error> {
Sink::<protocol::Request>::start_send(self.framed.as_mut(), item)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::<protocol::Request>::poll_flush(self.framed.as_mut(), cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::<protocol::Request>::poll_close(self.framed.as_mut(), cx)
}
}
|
//! A module that provides task synchronisation primitives.
#[doc(inline)]
pub use tokio::sync::oneshot;
pub mod mpsc;
|
fn main() {
let (flashes, sync) = solve();
println!("First solution: {}", flashes);
println!("Second solution: {}", sync);
}
fn solve() -> (usize, usize) {
let mut field = input();
let mut flashes = 0;
let mut i = 0;
loop {
i += 1;
// Add one to each octopus
field.apply(|o| {
o.energy += 1;
});
// Do the flashing
let mut changed = true;
while changed {
changed = false;
for row in 0..10 {
for col in 0..10 {
let current = &mut field.0[row][col];
if current.energy > 9 && !current.did_flash {
current.did_flash = true;
changed = true;
if i <= 100 {
flashes += 1;
}
for (r, c) in neighbors(row, col) {
field.0[r][c].energy += 1;
}
}
}
}
}
// Have all octopi flashed?
if field.0.iter().flat_map(|r| r.iter()).all(|o| o.did_flash) {
return (flashes, i);
}
// Reset octopi > 9
field.apply(|o| {
if o.energy > 9 {
o.energy = 0;
o.did_flash = false;
}
});
}
}
fn neighbors(row: usize, col: usize) -> Vec<(usize, usize)> {
let mut neighbors = Vec::new();
let mut rs = vec![row];
let mut cs = vec![col];
if row > 0 {
rs.push(row - 1);
}
if row < 9 {
rs.push(row + 1);
}
if col > 0 {
cs.push(col - 1);
}
if col < 9 {
cs.push(col + 1);
}
for r in rs {
for &c in &cs {
if r == row && c == col {
continue;
}
neighbors.push((r, c));
}
}
neighbors
}
struct Field(Vec<Vec<Octopus>>);
impl Field {
/// Do something with every octopus
fn apply<F>(&mut self, mut op: F)
where
F: FnMut(&mut Octopus),
{
for row in 0..10 {
for col in 0..10 {
op(&mut self.0[row][col])
}
}
}
}
struct Octopus {
energy: u32,
did_flash: bool,
}
fn input() -> Field {
Field(
include_str!("../../input/11.txt")
.lines()
.map(|l| {
l.chars()
.map(|c| c.to_digit(10).unwrap())
.map(|n| Octopus {
energy: n,
did_flash: false,
})
.collect()
})
.collect(),
)
}
|
cfg_if::cfg_if! {
if #[cfg(feature = "sha1")] {
use std::io::Write;
use encoding::hex;
use cryptographer::{sha1, Hash};
fn main() {
let mut h = sha1::new();
h.write(b"His money is twice tainted:")
.expect("failed to consume");
h.write(b" 'taint yours and 'taint mine.")
.expect("failed to consume");
let got = {
let v = h.sum();
hex::encode_to_string(&v[..])
};
let expect = "597f6a540010f94c15d71806a99a2c8710e747bd";
assert_eq!(&got, expect);
}
}else {
fn main() {
panic!("this example has been disabled due to missing feature 'sha1'");
}
}
}
|
extern crate homotopy;
use homotopy::*;
fn main() {
let a = Circle {center: [0.0, 0.0], radius: 1.0};
let b = Lerp(0.0, 10.0);
let c = Square::new(a, b);
assert!(check2(&c, Default::default()));
let d = c.map(|(xy, z)| [xy[0], xy[1], z]);
assert!(check2(&d, Default::default()));
let left = d.left();
assert_eq!(left.hu(0.0), [1.0, 0.0, 0.0]);
assert_eq!(left.hu(0.5), [1.0, 0.0, 5.0]);
assert_eq!(left.hu(1.0), [1.0, 0.0, 10.0]);
let right = d.right();
assert_eq!(right.hu(0.0), [1.0, 0.0, 0.0]);
assert_eq!(right.hu(0.5), [1.0, 0.0, 5.0]);
assert_eq!(right.hu(1.0), [1.0, 0.0, 10.0]);
let top = d.top();
assert_eq!(top.hu(0.0), [1.0, 0.0, 0.0]);
assert_eq!(top.hu(0.5), [-1.0, 0.0, 0.0]);
assert_eq!(top.hu(1.0), [1.0, 0.0, 0.0]);
let bottom = d.bottom();
assert_eq!(bottom.hu(0.0), [1.0, 0.0, 10.0]);
assert_eq!(bottom.hu(0.5), [-1.0, 0.0, 10.0]);
assert_eq!(bottom.hu(1.0), [1.0, 0.0, 10.0]);
let middle = d.top_bottom(0.5);
assert_eq!(middle.hu(0.0), [1.0, 0.0, 5.0]);
assert_eq!(middle.hu(0.5), [-1.0, 0.0, 5.0]);
assert_eq!(middle.hu(1.0), [1.0, 0.0, 5.0]);
}
|
use jsonrpc_core::{MetaIoHandler, Metadata};
use std::sync::mpsc::Sender;
use messages::{EnvelopeSubject, Notification};
use rpc::agent::Rpc as AgentRpc;
use rpc::ping::Rpc as PingRpc;
use rpc::room::Rpc as RoomRpc;
use rpc::subscription::Rpc as SubscriptionRpc;
use rpc::track::Rpc as TrackRpc;
use rpc::webrtc::Rpc as WebrtcRpc;
use DbPool;
mod agent;
mod error;
mod event;
mod ping;
mod room;
mod subscription;
mod track;
mod webrtc;
// TODO: remove Default on new jsonrpc_core version
#[derive(Clone, Default)]
pub struct Meta {
pub subject: EnvelopeSubject,
pub notification_tx: Option<Sender<Notification>>,
pub db_pool: Option<DbPool>,
}
impl Metadata for Meta {}
pub type Server = MetaIoHandler<Meta>;
pub fn build_server() -> Server {
let mut io = MetaIoHandler::default();
let rpc = ping::RpcImpl {};
io.extend_with(rpc.to_delegate());
let rpc = room::RpcImpl {};
io.extend_with(rpc.to_delegate());
let rpc = subscription::RpcImpl {};
io.extend_with(rpc.to_delegate());
let rpc = agent::RpcImpl {};
io.extend_with(rpc.to_delegate());
let rpc = track::RpcImpl {};
io.extend_with(rpc.to_delegate());
let rpc = webrtc::RpcImpl {};
io.extend_with(rpc.to_delegate());
io.add_notification_with_meta("event", event::call);
io
}
|
use tui::layout::{Constraint, Direction, Layout as TUILayout, Rect};
pub struct Layout {
pub help_bar: Rect,
pub formulae_list: Rect,
pub info: Rect,
}
impl Layout {
pub fn new(size: Rect) -> Layout {
let main_chunks = TUILayout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(5), Constraint::Length(3)].as_ref())
.split(size);
let content_chunks = TUILayout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)].as_ref())
.split(main_chunks[0]);
Layout {
help_bar: main_chunks[1],
formulae_list: content_chunks[0],
info: content_chunks[1],
}
}
}
|
use rustberry::effects::http_player::HttpPlayer;
use rustberry::player::PlaybackHandle;
#[tokio::main]
async fn main() -> Result<(), failure::Error> {
let player = HttpPlayer::new().unwrap();
println!("starting...");
let handle = player
.start_playback(
"https://tortoise.silverratio.net/rustberry/TestRecording.mp3",
None,
)
.await
.unwrap();
println!("started...");
std::thread::sleep(std::time::Duration::from_secs(2));
let _ = handle.stop();
std::thread::sleep(std::time::Duration::from_secs(60));
Ok(())
}
|
use juice_sdk_rs::{client, transports, types, Result};
#[tokio::main]
async fn main() -> Result<()> {
let transport = transports::http::Http::new("http://10.1.1.40:7009")?;
let client = client::Client::new(transport, true);
//let number = client.block_number(String::from("sys")).await?;
let block = client
.block_by_number(
String::from("sys"),
types::BlockNumber::Number(types::U64::from(300)),
)
.await?;
println!("{}", serde_json::to_string_pretty(&block).unwrap());
Ok(())
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Blueprint {
#[serde(flatten)]
pub azure_resource_base: AzureResourceBase,
pub properties: BlueprintProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Artifact {
#[serde(flatten)]
pub azure_resource_base: AzureResourceBase,
pub kind: artifact::Kind,
}
pub mod artifact {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kind {
#[serde(rename = "template")]
Template,
#[serde(rename = "roleAssignment")]
RoleAssignment,
#[serde(rename = "policyAssignment")]
PolicyAssignment,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PublishedBlueprint {
#[serde(flatten)]
pub azure_resource_base: AzureResourceBase,
pub properties: PublishedBlueprintProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlueprintList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Blueprint>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PublishedBlueprintList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PublishedBlueprint>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArtifactList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Artifact>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceProviderOperationList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ResourceProviderOperation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceProviderOperation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<resource_provider_operation::Display>,
}
pub mod resource_provider_operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SharedBlueprintProperties {
#[serde(flatten)]
pub blueprint_resource_properties_base: BlueprintResourcePropertiesBase,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<BlueprintStatus>,
#[serde(rename = "targetScope", default, skip_serializing_if = "Option::is_none")]
pub target_scope: Option<shared_blueprint_properties::TargetScope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<ParameterDefinitionCollection>,
#[serde(rename = "resourceGroups", default, skip_serializing_if = "Option::is_none")]
pub resource_groups: Option<ResourceGroupDefinitionCollection>,
}
pub mod shared_blueprint_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TargetScope {
#[serde(rename = "subscription")]
Subscription,
#[serde(rename = "managementGroup")]
ManagementGroup,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlueprintProperties {
#[serde(flatten)]
pub shared_blueprint_properties: SharedBlueprintProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub versions: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layout: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PublishedBlueprintProperties {
#[serde(flatten)]
pub shared_blueprint_properties: SharedBlueprintProperties,
#[serde(rename = "blueprintName", default, skip_serializing_if = "Option::is_none")]
pub blueprint_name: Option<String>,
#[serde(rename = "changeNotes", default, skip_serializing_if = "Option::is_none")]
pub change_notes: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlueprintStatus {
#[serde(flatten)]
pub blueprint_resource_status_base: BlueprintResourceStatusBase,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TemplateArtifactProperties {
#[serde(flatten)]
pub blueprint_resource_properties_base: BlueprintResourcePropertiesBase,
#[serde(flatten)]
pub artifact_properties_base: ArtifactPropertiesBase,
pub template: serde_json::Value,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
pub parameters: ParameterValueCollection,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TemplateArtifact {
#[serde(flatten)]
pub artifact: Artifact,
pub properties: TemplateArtifactProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentArtifactProperties {
#[serde(flatten)]
pub blueprint_resource_properties_base: BlueprintResourcePropertiesBase,
#[serde(flatten)]
pub artifact_properties_base: ArtifactPropertiesBase,
#[serde(rename = "roleDefinitionId")]
pub role_definition_id: String,
#[serde(rename = "principalIds")]
pub principal_ids: serde_json::Value,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentArtifact {
#[serde(flatten)]
pub artifact: Artifact,
pub properties: RoleAssignmentArtifactProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyAssignmentArtifactProperties {
#[serde(flatten)]
pub blueprint_resource_properties_base: BlueprintResourcePropertiesBase,
#[serde(flatten)]
pub artifact_properties_base: ArtifactPropertiesBase,
#[serde(rename = "policyDefinitionId")]
pub policy_definition_id: String,
pub parameters: ParameterValueCollection,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyAssignmentArtifact {
#[serde(flatten)]
pub artifact: Artifact,
pub properties: PolicyAssignmentArtifactProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterValueCollection {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterValueBase {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterValue {
#[serde(flatten)]
pub parameter_value_base: ParameterValueBase,
pub value: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretReferenceParameterValue {
#[serde(flatten)]
pub parameter_value_base: ParameterValueBase,
pub reference: SecretValueReference,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SecretValueReference {
#[serde(rename = "keyVault")]
pub key_vault: KeyVaultReference,
#[serde(rename = "secretName")]
pub secret_name: String,
#[serde(rename = "secretVersion", default, skip_serializing_if = "Option::is_none")]
pub secret_version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultReference {
pub id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterDefinitionCollection {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterDefinition {
#[serde(rename = "type")]
pub type_: parameter_definition::Type,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<ParameterDefinitionMetadata>,
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<serde_json::Value>,
#[serde(rename = "allowedValues", default, skip_serializing_if = "Vec::is_empty")]
pub allowed_values: Vec<serde_json::Value>,
}
pub mod parameter_definition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "string")]
String,
#[serde(rename = "array")]
Array,
#[serde(rename = "bool")]
Bool,
#[serde(rename = "int")]
Int,
#[serde(rename = "object")]
Object,
#[serde(rename = "secureObject")]
SecureObject,
#[serde(rename = "secureString")]
SecureString,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceGroupDefinitionCollection {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceGroupDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<ParameterDefinitionMetadata>,
#[serde(rename = "dependsOn", default, skip_serializing_if = "Vec::is_empty")]
pub depends_on: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterDefinitionMetadata {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "strongType", default, skip_serializing_if = "Option::is_none")]
pub strong_type: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceGroupValueCollection {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceGroupValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureResourceBase {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArtifactPropertiesBase {
#[serde(rename = "dependsOn", default, skip_serializing_if = "Vec::is_empty")]
pub depends_on: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlueprintResourcePropertiesBase {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlueprintResourceStatusBase {
#[serde(rename = "timeCreated", default, skip_serializing_if = "Option::is_none")]
pub time_created: Option<String>,
#[serde(rename = "lastModified", default, skip_serializing_if = "Option::is_none")]
pub last_modified: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Assignment {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
pub identity: ManagedServiceIdentity,
pub properties: AssignmentProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AssignmentList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Assignment>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedServiceIdentity {
#[serde(rename = "type")]
pub type_: managed_service_identity::Type,
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
pub mod managed_service_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
None,
SystemAssigned,
UserAssigned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AssignmentStatus {
#[serde(flatten)]
pub blueprint_resource_status_base: BlueprintResourceStatusBase,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AssignmentLockSettings {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<assignment_lock_settings::Mode>,
}
pub mod assignment_lock_settings {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Mode {
None,
AllResources,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AssignmentProperties {
#[serde(flatten)]
pub blueprint_resource_properties_base: BlueprintResourcePropertiesBase,
#[serde(rename = "blueprintId", default, skip_serializing_if = "Option::is_none")]
pub blueprint_id: Option<String>,
pub parameters: ParameterValueCollection,
#[serde(rename = "resourceGroups")]
pub resource_groups: ResourceGroupValueCollection,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<AssignmentStatus>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub locks: Option<AssignmentLockSettings>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<assignment_properties::ProvisioningState>,
}
pub mod assignment_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
#[serde(rename = "creating")]
Creating,
#[serde(rename = "validating")]
Validating,
#[serde(rename = "waiting")]
Waiting,
#[serde(rename = "deploying")]
Deploying,
#[serde(rename = "cancelling")]
Cancelling,
#[serde(rename = "locking")]
Locking,
#[serde(rename = "succeeded")]
Succeeded,
#[serde(rename = "failed")]
Failed,
#[serde(rename = "canceled")]
Canceled,
#[serde(rename = "deleting")]
Deleting,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub azure_resource_base: AzureResourceBase,
pub location: String,
}
|
use super::*;
use add_generator::*;
use bitop_generator::*;
use mathic::*;
impl<'a> JIT<'a> {
pub fn emit_op_bitand(&mut self, op: &Ins) {
if let Ins::BitAnd(dest, op1, op2) = op {
let left_reg = T1;
let right_reg = T2;
let result_reg = T0;
let scratch_gpr = T3;
let mut gen = BitAndGenerator {
scratch: scratch_gpr,
left: left_reg,
right: right_reg,
result: result_reg,
slow_path_jump_list: vec![],
};
self.emit_get_virtual_register(*op1, left_reg);
self.emit_get_virtual_register(*op2, right_reg);
gen.generate_fast_path(self);
self.emit_put_virtual_register(*dest, result_reg, scratch_gpr);
for j in gen.slow_path_jump_list {
self.add_slow_case(j);
}
}
}
pub fn emit_op_bitor(&mut self, op: &Ins) {
if let Ins::BitOr(dest, op1, op2) = op {
let left_reg = T1;
let right_reg = T2;
let result_reg = T0;
let scratch_gpr = T3;
let mut gen = BitOrGenerator {
left: left_reg,
right: right_reg,
result: result_reg,
slow_path_jump_list: vec![],
};
self.emit_get_virtual_register(*op1, left_reg);
self.emit_get_virtual_register(*op2, right_reg);
gen.generate_fast_path(self);
self.emit_put_virtual_register(*dest, result_reg, scratch_gpr);
for j in gen.slow_path_jump_list {
self.add_slow_case(j);
}
}
}
pub fn emit_op_bitxor(&mut self, op: &Ins) {
if let Ins::BitOr(dest, op1, op2) = op {
let left_reg = T1;
let right_reg = T2;
let result_reg = T0;
let scratch_gpr = T3;
let mut gen = BitXorGenerator {
left: left_reg,
right: right_reg,
result: result_reg,
slow_path_jump_list: vec![],
};
self.emit_get_virtual_register(*op1, left_reg);
self.emit_get_virtual_register(*op2, right_reg);
gen.generate_fast_path(self);
self.emit_put_virtual_register(*dest, result_reg, scratch_gpr);
for j in gen.slow_path_jump_list {
self.add_slow_case(j);
}
}
}
pub fn emit_op_jless(&mut self, op: &Ins) {
if let Ins::JLess(op1, op2, target) = op {
self.emit_compare_and_jump(*op1, *op2, *target as _, RelationalCondition::LessThan);
}
}
pub fn emit_op_jlesseq(&mut self, op: &Ins) {
if let Ins::JLessEq(op1, op2, target) = op {
self.emit_compare_and_jump(
*op1,
*op2,
*target as _,
RelationalCondition::LessThanOrEqual,
);
}
}
pub fn emit_op_jgreater(&mut self, op: &Ins) {
if let Ins::JGreater(op1, op2, target) = op {
self.emit_compare_and_jump(*op1, *op2, *target as _, RelationalCondition::GreaterThan);
}
}
pub fn emit_op_jgreatereq(&mut self, op: &Ins) {
if let Ins::JGreaterEq(op1, op2, target) = op {
self.emit_compare_and_jump(
*op1,
*op2,
*target as _,
RelationalCondition::GreaterThanOrEqual,
);
}
}
pub fn emit_op_jnless(&mut self, op: &Ins) {
if let Ins::JNLess(op1, op2, target) = op {
self.emit_compare_and_jump(*op1, *op2, *target as _, RelationalCondition::GreaterThan);
}
}
pub fn emit_op_jnlesseq(&mut self, op: &Ins) {
if let Ins::JNLessEq(op1, op2, target) = op {
self.emit_compare_and_jump(
*op1,
*op2,
*target as _,
RelationalCondition::GreaterThanOrEqual,
);
}
}
pub fn emit_op_jngreater(&mut self, op: &Ins) {
if let Ins::JNGreater(op1, op2, target) = op {
self.emit_compare_and_jump(*op1, *op2, *target as _, RelationalCondition::LessThan);
}
}
pub fn emit_op_jngreatereq(&mut self, op: &Ins) {
if let Ins::JNGreaterEq(op1, op2, target) = op {
self.emit_compare_and_jump(
*op1,
*op2,
*target as _,
RelationalCondition::LessThanOrEqual,
);
}
}
pub fn emit_slow_op_jless(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JLess(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
0,
FpCondition::LessThanAndOrdered,
operations::operation_compare_less as *const _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jlesseq(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JLessEq(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
1,
FpCondition::LessThanOrEqualAndOrdered,
operations::operation_compare_lesseq as *const _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jgreater(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JGreater(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
1,
FpCondition::GreaterThanAndOrdered,
operations::operation_compare_greater as *const _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jgreatereq(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JGreaterEq(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
1,
FpCondition::GreaterThanOrEqualAndOrdered,
operations::operation_compare_greatereq as *const _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jnless(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JNLess(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
1,
FpCondition::GreaterThanOrUnordered,
operations::operation_compare_greater as _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jnlesseq(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JNLessEq(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
1,
FpCondition::GreaterThanOrEqualOrUnordered,
operations::operation_compare_greatereq as _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jngreater(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JNGreater(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
1,
FpCondition::LessThanOrUnordered,
operations::operation_compare_less as _,
false,
slow_cases,
);
}
}
pub fn emit_slow_op_jngreatereq(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
if let Ins::JNGreaterEq(op1, op2, target) = op {
self.emit_compare_and_jump_slow(
*op1,
*op2,
*target as _,
0,
FpCondition::LessThanOrEqualOrUnordered,
operations::operation_compare_lesseq as _,
false,
slow_cases,
);
}
}
pub fn emit_op_div(&mut self, op: &Ins) {
if let Ins::Div(dest, op1, op2) = op {
let left = T0;
let right = T1;
let result = left;
let scratch = T2;
let scratch_fp = FT2;
self.emit_get_virtual_register(*op1, left);
self.emit_get_virtual_register(*op2, right);
let mut gen = div_generator::DivGenerator::new(
result, left, right, FT0, FT1, scratch, scratch_fp,
);
gen.generate_fast_path(self);
if gen.did_emit_fast_path {
gen.end_jump_list
.iter()
.for_each(|item| item.link(&mut self.masm));
self.emit_put_virtual_register(*dest, result, scratch);
self.add_slow_cases(&gen.slow_path_jump_list);
}
}
}
pub fn emit_op_add(&mut self, op: &Ins) {
match op {
Ins::Add(dest, src1, src2) => {
let meta = self.code_block.metadata(self.bytecode_index as _);
let math_ic = self.code_block.add_jit_addic(&meta.arith_profile);
self.ins_to_mathic
.insert(op as *const Ins, math_ic as *mut MathIC<_> as *mut u8);
self.emit_mathic_fast_bin(
math_ic,
op,
*src1,
*src2,
*dest,
0 as *mut _,
operations::operation_value_add as *const u8,
);
}
_ => op_unreachable!(),
}
}
pub fn emit_slow_op_add(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
self.link_all_slow_cases(slow_cases);
match op {
Ins::Add(dest, src1, src2) => {
let ic = *self.ins_to_mathic.get(&(op as *const Ins)).unwrap();
let math_ic = unsafe { &mut *(ic as *mut MathIC<AddGenerator>) };
self.emit_mathic_slow_bin(
math_ic,
op,
*src1,
*src2,
*dest,
0xdead as *const _,
operations::operation_value_add_optimize as *const _,
);
}
_ => op_unreachable!(),
}
}
pub fn emit_op_sub(&mut self, op: &Ins) {
match op {
Ins::Sub(dest, src1, src2) => {
let meta = self.code_block.metadata(self.bytecode_index as _);
let math_ic = self.code_block.add_jit_subic(&meta.arith_profile);
self.ins_to_mathic
.insert(op as *const Ins, math_ic as *mut MathIC<_> as *mut u8);
self.emit_mathic_fast_bin(
math_ic,
op,
*src1,
*src2,
*dest,
0 as *mut _,
operations::operation_value_sub as *const u8,
);
}
_ => op_unreachable!(),
}
}
pub fn emit_slow_op_sub(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
self.link_all_slow_cases(slow_cases);
match op {
Ins::Sub(dest, src1, src2) => {
let ic = *self.ins_to_mathic.get(&(op as *const Ins)).unwrap();
let math_ic = unsafe { &mut *(ic as *mut MathIC<sub_generator::SubGenerator>) };
self.emit_mathic_slow_bin(
math_ic,
op,
*src1,
*src2,
*dest,
0xdead as *const _,
operations::operation_value_sub_optimize as *const _,
);
}
_ => op_unreachable!(),
}
}
pub fn emit_op_mul(&mut self, op: &Ins) {
match op {
Ins::Mul(dest, src1, src2) => {
let meta = self.code_block.metadata(self.bytecode_index as _);
let math_ic = self.code_block.add_jit_mulic(&meta.arith_profile);
self.ins_to_mathic
.insert(op as *const Ins, math_ic as *mut MathIC<_> as *mut u8);
self.emit_mathic_fast_bin(
math_ic,
op,
*src1,
*src2,
*dest,
0 as *mut _,
operations::operation_value_mul as *const u8,
);
}
_ => op_unreachable!(),
}
}
pub fn emit_slow_op_mul(
&mut self,
op: &Ins,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
self.link_all_slow_cases(slow_cases);
match op {
Ins::Mul(dest, src1, src2) => {
let ic = *self.ins_to_mathic.get(&(op as *const Ins)).unwrap();
let math_ic = unsafe { &mut *(ic as *mut MathIC<mul_generator::MulGenerator>) };
self.emit_mathic_slow_bin(
math_ic,
op,
*src1,
*src2,
*dest,
0xdead as *const _,
operations::operation_value_mul_optimize as *const _,
);
}
_ => op_unreachable!(),
}
}
pub fn emit_mathic_slow_bin<GEN: MathICGenerator + BinaryMathICGenerator>(
&mut self,
math_ic: &mut MathIC<GEN>,
ins: &Ins,
src1: virtual_register::VirtualRegister,
src2: virtual_register::VirtualRegister,
dest: virtual_register::VirtualRegister,
_profiled_fn: *const u8, // TODO: Type info
repatch_fn: *const u8,
) {
log!("[JIT Arithmetic] Emit slow MathIC case");
let label = self.masm.label();
self.ins_to_mathic_state
.get_mut(&(ins as *const Ins))
.map(|item| {
item.slow_path_start = label;
});
let left_reg = T1;
let right_reg = T2;
let result_reg = T0;
let scratch_gpr = T3;
let scratch_fpr = FT2;
let generator = GEN::new(
result_reg,
left_reg,
right_reg,
FT0,
FT1,
scratch_gpr,
scratch_fpr,
);
math_ic.generator = Some(generator);
self.emit_get_virtual_register(src1, left_reg);
self.emit_get_virtual_register(src2, right_reg);
let slow_path_call = {
self.masm.prepare_call_with_arg_count(4);
self.masm.pass_reg_as_arg(right_reg, 2);
self.masm.pass_reg_as_arg(left_reg, 1);
self.masm.pass_ptr_as_arg(math_ic as *mut _ as usize, 3);
self.masm
.pass_ptr_as_arg(crate::get_vm() as *mut _ as usize, 0); // TODO: Put VM pointer as first argument
self.update_top_frame();
let call = self.masm.call_ptr_repatch_argc(repatch_fn, 3);
self.masm.move_rr(RET0, result_reg);
call
};
self.ins_to_mathic_state
.get_mut(&(ins as *const Ins))
.map(|item| {
item.slow_path_call = slow_path_call;
});
self.emit_put_virtual_register(dest, result_reg, scratch_gpr);
let state = self
.ins_to_mathic_state
.get_mut(&(ins as *const Ins))
.unwrap() as *mut MathICGenerationState;
let ic = *self.ins_to_mathic.get(&(ins as *const Ins)).unwrap();
self.masm.add_link_task(Box::new(move |link_buffer| {
let state = unsafe { &mut *state };
let math_ic = unsafe { &mut *(ic as *mut MathIC<GEN>) };
math_ic.finalize_inline_code(state, link_buffer);
}));
}
pub fn emit_mathic_fast_bin<GEN: MathICGenerator + BinaryMathICGenerator>(
&mut self,
math_ic: &mut MathIC<GEN>,
ins: &Ins,
src1: virtual_register::VirtualRegister,
src2: virtual_register::VirtualRegister,
dest: virtual_register::VirtualRegister,
_profiled_fn: *const u8, // TODO: Type info
non_profiled_fn: *const u8,
) {
log!("[JIT Arithmetic] Emit fast MathIC case");
let left_reg = T1;
let right_reg = T2;
let result_reg = T0;
let scratch_gpr = T3;
let scratch_fpr = FT2;
let generator = GEN::new(
result_reg,
left_reg,
right_reg,
FT0,
FT1,
scratch_gpr,
scratch_fpr,
);
math_ic.generator = Some(generator);
self.emit_get_virtual_register(src1, left_reg);
self.emit_get_virtual_register(src2, right_reg);
self.ins_to_mathic_state
.insert(ins, MathICGenerationState::default());
let state = self
.ins_to_mathic_state
.get_mut(&(ins as *const Ins))
.unwrap() as *mut MathICGenerationState;
let generated_inline = math_ic.generate_inline(self, unsafe { &mut *state }, true);
if !generated_inline {
// cannot generate inline code based on type info, invoke `profiled_fn` if profiling is enabled or `non_profiled_fn` if disabled.
self.masm.prepare_call_with_arg_count(3);
self.masm.pass_reg_as_arg(right_reg, 2);
self.masm.pass_reg_as_arg(left_reg, 1);
self.masm
.pass_ptr_as_arg(crate::get_vm() as *mut _ as usize, 0); // TODO: Put VM pointer as first argument
self.update_top_frame();
self.masm.call_ptr(non_profiled_fn);
self.masm.move_rr(RET0, result_reg);
} else {
// inline code generated, now we can generate slow path at end of the function.
for j in unsafe { (&*state).slow_path_jumps.jumps.iter() } {
self.add_slow_case(*j);
}
}
self.emit_put_virtual_register(dest, result_reg, scratch_gpr);
}
pub fn emit_compare_and_jump(
&mut self,
op1: virtual_register::VirtualRegister,
op2: virtual_register::VirtualRegister,
target: u32,
cond: RelationalCondition,
) {
self.emit_get_virtual_registers(op1, op2, T0, T1);
let br = self.branch_if_not_int32(T0, true);
self.add_slow_case(br);
let br = self.branch_if_not_int32(T1, true);
self.add_slow_case(br);
let j = self.masm.branch32(cond, T0, T1);
self.add_jump(j, target as _);
}
pub fn emit_compare(
&mut self,
op1: virtual_register::VirtualRegister,
op2: virtual_register::VirtualRegister,
cond: RelationalCondition,
dest: virtual_register::VirtualRegister,
) {
self.emit_get_virtual_registers(op1, op2, T0, T1);
let br = self.branch_if_not_int32(T0, true);
self.add_slow_case(br);
let br = self.branch_if_not_int32(T1, true);
self.add_slow_case(br);
self.masm.compare32(cond, T0, T1, T0);
self.box_boolean(T0, T0);
self.emit_put_virtual_register(dest, T0, T1);
}
pub fn emit_compare_slow(
&mut self,
_op1: virtual_register::VirtualRegister,
_op2: virtual_register::VirtualRegister,
dest: virtual_register::VirtualRegister,
double_cond: FpCondition,
operation: *const u8,
invert: bool,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
self.link_all_slow_cases(slow_cases); // lhs is not int
let fail1 = self.branch_if_not_number(T0, true);
let fail2 = self.branch_if_not_number(T1, true);
let fail3 = self.branch_if_int32(T1, true);
self.masm.add64(NUMBER_TAG_REGISTER, T0, T0);
self.masm.add64(NUMBER_TAG_REGISTER, T1, T1);
self.masm.move_gp_to_fp(T0, FT0);
self.masm.move_gp_to_fp(T1, FT1);
let j = self.masm.branch_double(double_cond, FT0, FT1);
self.emit_jump_slow_to_hot(j, 0);
let j = self.masm.jump();
self.emit_jump_slow_to_hot(j, 0);
fail1.link(&mut self.masm);
fail2.link(&mut self.masm);
fail3.link(&mut self.masm);
self.link_all_slow_cases(slow_cases);
self.masm.prepare_call_with_arg_count(3);
self.masm.pass_reg_as_arg(T0, 1);
self.masm.pass_reg_as_arg(T1, 2);
self.masm
.pass_ptr_as_arg(crate::get_vm() as *const _ as _, 0);
self.masm.call_ptr_argc(operation, 3);
let c = if invert {
ResultCondition::Zero
} else {
ResultCondition::NonZero
};
self.masm.test32(c, RET0, RET0, RET0);
self.box_boolean(RET0, RET0);
self.emit_put_virtual_register(dest, RET0, RET1);
//let j = self.masm.branch32_test(c, RET0, RET0);
}
pub fn emit_compare_and_jump_slow(
&mut self,
_op1: virtual_register::VirtualRegister,
_op2: virtual_register::VirtualRegister,
target: u32,
_ins_size: i32,
double_cond: FpCondition,
operation: *const u8,
invert: bool,
slow_cases: &mut std::iter::Peekable<std::slice::Iter<'_, SlowCaseEntry>>,
) {
self.link_all_slow_cases(slow_cases); // lhs is not int
let fail1 = self.branch_if_not_number(T0, true);
let fail2 = self.branch_if_not_number(T1, true);
let fail3 = self.branch_if_int32(T1, true);
self.masm.add64(NUMBER_TAG_REGISTER, T0, T0);
self.masm.add64(NUMBER_TAG_REGISTER, T1, T1);
self.masm.move_gp_to_fp(T0, FT0);
self.masm.move_gp_to_fp(T1, FT1);
let j = self.masm.branch_double(double_cond, FT0, FT1);
self.emit_jump_slow_to_hot(j, target as _);
let j = self.masm.jump();
self.emit_jump_slow_to_hot(j, 1);
fail1.link(&mut self.masm);
fail2.link(&mut self.masm);
fail3.link(&mut self.masm);
self.link_all_slow_cases(slow_cases);
self.masm.prepare_call_with_arg_count(3);
self.masm.pass_reg_as_arg(T0, 1);
self.masm.pass_reg_as_arg(T1, 2);
self.masm
.pass_ptr_as_arg(crate::get_vm() as *const _ as _, 0);
self.masm.call_ptr_argc(operation, 3);
let c = if invert {
ResultCondition::Zero
} else {
ResultCondition::NonZero
};
let j = self.masm.branch32_test(c, RET0, RET0);
self.emit_jump_slow_to_hot(j, target as _);
}
}
|
use uuid::Uuid;
#[derive(juniper::GraphQLInputObject)]
pub struct NewUser {
pub username: String,
pub password: String,
pub email: String,
}
#[derive(juniper::GraphQLObject)]
pub struct User {
pub uuid: Uuid,
pub first_name: String,
pub last_name: String,
pub username: String,
pub email: String,
}
|
// -------------------------------------------------------------------------------//
// Cryptopals, Set 2, Challenge 11: https://cryptopals.com/sets/2/challenges/11
// Impl by Frodo45127
// -------------------------------------------------------------------------------//
use crate::utils::*;
const DATA: &[u8; 164] = b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
pub fn challenge() {
// So, we're not told any specific data about what should we encrypt... so we just encrypt the same letter again and again.
// This will generate similar blocks when ECB encryption is used, allowing us to identify them.
let (result, cyphers) = encrypt_aes_128_ecb_and_cbc(DATA, );
let (ok, err) = encryption_oracle(&result, &cyphers);
println!("Results Ok: {}", ok);
println!("Results Err: {}", err);
// This can easely fail, so we are ok with at least 50% success.
assert!(ok > err);
println!("Challenge passed!!!");
}
|
/*
---New Cashier No Space or Shift---
Some new cashiers started to work at your restaurant.
They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
All the orders they create look something like this:
"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
Their preference is to get the orders as a nice clean string with spaces and capitals like so:
"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"
The kitchen staff expect the items to be in the same order as they appear in the menu.
The menu items are fairly simple, there is no overlap in the names of the items:
1. Burger
2. Fries
3. Chicken
4. Pizza
5. Sandwich
6. Onionrings
7. Milkshake
8. Coke
*/
fn main() {
println!("{}", get_order("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
.to_string()));
}
fn get_order(input: String) -> String {
let items: Vec<&str> = vec!["Burger ", "Fries ", "Chicken ", "Pizza ", "Sandwich ",
"Onionrings ", "Milkshake ", "Coke "];
let mut return_string:String = String::new();
for item in items {
for _ in 0..input.matches(&item.to_lowercase().trim_end()).count() {
return_string.push_str(item);
}
}
return_string.trim_end().to_string()
/*let master_vec:Vec<(String, String)> = [("burger", "Burger "), ("fries", "Fries "),
("chicken", "Chicken "), ("pizza", "Pizza "), ("sandwich", "Sandwich "),
("onionrings", "Onionrings "), ("milkshake", "Milkshake "), ("coke", "Coke ")]
.iter()
.map(|&p| (p.0.to_string(), p.1.to_string()))
.collect();
let mut return_string:String = String::new();
let mut input_copy:String = input;
for t in &master_vec {
let mut find_elements = input_copy.find(&t.0);
while find_elements.is_some() {
return_string.push_str(&t.1);
input_copy = input_copy.replacen(&t.0, "", 1);
find_elements = input_copy.find(&t.0);
}
}
return_string.trim_end().to_string()*/
}
|
use once_cell::sync::Lazy;
use parking_lot::{Mutex, MutexGuard};
use std::sync::Arc;
#[derive(Clone)]
pub struct Atom<T> {
value: Arc<Mutex<T>>,
subscribers: Arc<Mutex<Vec<Subscriber>>>,
}
impl<T> Atom<T> {
pub fn new(initial: T) -> Self {
Self {
value: Arc::new(Mutex::new(initial)),
subscribers: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn get(&self) -> MutexGuard<'_, T> {
let mut current_reaction = CURRENT_REACTION.lock();
if let Some(current_reaction) = &mut *current_reaction {
current_reaction.sources.push(self.subscribers.clone());
}
self.value.lock()
}
pub fn set(&self, value: T) {
*self.value.lock() = value;
for subscriber in &*self.subscribers.lock() {
subscriber.lock()();
}
}
}
type Subscriber = Arc<Mutex<dyn Fn() + Send>>;
pub fn react(f: impl Fn() + Send + 'static) {
let mut current_reaction = CURRENT_REACTION.lock();
assert!(current_reaction.is_none());
*current_reaction = Some(Reaction::new());
drop(current_reaction);
f();
let mut current_reaction = CURRENT_REACTION.lock();
let reaction = current_reaction.take().unwrap();
let sources = reaction.sources.clone();
drop(current_reaction);
let f = Arc::new(Mutex::new(f));
for source in sources {
source.lock().push(f.clone());
}
}
struct Reaction {
sources: Vec<Arc<Mutex<Vec<Subscriber>>>>,
}
impl Reaction {
pub fn new() -> Self {
Reaction {
sources: Vec::new(),
}
}
}
static CURRENT_REACTION: Lazy<Mutex<Option<Reaction>>> = Lazy::new(|| Mutex::new(None));
|
use crate::access_control;
use fund::{
accounts::{
fund::{Fund, FundType},
vault::TokenVault,
},
error::{FundError, FundErrorCode},
};
use serum_common::pack::Pack;
use solana_program::{
account_info::{next_account_info, AccountInfo},
msg, program,
pubkey::Pubkey,
};
use spl_token::instruction;
use std::convert::Into;
pub fn handler(
program_id: &Pubkey,
accounts: &[AccountInfo],
amount: u64,
) -> Result<(), FundError> {
msg!("Handler: deposit");
let acc_infos = &mut accounts.iter();
let vault_acc_info = next_account_info(acc_infos)?;
let depositor_acc_info = next_account_info(acc_infos)?;
let depositor_authority_acc_info = next_account_info(acc_infos)?;
let fund_acc_info = next_account_info(acc_infos)?;
let vault_authority_acc_info = next_account_info(acc_infos)?;
let token_program_acc_info = next_account_info(acc_infos)?;
let nft_mint_acc_info = acc_infos.next(); // optional
let nft_token_acc_info = acc_infos.next(); //optional
let whitelist_acc_info = acc_infos.next(); // optional
access_control(AccessControlRequest {
program_id,
amount,
fund_acc_info,
depositor_acc_info,
depositor_authority_acc_info,
vault_acc_info,
vault_authority_acc_info,
nft_mint_acc_info,
nft_token_acc_info,
whitelist_acc_info,
})?;
Fund::unpack_mut(
&mut fund_acc_info.try_borrow_mut_data()?,
&mut |fund_acc: &mut Fund| {
state_transistion(StateTransistionRequest {
accounts,
fund_acc,
fund_acc_info,
depositor_authority_acc_info,
depositor_acc_info,
vault_acc_info,
vault_authority_acc_info,
token_program_acc_info,
nft_mint_acc_info,
nft_token_acc_info,
amount,
})
.map_err(Into::into)
},
)?;
Ok(())
}
fn access_control(req: AccessControlRequest) -> Result<(), FundError> {
let AccessControlRequest {
program_id,
amount,
fund_acc_info,
depositor_acc_info,
depositor_authority_acc_info,
vault_acc_info,
vault_authority_acc_info,
nft_mint_acc_info,
nft_token_acc_info,
whitelist_acc_info,
} = req;
if !depositor_authority_acc_info.is_signer {
return Err(FundErrorCode::Unauthorized.into());
}
{
// let rent = access_control::rent(rent_acc_info)?;
let fund = access_control::fund(fund_acc_info, program_id)?;
let _ = access_control::vault_join(
vault_acc_info,
vault_authority_acc_info,
fund_acc_info,
program_id,
)?;
let _ = access_control::check_balance(fund_acc_info, amount)?;
let _ = access_control::fund_open(fund_acc_info, program_id)?;
// check if the despoitor is part of the whitelist.
if fund.fund_type.eq(&FundType::Raise { private: true })
|| fund.fund_type.eq(&FundType::Raise { private: false })
{
let _ = access_control::check_nft(
&fund,
nft_mint_acc_info
.ok_or(FundErrorCode::NFTMintMissing)
.unwrap(),
nft_token_acc_info
.ok_or(FundErrorCode::NFTTokenAccountMissing)
.unwrap(),
)?;
}
if fund.fund_type.eq(&FundType::Raise { private: true }) {
let _ = access_control::check_depositor(
program_id,
whitelist_acc_info
.ok_or(FundErrorCode::NFTTokenAccountMissing)
.unwrap()
.clone(),
&fund,
depositor_acc_info,
)?;
}
}
msg!("access control deposit success");
Ok(())
}
fn state_transistion(req: StateTransistionRequest) -> Result<(), FundError> {
let StateTransistionRequest {
accounts,
fund_acc,
fund_acc_info,
depositor_acc_info,
vault_acc_info,
vault_authority_acc_info,
depositor_authority_acc_info,
token_program_acc_info,
nft_mint_acc_info,
nft_token_acc_info,
amount,
} = req;
{
if fund_acc.fund_type.eq(&FundType::Raise { private: false })
|| fund_acc.fund_type.eq(&FundType::Raise { private: true })
{
msg!("invoke SPL token mint");
let mint_to_instr = instruction::mint_to(
&spl_token::ID,
nft_token_acc_info.unwrap().key,
nft_mint_acc_info.unwrap().key,
vault_authority_acc_info.key,
&[],
amount,
)?;
let signer_seeds = TokenVault::signer_seeds(fund_acc_info.key, &fund_acc.nonce);
program::invoke_signed(&mint_to_instr, &accounts[..], &[&signer_seeds])?;
}
}
fund_acc.add(amount);
// Send tokens from depositor to fund account.
// Now transfer SPL funds from the depositor, to the
// program-controlled account.
{
msg!("invoke SPL token transfer");
let deposit_instruction = instruction::transfer(
&spl_token::ID,
depositor_acc_info.key,
vault_acc_info.key,
depositor_authority_acc_info.key,
&[],
amount,
)?;
program::invoke_signed(
&deposit_instruction,
&[
depositor_acc_info.clone(),
depositor_authority_acc_info.clone(),
vault_acc_info.clone(),
token_program_acc_info.clone(),
],
&[],
)?;
}
msg!("state transition deposit success");
Ok(())
}
struct AccessControlRequest<'a, 'b> {
program_id: &'a Pubkey,
amount: u64,
fund_acc_info: &'a AccountInfo<'b>,
depositor_acc_info: &'a AccountInfo<'b>,
depositor_authority_acc_info: &'a AccountInfo<'b>,
vault_acc_info: &'a AccountInfo<'b>,
vault_authority_acc_info: &'a AccountInfo<'b>,
nft_mint_acc_info: Option<&'a AccountInfo<'b>>,
nft_token_acc_info: Option<&'a AccountInfo<'b>>,
whitelist_acc_info: Option<&'a AccountInfo<'b>>,
}
struct StateTransistionRequest<'a, 'b, 'c> {
accounts: &'a [AccountInfo<'b>],
fund_acc: &'c mut Fund,
fund_acc_info: &'a AccountInfo<'b>,
depositor_acc_info: &'a AccountInfo<'b>,
depositor_authority_acc_info: &'a AccountInfo<'b>,
vault_acc_info: &'a AccountInfo<'b>,
vault_authority_acc_info: &'a AccountInfo<'b>,
token_program_acc_info: &'a AccountInfo<'b>,
nft_token_acc_info: Option<&'a AccountInfo<'b>>,
nft_mint_acc_info: Option<&'a AccountInfo<'b>>,
amount: u64,
}
|
use crate::PopReceipt;
use azure_core::headers::{utc_date_from_rfc2822, CommonStorageResponseHeaders};
use azure_storage::core::xml::read_xml;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use http::response::Response;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct GetMessagesResponse {
pub common_storage_response_headers: CommonStorageResponseHeaders,
pub messages: Vec<Message>,
}
#[derive(Debug, Clone)]
pub struct Message {
pub pop_receipt: PopReceipt,
pub insertion_time: DateTime<Utc>,
pub expiration_time: DateTime<Utc>,
pub time_next_visible: DateTime<Utc>,
pub dequeue_count: u64,
pub message_text: String,
}
impl From<Message> for PopReceipt {
fn from(message: Message) -> Self {
message.pop_receipt
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MessageInternal {
#[serde(rename = "MessageId")]
pub message_id: String,
#[serde(rename = "InsertionTime")]
pub insertion_time: String,
#[serde(rename = "ExpirationTime")]
pub expiration_time: String,
#[serde(rename = "PopReceipt")]
pub pop_receipt: String,
#[serde(rename = "TimeNextVisible")]
pub time_next_visible: String,
#[serde(rename = "DequeueCount")]
pub dequeue_count: u64,
#[serde(rename = "MessageText")]
pub message_text: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MessagesInternal {
#[serde(rename = "QueueMessage")]
pub messages: Option<Vec<MessageInternal>>,
}
impl std::convert::TryFrom<&Response<Bytes>> for GetMessagesResponse {
type Error = crate::Error;
fn try_from(response: &Response<Bytes>) -> Result<Self, Self::Error> {
let headers = response.headers();
let body = response.body();
debug!("headers == {:?}", headers);
debug!("body == {:#?}", body);
let response: MessagesInternal = read_xml(body)?;
debug!("response == {:?}", response);
let mut messages = Vec::new();
for message in response.messages.unwrap_or_default().into_iter() {
messages.push(Message {
pop_receipt: PopReceipt::new(message.message_id, message.pop_receipt),
insertion_time: utc_date_from_rfc2822(&message.insertion_time)?,
expiration_time: utc_date_from_rfc2822(&message.expiration_time)?,
time_next_visible: utc_date_from_rfc2822(&message.time_next_visible)?,
dequeue_count: message.dequeue_count,
message_text: message.message_text,
})
}
Ok(GetMessagesResponse {
common_storage_response_headers: headers.try_into()?,
messages,
})
}
}
|
#[doc = "Register `FRCR` reader"]
pub type R = crate::R<FRCR_SPEC>;
#[doc = "Register `FRCR` writer"]
pub type W = crate::W<FRCR_SPEC>;
#[doc = "Field `FRL` reader - Frame length"]
pub type FRL_R = crate::FieldReader;
#[doc = "Field `FRL` writer - Frame length"]
pub type FRL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `FSALL` reader - Frame synchronization active level length"]
pub type FSALL_R = crate::FieldReader;
#[doc = "Field `FSALL` writer - Frame synchronization active level length"]
pub type FSALL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>;
#[doc = "Field `FSDEF` reader - Frame synchronization definition"]
pub type FSDEF_R = crate::BitReader;
#[doc = "Field `FSDEF` writer - Frame synchronization definition"]
pub type FSDEF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FSPOL` reader - Frame synchronization polarity"]
pub type FSPOL_R = crate::BitReader<FSPOL_A>;
#[doc = "Frame synchronization polarity\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FSPOL_A {
#[doc = "0: FS is active low (falling edge)"]
FallingEdge = 0,
#[doc = "1: FS is active high (rising edge)"]
RisingEdge = 1,
}
impl From<FSPOL_A> for bool {
#[inline(always)]
fn from(variant: FSPOL_A) -> Self {
variant as u8 != 0
}
}
impl FSPOL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FSPOL_A {
match self.bits {
false => FSPOL_A::FallingEdge,
true => FSPOL_A::RisingEdge,
}
}
#[doc = "FS is active low (falling edge)"]
#[inline(always)]
pub fn is_falling_edge(&self) -> bool {
*self == FSPOL_A::FallingEdge
}
#[doc = "FS is active high (rising edge)"]
#[inline(always)]
pub fn is_rising_edge(&self) -> bool {
*self == FSPOL_A::RisingEdge
}
}
#[doc = "Field `FSPOL` writer - Frame synchronization polarity"]
pub type FSPOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FSPOL_A>;
impl<'a, REG, const O: u8> FSPOL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "FS is active low (falling edge)"]
#[inline(always)]
pub fn falling_edge(self) -> &'a mut crate::W<REG> {
self.variant(FSPOL_A::FallingEdge)
}
#[doc = "FS is active high (rising edge)"]
#[inline(always)]
pub fn rising_edge(self) -> &'a mut crate::W<REG> {
self.variant(FSPOL_A::RisingEdge)
}
}
#[doc = "Field `FSOFF` reader - Frame synchronization offset"]
pub type FSOFF_R = crate::BitReader<FSOFF_A>;
#[doc = "Frame synchronization offset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FSOFF_A {
#[doc = "0: FS is asserted on the first bit of the slot 0"]
OnFirst = 0,
#[doc = "1: FS is asserted one bit before the first bit of the slot 0"]
BeforeFirst = 1,
}
impl From<FSOFF_A> for bool {
#[inline(always)]
fn from(variant: FSOFF_A) -> Self {
variant as u8 != 0
}
}
impl FSOFF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FSOFF_A {
match self.bits {
false => FSOFF_A::OnFirst,
true => FSOFF_A::BeforeFirst,
}
}
#[doc = "FS is asserted on the first bit of the slot 0"]
#[inline(always)]
pub fn is_on_first(&self) -> bool {
*self == FSOFF_A::OnFirst
}
#[doc = "FS is asserted one bit before the first bit of the slot 0"]
#[inline(always)]
pub fn is_before_first(&self) -> bool {
*self == FSOFF_A::BeforeFirst
}
}
#[doc = "Field `FSOFF` writer - Frame synchronization offset"]
pub type FSOFF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FSOFF_A>;
impl<'a, REG, const O: u8> FSOFF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "FS is asserted on the first bit of the slot 0"]
#[inline(always)]
pub fn on_first(self) -> &'a mut crate::W<REG> {
self.variant(FSOFF_A::OnFirst)
}
#[doc = "FS is asserted one bit before the first bit of the slot 0"]
#[inline(always)]
pub fn before_first(self) -> &'a mut crate::W<REG> {
self.variant(FSOFF_A::BeforeFirst)
}
}
impl R {
#[doc = "Bits 0:7 - Frame length"]
#[inline(always)]
pub fn frl(&self) -> FRL_R {
FRL_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:14 - Frame synchronization active level length"]
#[inline(always)]
pub fn fsall(&self) -> FSALL_R {
FSALL_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bit 16 - Frame synchronization definition"]
#[inline(always)]
pub fn fsdef(&self) -> FSDEF_R {
FSDEF_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Frame synchronization polarity"]
#[inline(always)]
pub fn fspol(&self) -> FSPOL_R {
FSPOL_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Frame synchronization offset"]
#[inline(always)]
pub fn fsoff(&self) -> FSOFF_R {
FSOFF_R::new(((self.bits >> 18) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:7 - Frame length"]
#[inline(always)]
#[must_use]
pub fn frl(&mut self) -> FRL_W<FRCR_SPEC, 0> {
FRL_W::new(self)
}
#[doc = "Bits 8:14 - Frame synchronization active level length"]
#[inline(always)]
#[must_use]
pub fn fsall(&mut self) -> FSALL_W<FRCR_SPEC, 8> {
FSALL_W::new(self)
}
#[doc = "Bit 16 - Frame synchronization definition"]
#[inline(always)]
#[must_use]
pub fn fsdef(&mut self) -> FSDEF_W<FRCR_SPEC, 16> {
FSDEF_W::new(self)
}
#[doc = "Bit 17 - Frame synchronization polarity"]
#[inline(always)]
#[must_use]
pub fn fspol(&mut self) -> FSPOL_W<FRCR_SPEC, 17> {
FSPOL_W::new(self)
}
#[doc = "Bit 18 - Frame synchronization offset"]
#[inline(always)]
#[must_use]
pub fn fsoff(&mut self) -> FSOFF_W<FRCR_SPEC, 18> {
FSOFF_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "AFRCR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`frcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`frcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FRCR_SPEC;
impl crate::RegisterSpec for FRCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`frcr::R`](R) reader structure"]
impl crate::Readable for FRCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`frcr::W`](W) writer structure"]
impl crate::Writable for FRCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FRCR to value 0x07"]
impl crate::Resettable for FRCR_SPEC {
const RESET_VALUE: Self::Ux = 0x07;
}
|
// https://projecteuler.net/problem=15
/*
Starting in the top left corner of a 2×2 grid, and only being able to
move to the right and down, there are exactly 6 routes to the bottom
right corner.
rrdd - right right down down
rdrd
rddr
drrd
drdr
ddrr
How many such routes are there through a 20×20 grid?
*/
fn main() {
let start_time = std::time::Instant::now();
//const SZ : usize = 2+1;
const SZ : usize = 20+1;
let mut locs : [ [u64; SZ] ; SZ ] = [ [0 ; SZ] ;SZ ];
// set the south and east edges:
for i in 0..SZ {
locs[SZ-1][i] = 1;
locs[i][SZ-1] = 1;
}
// starting in the far south east corner, fill rows east first, then north
for y in (0..SZ-1).rev() {
for x in (0..SZ-1).rev() {
locs[x][y] = locs[x+1][y] + locs[x][y+1];
/*
println!("{} {}", x, y);
for i in 0..SZ {
println!(" {:?}", locs[i]);
}
*/
}
}
println!("\nSolution: {}", locs[0][0]);
let elapsed = start_time.elapsed().as_micros();
println!("Elasped time: {} us", elapsed);
}
|
//! Log module
use byteorder::{BigEndian, ByteOrder};
use super::types::*;
/// As log trait for how primitive types are represented as indexed arguments
/// of the event log
pub trait AsLog {
/// Convert type to hash representation for the event log.
fn as_log(&self) -> H256;
}
impl AsLog for u32 {
fn as_log(&self) -> H256 {
let mut result = H256::zero();
BigEndian::write_u32(&mut result.as_mut()[28..32], *self);
result
}
}
impl AsLog for u64 {
fn as_log(&self) -> H256 {
let mut result = H256::zero();
BigEndian::write_u64(&mut result.as_mut()[24..32], *self);
result
}
}
impl AsLog for i64 {
fn as_log(&self) -> H256 {
let mut result = H256::zero();
BigEndian::write_i64(&mut result.as_mut()[24..32], *self);
result
}
}
impl AsLog for i32 {
fn as_log(&self) -> H256 {
let mut result = H256::zero();
BigEndian::write_i32(&mut result.as_mut()[28..32], *self);
result
}
}
impl AsLog for bool {
fn as_log(&self) -> H256 {
let mut result = H256::zero();
result.as_mut()[32] = if *self { 1 } else { 0 };
result
}
}
impl AsLog for U256 {
fn as_log(&self) -> H256 {
let mut result = H256::zero();
self.to_big_endian(result.as_mut());
result
}
}
impl AsLog for H256 {
fn as_log(&self) -> H256 {
self.clone()
}
}
impl AsLog for Address {
fn as_log(&self) -> H256 {
(*self).into()
}
}
|
extern crate tui;
extern crate termion;
extern crate chrono;
extern crate xdg;
use std::io;
use termion::event;
use termion::input::TermRead;
use termion::screen::AlternateScreen;
use tui::Terminal;
use tui::backend::TermionBackend;
use tui::layout::{Group, Size};
use tui::widgets::Widget;
use chrono::offset::local::Local;
use self::calendar::Calendar;
mod editor;
mod month;
mod calendar;
mod week;
mod database;
fn one_day() -> chrono::Duration {
chrono::Duration::days(1)
}
fn day_suffix(n: u32) -> &'static str {
match (n % 10, (n % 100) / 10) {
(1, x) if x != 1 => "st",
(2, x) if x != 1 => "nd",
(3, x) if x != 1 => "rd",
_ => "th",
}
}
const DAY_NAMES: [&'static str; 7] = [
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun",
];
const MONTH_NAMES: [&'static str; 12] = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
fn main() {
match run() {
Ok(()) => (),
Err(e) => {
println!("Error! {}", e);
},
}
}
fn run() -> Result<(), io::Error> {
let _alt_screen = AlternateScreen::from(io::stdout());
let backend = TermionBackend::new()?;
let mut terminal = Terminal::new(backend)?;
terminal.clear()?;
terminal.hide_cursor()?;
let mut calendar = Calendar::new(Local::now().naive_local());
let mut size = terminal.size()?;
let mut keys = io::stdin().keys();
loop {
Group::default()
.sizes(&[Size::Percent(100)])
.render(&mut terminal, &size, |t, chunks| {
calendar.render(t, &chunks[0])
});
terminal.draw()?;
let c = match keys.next() {
Some(c) => c?,
None => break,
};
let new_size = terminal.size()?;
if new_size != size {
size = new_size;
terminal.resize(size)?;
}
let redraw = match c {
event::Key::Char('q') => break,
event::Key::Left | event::Key::Char('h') => calendar.left(),
event::Key::Down | event::Key::Char('j') => calendar.down(),
event::Key::Up | event::Key::Char('k') => calendar.up(),
event::Key::Right | event::Key::Char('l') => calendar.right(),
event::Key::Char('\n') => calendar.enter(),
event::Key::Char('>') => calendar.next_view(),
event::Key::Char('<') => calendar.prev_view(),
_ => false,
};
if redraw {
terminal.hide_cursor()?;
terminal.resize(size)?;
}
}
terminal.show_cursor()?;
Ok(())
}
|
use std::collections::{HashMap, HashSet};
use hymns::runner::timed_run;
const INPUT: &str = include_str!("../input.txt");
type Graph = HashMap<Cave, Vec<Cave>>;
#[derive(Debug, Hash, Eq, PartialEq, Copy, Clone)]
enum Cave {
Start,
End,
Big(&'static str),
Small(&'static str),
}
impl TryFrom<&'static str> for Cave {
type Error = ();
fn try_from(s: &'static str) -> Result<Self, Self::Error> {
match s {
"start" => Ok(Cave::Start),
"end" => Ok(Cave::End),
_ => {
if s.chars().next().ok_or(())?.is_ascii_lowercase() {
Ok(Cave::Small(s))
} else {
Ok(Cave::Big(s))
}
}
}
}
}
fn find_paths(map: &Graph, can_visit_smalls_twice: bool) -> usize {
let mut exploring: Vec<(HashSet<Cave>, Cave, bool)> = vec![(
HashSet::from([Cave::Start]),
Cave::Start,
can_visit_smalls_twice,
)];
let mut path_count = 0;
while let Some((path, last, can_visit_twice)) = exploring.pop() {
let filtered_neighbors = map
.get(&last)
.unwrap()
.iter()
.filter(|&&n| n != Cave::Start);
for neighbor in filtered_neighbors {
if neighbor == &Cave::End {
path_count += 1;
} else if matches!(neighbor, Cave::Big(_)) || !path.contains(neighbor) {
let mut path = path.clone();
path.insert(*neighbor);
exploring.push((path, *neighbor, can_visit_twice));
} else if can_visit_twice {
let mut path = path.clone();
path.insert(*neighbor);
exploring.push((path, *neighbor, false));
}
}
}
path_count
}
fn build_graph() -> Graph {
let mut graph: Graph = HashMap::new();
for line in INPUT.lines() {
let mut comps = line.split('-');
let begin: Cave = comps.next().unwrap().try_into().unwrap();
let end: Cave = comps.next().unwrap().try_into().unwrap();
graph.entry(begin).or_insert_with(Vec::new).push(end);
graph.entry(end).or_insert_with(Vec::new).push(begin);
}
graph
}
fn part1() -> usize {
let graph = build_graph();
find_paths(&graph, false)
}
fn part2() -> usize {
let graph = build_graph();
find_paths(&graph, true)
}
fn main() {
timed_run(1, part1);
timed_run(2, part2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert_eq!(part1(), 4754);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 143562);
}
}
|
//! # InfluxDB Client
//! InfluxDB is an open source time series database with no external dependencies.
//! It's useful for recording metrics, events, and performing analytics.
//!
//! ## Usage
//!
//! ```Rust
//! extern crate influx_db_client;
//!
//! use influx_db_client::{InfluxdbClient, Point, Points, Value, InfluxClient, Precision};
//!
//! fn main() {
//! let mut client = InfluxdbClient::new("http://localhost:8086", "test", "root", "root");
//! client.set_write_timeout(10);
//! client.set_read_timeout(10);
//!
//! let mut point = Point::new("test");
//! point.add_field("somefield", Value::Integer(65));
//!
//! let mut point1 = Point::new("test2");
//! point1.add_field("somefield", Value::Float(12.2));
//! point1.add_tag("sometag", Value::Boolean(false));
//!
//! let mut points = Points::new(point);
//! points.push(point1);
//!
//! // if Precision is None, the default is second
//! // Multiple write
//! let res = client.write_points(points, Some(Precision::Microseconds), None).unwrap();
//! let version = client.get_version().unwrap();
//! println!("{}\nversion:{}", res, version)
//!
//! // query
//! let res = client.query("select * from test", None).unwrap();
//! println!("{:?}", res[0].get("series").unwrap()[0].get("values"))
//! }
//! ```
extern crate hyper;
extern crate serde_json;
use hyper::client::Client;
use hyper::Url;
use std::collections::BTreeMap;
use std::io::Read;
use std::time::Duration;
pub mod serialization;
#[derive(Debug, Clone)]
pub enum Value {
String(String),
Float(f64),
Integer(i64),
Boolean(bool)
}
#[derive(Debug, Clone)]
pub struct Point {
pub measurement: String,
pub tags: BTreeMap<String, Value>,
pub fields: BTreeMap<String, Value>,
pub timestamp: Option<i64>
}
#[derive(Debug)]
pub struct Points {
pub point: Vec<Point>
}
#[derive(Debug)]
pub enum Precision {
Nanoseconds,
Microseconds,
Milliseconds,
Seconds,
Minutes,
Hours
}
trait Tostr {
fn to_str(&self) -> &str;
}
impl Tostr for Precision {
/// Convert Precision to &str
fn to_str(&self) -> &str {
match *self {
Precision::Nanoseconds => "n",
Precision::Microseconds => "u",
Precision::Milliseconds => "ms",
Precision::Seconds => "s",
Precision::Minutes => "m",
Precision::Hours => "h"
}
}
}
#[derive(Debug)]
pub struct InfluxdbClient<'a> {
host: &'a str,
db: &'a str,
username: &'a str,
passwd: &'a str,
read_timeout: Option<u64>,
write_timeout: Option<u64>,
}
pub trait InfluxClient {
/// Query whether the corresponding database exists, return bool
fn ping(&self) -> bool;
/// Query the version of the database and return the version number
fn get_version(&self) -> Option<String>;
/// Write a point to the database
fn write_point(&self, point: Point, precision: Option<Precision>, rp: Option<&str>) -> Result<bool, String>;
/// Write multiple points to the database
///
/// ```Rust
/// let mut client = InfluxdbClient::new("http://localhost:8086", "test", "root", "root");
/// client.set_write_timeout(10);
/// client.set_read_timeout(10);
///
/// let mut point = Point::new("test");
/// point.add_field("somefield", Value::Integer(65));
///
/// let mut point1 = Point::new("test2");
/// point1.add_field("somefield", Value::Float(12.2));
/// point1.add_tag("sometag", Value::Boolean(false));
///
/// let mut points = Points::new(point);
/// points.push(point1);
///
/// if Precision is None, the default is second
/// Multiple write
/// let res = client.write_points(points, Some(Precision::Microseconds), None).unwrap();
/// ```
fn write_points(&self, points: Points, precision: Option<Precision>, rp: Option<&str>) -> Result<bool, String>;
/// Query and return data, the data type is `Vec<serde_json::Value>`, such as "show, select"
///
/// ```Rust
/// let client = InfluxdbClient::new("http://localhost:8086", "test", "root", "root");
/// let res = client.query("select * from test", None).unwrap();
/// println!("{:?}", res[0].get("series").unwrap()[0].get("values"));
/// ```
fn query(&self, q: &str, epoch: Option<Precision>) -> Result<Vec<serde_json::Value>, String>;
/// Create a new database in InfluxDB.
fn create_database(&self, dbname: &str) -> String;
/// Drop a database from InfluxDB.
fn drop_database(&self, dbname: &str) -> String;
/// Create a new user in InfluxDB.
fn create_user(&self, user: &str, passwd: &str, admin: bool) -> String;
/// Drop a user from InfluxDB.
fn drop_user(&self, user: &str) -> String;
/// Change the password of an existing user.
fn set_user_password(&self, user: &str, passwd: &str) -> String;
/// Grant cluster administration privileges to a user.
fn grant_admin_privileges(&self, user: &str) -> String;
/// Revoke cluster administration privileges from a user.
fn revoke_admin_privileges(&self, user: &str) -> String;
/// Grant a privilege on a database to a user.
/// :param privilege: the privilege to grant, one of 'read', 'write'
/// or 'all'. The string is case-insensitive
fn grant_privilege(&self, user: &str, db: &str, privilege: &str) -> String;
/// Revoke a privilege on a database from a user.
/// :param privilege: the privilege to grant, one of 'read', 'write'
/// or 'all'. The string is case-insensitive
fn revoke_privilege(&self, user: &str, db: &str, privilege: &str) -> String;
/// Create a retention policy for a database.
fn create_retention_policy(&self, name: &str, duration: &str, replication: &str, default: bool, db: Option<&str>) -> String;
/// Drop an existing retention policy for a database.
fn drop_retention_policy(&self, name: &str, db: Option<&str>) -> String;
}
trait Query {
/// Query and return to the native json structure
fn query_raw(&self, q: &str, epoch: Option<Precision>) -> Result<serde_json::Value, String>;
}
impl<'a> InfluxdbClient<'a> {
/// Create a new influxdb client
pub fn new(host: &'a str, db: &'a str, username: &'a str, passwd: &'a str) -> InfluxdbClient<'a> {
InfluxdbClient {
host: host,
db: db,
username: username,
passwd: passwd,
read_timeout: None,
write_timeout: None,
}
}
/// Set the read timeout value
pub fn set_read_timeout(&mut self, timeout: u64) {
self.read_timeout = Some(timeout);
}
/// Set the write timeout value
pub fn set_write_timeout(&mut self, timeout: u64) {
self.write_timeout = Some(timeout);
}
/// Change the client's database
pub fn swith_database(&mut self, database: &'a str) {
self.db = database;
}
/// Change the client's user
pub fn swith_user(&mut self, user: &'a str, passwd: &'a str) {
self.username = user;
self.passwd = passwd;
}
}
impl<'a> Query for InfluxdbClient<'a> {
/// Query and return to the native json structure
fn query_raw(&self, q: &str, epoch: Option<Precision>) -> Result<serde_json::Value, String> {
let mut param = vec![("db", self.db), ("u", self.username), ("p", self.passwd), ("q", q)];
match epoch {
Some(ref t) => param.push(("epoch", t.to_str())),
None => ()
}
let mut client = Client::new();
match self.read_timeout {
Some(t) => client.set_read_timeout(Some(Duration::new(t, 0))),
None => ()
}
match self.write_timeout {
Some(t) => client.set_write_timeout(Some(Duration::new(t, 0))),
None => ()
}
let url = Url::parse(self.host).unwrap();
let url = url.join("query").unwrap();
let url = Url::parse_with_params(url.as_str(), ¶m).unwrap();
let q_lower = q.to_lowercase();
let mut res = {
if q_lower.starts_with("select") && !q_lower.contains("into") || q_lower.starts_with("show") {
client.get(url).send().unwrap()
} else {
client.post(url).send().unwrap()
}
};
let mut context = String::new();
let _ = res.read_to_string(&mut context);
let json_data = serde_json::from_str(&context).unwrap();
match res.status_raw().0 {
200 => Ok(json_data),
400 => Err(json_data.get("error").unwrap().to_string()),
401 => Err("Invalid authentication credentials.".to_string()),
_ => Err("There is something wrong".to_string())
}
}
}
impl<'a> InfluxClient for InfluxdbClient<'a> {
/// Query whether the corresponding database exists, return bool
fn ping(&self) -> bool {
let ping = Client::new();
let url = Url::parse(self.host).unwrap();
let url = url.join("ping").unwrap();
let res = ping.get(url).send().unwrap();
match res.status_raw().0 {
204 => true,
_ => false,
}
}
/// Query the version of the database and return the version number
fn get_version(&self) -> Option<String> {
let ping = Client::new();
let url = Url::parse(self.host).unwrap();
let url = url.join("ping").unwrap();
let res = ping.get(url).send().unwrap();
match res.status_raw().0 {
204 => match res.headers.get_raw("X-Influxdb-Version") {
Some(i) => Some(String::from_utf8(i[0].to_vec()).unwrap()),
None => Some(String::from("Don't know"))
},
_ => None,
}
}
/// Write a point to the database
fn write_point(&self, point: Point, precision: Option<Precision>, rp: Option<&str>) -> Result<bool, String> {
let points = Points::new(point);
self.write_points(points, precision, rp)
}
/// Write multiple points to the database
fn write_points(&self, points: Points, precision: Option<Precision>, rp: Option<&str>) -> Result<bool, String> {
let line = serialization::line_serialization(points);
let mut param = vec![("db", self.db), ("u", self.username), ("p", self.passwd)];
match precision {
Some(ref t) => param.push(("precision", t.to_str())),
None => param.push(("precision", "s")),
};
match rp {
Some(t) => param.push(("rp", t)),
None => (),
};
let mut client = Client::new();
match self.read_timeout {
Some(t) => client.set_read_timeout(Some(Duration::new(t, 0))),
None => ()
}
match self.write_timeout {
Some(t) => client.set_write_timeout(Some(Duration::new(t, 0))),
None => ()
}
let url = Url::parse(self.host).unwrap();
let url = url.join("write").unwrap();
let url = Url::parse_with_params(url.as_str(), ¶m).unwrap();
let mut res = client.post(url).body(&line).send().unwrap();
let mut err = String::new();
let _ = res.read_to_string(&mut err);
match res.status_raw().0 {
204 => Ok(true),
400 => Err(err),
401 => Err("Invalid authentication credentials.".to_string()),
404 => Err(err),
500 => Err(err),
_ => Err("There is something wrong".to_string())
}
}
/// Query and return data, the data type is `Vec<serde_json::Value>`
fn query(&self, q: &str, epoch: Option<Precision>) -> Result<Vec<serde_json::Value>, String> {
match self.query_raw(q, epoch) {
Ok(t) => Ok(t.get("results").unwrap().as_array().unwrap().to_vec()),
Err(e) => Err(e)
}
}
/// Create a new database in InfluxDB.
fn create_database(&self, dbname: &str) -> String {
let sql = format!("Create database {}", serialization::quote_ident(dbname));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Drop a database from InfluxDB.
fn drop_database(&self, dbname: &str) -> String {
let sql = format!("Drop database {}", serialization::quote_ident(dbname));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Create a new user in InfluxDB.
fn create_user(&self, user: &str, passwd: &str, admin: bool) -> String {
let sql: String = {
if admin {
format!("Create user {0} with password {1} with all privileges",
serialization::quote_ident(user), serialization::quote_literal(passwd))
} else {
format!("Create user {0} WITH password {1}", serialization::quote_ident(user),
serialization::quote_literal(passwd))
}
};
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Drop a user from InfluxDB.
fn drop_user(&self, user: &str) -> String {
let sql = format!("Drop user {}", serialization::quote_ident(user));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Change the password of an existing user.
fn set_user_password(&self, user: &str, passwd: &str) -> String {
let sql = format!("Set password for {}={}", serialization::quote_ident(user),
serialization::quote_literal(passwd));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Grant cluster administration privileges to a user.
fn grant_admin_privileges(&self, user: &str) -> String {
let sql = format!("Grant all privileges to {}", serialization::quote_ident(user));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Revoke cluster administration privileges from a user.
fn revoke_admin_privileges(&self, user: &str) -> String {
let sql = format!("Revoke all privileges from {}", serialization::quote_ident(user));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Grant a privilege on a database to a user.
/// :param privilege: the privilege to grant, one of 'read', 'write'
/// or 'all'. The string is case-insensitive
fn grant_privilege(&self, user: &str, db: &str, privilege: &str) -> String {
let sql = format!("Grant {} on {} to {}", privilege, serialization::quote_ident(db),
serialization::quote_ident(user));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Revoke a privilege on a database from a user.
/// :param privilege: the privilege to grant, one of 'read', 'write'
/// or 'all'. The string is case-insensitive
fn revoke_privilege(&self, user: &str, db: &str, privilege: &str) -> String {
let sql = format!("Revoke {0} on {1} from {2}", privilege, serialization::quote_ident(db),
serialization::quote_ident(user));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Create a retention policy for a database.
/// :param duration: the duration of the new retention policy.
/// Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
/// and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
/// respectively. For infinite retention – meaning the data will
/// never be deleted – use 'INF' for duration.
/// The minimum retention period is 1 hour.
fn create_retention_policy(&self, name: &str, duration: &str, replication: &str, default: bool, db: Option<&str>) -> String {
let database = {
if let Some(t) = db {
t
} else {
self.db
}
};
let sql: String = {
if default {
format!("Create retention policy {} on {} duration {} replication {} default",
serialization::quote_ident(name), serialization::quote_ident(database), duration, replication)
} else {
format!("Create retention policy {} on {} duration {} replication {}",
serialization::quote_ident(name), serialization::quote_ident(database), duration, replication)
}
};
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
/// Drop an existing retention policy for a database.
fn drop_retention_policy(&self, name: &str, db: Option<&str>) -> String {
let database = {
if let Some(t) = db {
t
} else {
self.db
}
};
let sql = format!("Drop retention policy {} on {}", serialization::quote_ident(name),
serialization::quote_ident(database));
if let Err(err) = self.query_raw(&sql, None) {
err
} else { String::from("0") }
}
}
impl Point {
/// Create a new point
pub fn new(measurement: &str) -> Point {
Point {
measurement: String::from(measurement),
tags: BTreeMap::new(),
fields: BTreeMap::new(),
timestamp: None,
}
}
/// Add a tag and its value
pub fn add_tag(&mut self, tag: &str, value: Value) {
self.tags.insert(tag.to_string(), value);
}
/// Add a field and its value
pub fn add_field(&mut self, field: &str, value: Value) {
self.fields.insert(field.to_string(), value);
}
/// Set the specified timestamp
pub fn add_timestamp(&mut self, timestamp: i64) {
self.timestamp = Some(timestamp);
}
}
impl Points {
/// Create a new points
pub fn new(point: Point) -> Points {
let mut points = Vec::new();
points.push(point);
Points {
point: points,
}
}
/// Insert point into already existing points
pub fn push(&mut self, point: Point) {
self.point.push(point)
}
/// Create a multi Points more directly
pub fn create_new(points: Vec<Point>) -> Points {
Points {
point: points
}
}
}
|
#[cfg(feature="wav")] extern crate hound;
extern crate instrument;
extern crate pitch_calc as pitch;
extern crate sample;
extern crate time_calc as time;
pub use map::{Audio, Map, Sample};
pub use mode::Mode;
pub use sampler::{Frames, Sampler};
pub mod dynamic;
pub mod map;
mod mode;
mod sampler;
#[cfg(feature="serde_serialization")]
mod serde;
pub type Velocity = f32;
|
mod data_types;
mod deb;
mod extractor;
#[cfg(test)]
mod deb_test;
pub use data_types::*;
pub use deb::*;
pub use extractor::*;
|
use crate::ast;
use crate::{Parse, Spanned, ToTokens};
/// An is expression.
#[derive(Debug, Clone, ToTokens, Parse, Spanned)]
pub struct ExprIs {
/// The left-hand side of a is operation.
pub lhs: Box<ast::Expr>,
/// The `is` keyword.
pub is: ast::Is,
/// The right-hand side of a is operation.
pub rhs: Box<ast::Expr>,
}
impl ExprIs {
/// If the expression is empty.
pub fn produces_nothing(&self) -> bool {
false
}
/// Test if the expression is a constant expression.
pub fn is_const(&self) -> bool {
self.lhs.is_const() && self.rhs.is_const()
}
}
|
// file: pheno.rs
//
// Copyright 2015-2017 The RsGenetic Developers
//
// 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.
/// A `Fitness` value is used to determine the quality of a `Phenotype`.
/// `Fitness` values should have an ordering.
///
/// **Make sure the following statement holds:**
/// A `Phenotype` with a `Fitness` value of `f1` performs better than
/// another `Phenotype` with a `Fitness` value of `f2` iff `f1 > f2`.
pub trait Fitness: Ord + Eq {
/// Get the zero value of this `Fitness` value.
/// The internal value should be 0.
fn zero() -> Self;
/// Get the absolute difference between two `Fitness` values.
fn abs_diff(&self, other: &Self) -> Self;
}
/// Defines what a Phenotype is.
/// A Phenotype can breed with other Phenotypes, resulting in a single child.
/// A Phenotype can also be mutated.
/// Finally, a Phenotype has a certain fitness value associated with it.
///
/// If reasonable, it is recommended to have your implementation derive `Copy`.
pub trait Phenotype<F>: Clone
where
F: Fitness,
{
/// Calculate the fitness of this Phenotype.
fn fitness(&self) -> F;
/// Perform crossover on this Phenotype, returning a new Phenotype.
fn crossover(&self, other: &Self) -> Self;
/// Perform mutation on this Phenotype, returning a new Phenotype.
fn mutate(&self) -> Self;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.