text stringlengths 8 4.13M |
|---|
//! Queries the major, minor and build version of Windows (NT) efficiently
//! with usage of undocumented NTDLL functions. **This crate is no_std.**
//!
//! It only has one function: [get](fn.get.html),
//! and it's recommended you use it explicitly like `nt_version::get()` because of this.
//!
//!
//! ## Build Error?
//! If building fails with a linker error, you're missing `ntdll.lib` from your system.
//! It doesn't come on older versions of Windows with the SDK and you need to install the DDK.
//!
//! You can alternatively enable the **fallback** feature which queries the function pointer at runtime.
#![no_std]
#[cfg(not(target_os = "windows"))]
compile_error!("This crate is for querying Windows, but the target isn't Windows.");
#[cfg(not(feature = "fallback"))]
mod internal {
#[link(name = "ntdll")]
extern "system" {
pub fn RtlGetNtVersionNumbers(major: *mut u32, minor: *mut u32, build: *mut u32);
}
}
#[cfg(feature = "fallback")]
mod internal {
#![allow(non_snake_case)]
use core::{mem::transmute, ptr};
use winapi::um::libloaderapi::{GetModuleHandleA, GetProcAddress};
static mut NTDLL_FUNCTION: *const () = ptr::null();
pub unsafe fn RtlGetNtVersionNumbers(major: *mut u32, minor: *mut u32, build: *mut u32) {
if NTDLL_FUNCTION.is_null() {
NTDLL_FUNCTION = GetProcAddress(
GetModuleHandleA(b"ntdll.dll\0".as_ptr() as *const _),
b"RtlGetNtVersionNumbers\0".as_ptr() as *const _,
) as *const _;
}
transmute::<_, extern "system" fn(*mut u32, *mut u32, *mut u32)>(NTDLL_FUNCTION)(
major, minor, build,
);
}
}
/// Queries the (major, minor, build) version of the Windows NT system.
/// The versions correspond to this table (transcribed from [here](http://www.geoffchappell.com/studies/windows/win32/ntdll/history/index.htm)):
///
/// | Version | Windows | NT |
/// | ------- | ------- | -- |
/// | 3.51 | | Windows NT 3.51 |
/// | 4.0 | Windows 95 | Windows NT 4.0 |
/// | 4.10 | Windows 98 | |
/// | 4.90 | Windows Me | |
/// | 5.0 | | Windows 2000 |
/// | 5.1 | | Windows XP |
/// | 5.2 | | Windows Server 2003 |
/// | 6.0 | | Windows Vista / Windows Server 2008 |
/// | 6.1 | | Windows 7 / Windows Server 2008 R2 |
/// | 6.2 | | Windows 8 |
/// | 6.3 | | Windows 8.1 |
/// | 10.0 | | Windows 10 |
pub fn get() -> (u32, u32, u32) {
let (mut major, mut minor, mut build) = (0u32, 0u32, 0u32);
unsafe {
internal::RtlGetNtVersionNumbers(&mut major as _, &mut minor as _, &mut build as _);
}
(major, minor, build)
}
|
#![feature(try_trait)]
extern crate reqwest;
extern crate serde_json;
extern crate time;
use serde_json::Value;
use std::io::Read;
static BASE_URL: &str = "https://min-api.cryptocompare.com/data/";
pub struct Options<'a> {
pub exchanges: &'a str,
pub try_conversion: bool
}
#[derive(Debug)]
pub struct Dataset {
pub close: f64,
pub high: f64,
pub low: f64,
pub open: f64,
pub time: i64,
pub volumefrom: f64,
pub volumeto: f64
}
pub fn get_coin_list() -> Result<serde_json::Value, Box<::std::error::Error>> {
let url = format!("{}all/coinlist", BASE_URL);
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_price(fsym: &str, tsyms: &str, options: &Options) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}price?fsym={}&tsyms={}", BASE_URL, fsym, tsyms);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_price_multi(fsyms: &str, tsyms: &str, options: &Options) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}pricemulti?fsyms={}&tsyms={}", BASE_URL, fsyms, tsyms);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_price_multi_full(fsyms: &str, tsyms: &str, options: &Options) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}pricemultifull?fsyms={}&tsyms={}", BASE_URL, fsyms, tsyms);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_price_historical(fsym: &str, tsyms: &str, options: &Options) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}pricehistorical?fsym={}&tsyms={}&ts={}", BASE_URL, fsym, tsyms, time::get_time().sec);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_history_day(fsym: &str, tsym: &str, options: &Options, limit: &u64) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}histoday?fsym={}&tsym={}&limit={}&aggregate=1", BASE_URL, fsym, tsym, limit);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_history_hour(fsym: &str, tsym: &str, options: &Options, limit: &u64) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}histohour?fsym={}&tsym={}&limit={}&aggregate=1", BASE_URL, fsym, tsym, limit);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn get_history_minute(fsym: &str, tsym: &str, options: &Options, limit: &u64) -> Result<serde_json::Value, Box<::std::error::Error>> {
let mut url = format!("{}histominute?fsym={}&tsym={}&limit={}&aggregate=1", BASE_URL, fsym, tsym, limit);
if options.exchanges != "" { url = format!("{}&e={}", url, options.exchanges); }
if !options.try_conversion { url = format!("{}&tryConversion={}", url, options.try_conversion); }
let mut result = String::new();
reqwest::get(&url)?.read_to_string(&mut result)?;
let value: Value = serde_json::from_str(&mut result)?;
Ok(value)
}
pub fn parse_json_to_vector(object: Value) -> Result<Vec<Dataset>, Box<::std::option::NoneError>> {
let mut vector: Vec<Dataset> = Vec::new();
let array = object.as_object()?["Data"].as_array()?;
for entry in array {
let elem = entry.as_object()?;
vector.push(Dataset {
close: elem["close"].as_f64()?,
high: elem["high"].as_f64()?,
low: elem["low"].as_f64()?,
open: elem["open"].as_f64()?,
time: elem["time"].as_i64()?,
volumefrom: elem["volumefrom"].as_f64()?,
volumeto: elem["volumeto"].as_f64()?
})
}
Ok(vector)
}
pub fn parse_json_to_float(object: Value, key: &str) -> Result<f64, Box<::std::option::NoneError>> {
let value = object.as_object()?[key].as_f64()?;
Ok(value)
}
|
#[doc = "Reader of register COMP4_CSR"]
pub type R = crate::R<u32, super::COMP4_CSR>;
#[doc = "Writer for register COMP4_CSR"]
pub type W = crate::W<u32, super::COMP4_CSR>;
#[doc = "Register COMP4_CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::COMP4_CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Comparator 4 enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMP4EN_A {
#[doc = "0: Comparator disabled"]
DISABLED = 0,
#[doc = "1: Comparator enabled"]
ENABLED = 1,
}
impl From<COMP4EN_A> for bool {
#[inline(always)]
fn from(variant: COMP4EN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `COMP4EN`"]
pub type COMP4EN_R = crate::R<bool, COMP4EN_A>;
impl COMP4EN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4EN_A {
match self.bits {
false => COMP4EN_A::DISABLED,
true => COMP4EN_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == COMP4EN_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == COMP4EN_A::ENABLED
}
}
#[doc = "Write proxy for field `COMP4EN`"]
pub struct COMP4EN_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4EN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP4EN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Comparator disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(COMP4EN_A::DISABLED)
}
#[doc = "Comparator enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(COMP4EN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Comparator 4 inverting input selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum COMP4INMSEL_A {
#[doc = "0: 1/4 of VRefint"]
ONEQUARTERVREF = 0,
#[doc = "1: 1/2 of VRefint"]
ONEHALFVREF = 1,
#[doc = "2: 3/4 of VRefint"]
THREEQUARTERVREF = 2,
#[doc = "3: VRefint"]
VREF = 3,
#[doc = "4: PA4 or DAC1_CH1 output if enabled"]
PA4_DAC1_CH1 = 4,
#[doc = "5: DAC1_CH2"]
DAC1_CH2 = 5,
#[doc = "7: PB2"]
PB2 = 7,
}
impl From<COMP4INMSEL_A> for u8 {
#[inline(always)]
fn from(variant: COMP4INMSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `COMP4INMSEL`"]
pub type COMP4INMSEL_R = crate::R<u8, COMP4INMSEL_A>;
impl COMP4INMSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, COMP4INMSEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(COMP4INMSEL_A::ONEQUARTERVREF),
1 => Val(COMP4INMSEL_A::ONEHALFVREF),
2 => Val(COMP4INMSEL_A::THREEQUARTERVREF),
3 => Val(COMP4INMSEL_A::VREF),
4 => Val(COMP4INMSEL_A::PA4_DAC1_CH1),
5 => Val(COMP4INMSEL_A::DAC1_CH2),
7 => Val(COMP4INMSEL_A::PB2),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `ONEQUARTERVREF`"]
#[inline(always)]
pub fn is_one_quarter_vref(&self) -> bool {
*self == COMP4INMSEL_A::ONEQUARTERVREF
}
#[doc = "Checks if the value of the field is `ONEHALFVREF`"]
#[inline(always)]
pub fn is_one_half_vref(&self) -> bool {
*self == COMP4INMSEL_A::ONEHALFVREF
}
#[doc = "Checks if the value of the field is `THREEQUARTERVREF`"]
#[inline(always)]
pub fn is_three_quarter_vref(&self) -> bool {
*self == COMP4INMSEL_A::THREEQUARTERVREF
}
#[doc = "Checks if the value of the field is `VREF`"]
#[inline(always)]
pub fn is_vref(&self) -> bool {
*self == COMP4INMSEL_A::VREF
}
#[doc = "Checks if the value of the field is `PA4_DAC1_CH1`"]
#[inline(always)]
pub fn is_pa4_dac1_ch1(&self) -> bool {
*self == COMP4INMSEL_A::PA4_DAC1_CH1
}
#[doc = "Checks if the value of the field is `DAC1_CH2`"]
#[inline(always)]
pub fn is_dac1_ch2(&self) -> bool {
*self == COMP4INMSEL_A::DAC1_CH2
}
#[doc = "Checks if the value of the field is `PB2`"]
#[inline(always)]
pub fn is_pb2(&self) -> bool {
*self == COMP4INMSEL_A::PB2
}
}
#[doc = "Write proxy for field `COMP4INMSEL`"]
pub struct COMP4INMSEL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4INMSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP4INMSEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "1/4 of VRefint"]
#[inline(always)]
pub fn one_quarter_vref(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::ONEQUARTERVREF)
}
#[doc = "1/2 of VRefint"]
#[inline(always)]
pub fn one_half_vref(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::ONEHALFVREF)
}
#[doc = "3/4 of VRefint"]
#[inline(always)]
pub fn three_quarter_vref(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::THREEQUARTERVREF)
}
#[doc = "VRefint"]
#[inline(always)]
pub fn vref(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::VREF)
}
#[doc = "PA4 or DAC1_CH1 output if enabled"]
#[inline(always)]
pub fn pa4_dac1_ch1(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::PA4_DAC1_CH1)
}
#[doc = "DAC1_CH2"]
#[inline(always)]
pub fn dac1_ch2(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::DAC1_CH2)
}
#[doc = "PB2"]
#[inline(always)]
pub fn pb2(self) -> &'a mut W {
self.variant(COMP4INMSEL_A::PB2)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 4)) | (((value as u32) & 0x07) << 4);
self.w
}
}
#[doc = "Comparator 4 output selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum COMP4OUTSEL_A {
#[doc = "0: No selection"]
NOSELECTION = 0,
#[doc = "1: Timer 1 break input"]
TIMER1BREAKINPUT = 1,
#[doc = "2: Timer 1 break input 2"]
TIMER1BREAKINPUT2 = 2,
#[doc = "6: Timer 3 input capture 3"]
TIMER3INPUTCAPTURE3 = 6,
#[doc = "8: Timer 15 input capture 2"]
TIMER15INPUTCAPTURE2 = 8,
#[doc = "10: Timer 15 OCREF_CLR input"]
TIMER15OCREFCLEARINPUT = 10,
#[doc = "11: Timer 3 OCREF_CLR input"]
TIMER3OCREFCLEARINPUT = 11,
}
impl From<COMP4OUTSEL_A> for u8 {
#[inline(always)]
fn from(variant: COMP4OUTSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `COMP4OUTSEL`"]
pub type COMP4OUTSEL_R = crate::R<u8, COMP4OUTSEL_A>;
impl COMP4OUTSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, COMP4OUTSEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(COMP4OUTSEL_A::NOSELECTION),
1 => Val(COMP4OUTSEL_A::TIMER1BREAKINPUT),
2 => Val(COMP4OUTSEL_A::TIMER1BREAKINPUT2),
6 => Val(COMP4OUTSEL_A::TIMER3INPUTCAPTURE3),
8 => Val(COMP4OUTSEL_A::TIMER15INPUTCAPTURE2),
10 => Val(COMP4OUTSEL_A::TIMER15OCREFCLEARINPUT),
11 => Val(COMP4OUTSEL_A::TIMER3OCREFCLEARINPUT),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `NOSELECTION`"]
#[inline(always)]
pub fn is_no_selection(&self) -> bool {
*self == COMP4OUTSEL_A::NOSELECTION
}
#[doc = "Checks if the value of the field is `TIMER1BREAKINPUT`"]
#[inline(always)]
pub fn is_timer1break_input(&self) -> bool {
*self == COMP4OUTSEL_A::TIMER1BREAKINPUT
}
#[doc = "Checks if the value of the field is `TIMER1BREAKINPUT2`"]
#[inline(always)]
pub fn is_timer1break_input2(&self) -> bool {
*self == COMP4OUTSEL_A::TIMER1BREAKINPUT2
}
#[doc = "Checks if the value of the field is `TIMER3INPUTCAPTURE3`"]
#[inline(always)]
pub fn is_timer3input_capture3(&self) -> bool {
*self == COMP4OUTSEL_A::TIMER3INPUTCAPTURE3
}
#[doc = "Checks if the value of the field is `TIMER15INPUTCAPTURE2`"]
#[inline(always)]
pub fn is_timer15input_capture2(&self) -> bool {
*self == COMP4OUTSEL_A::TIMER15INPUTCAPTURE2
}
#[doc = "Checks if the value of the field is `TIMER15OCREFCLEARINPUT`"]
#[inline(always)]
pub fn is_timer15ocref_clear_input(&self) -> bool {
*self == COMP4OUTSEL_A::TIMER15OCREFCLEARINPUT
}
#[doc = "Checks if the value of the field is `TIMER3OCREFCLEARINPUT`"]
#[inline(always)]
pub fn is_timer3ocref_clear_input(&self) -> bool {
*self == COMP4OUTSEL_A::TIMER3OCREFCLEARINPUT
}
}
#[doc = "Write proxy for field `COMP4OUTSEL`"]
pub struct COMP4OUTSEL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4OUTSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP4OUTSEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "No selection"]
#[inline(always)]
pub fn no_selection(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::NOSELECTION)
}
#[doc = "Timer 1 break input"]
#[inline(always)]
pub fn timer1break_input(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::TIMER1BREAKINPUT)
}
#[doc = "Timer 1 break input 2"]
#[inline(always)]
pub fn timer1break_input2(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::TIMER1BREAKINPUT2)
}
#[doc = "Timer 3 input capture 3"]
#[inline(always)]
pub fn timer3input_capture3(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::TIMER3INPUTCAPTURE3)
}
#[doc = "Timer 15 input capture 2"]
#[inline(always)]
pub fn timer15input_capture2(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::TIMER15INPUTCAPTURE2)
}
#[doc = "Timer 15 OCREF_CLR input"]
#[inline(always)]
pub fn timer15ocref_clear_input(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::TIMER15OCREFCLEARINPUT)
}
#[doc = "Timer 3 OCREF_CLR input"]
#[inline(always)]
pub fn timer3ocref_clear_input(self) -> &'a mut W {
self.variant(COMP4OUTSEL_A::TIMER3OCREFCLEARINPUT)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 10)) | (((value as u32) & 0x0f) << 10);
self.w
}
}
#[doc = "Comparator 4 output polarity\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMP4POL_A {
#[doc = "0: Output is not inverted"]
NOTINVERTED = 0,
#[doc = "1: Output is inverted"]
INVERTED = 1,
}
impl From<COMP4POL_A> for bool {
#[inline(always)]
fn from(variant: COMP4POL_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `COMP4POL`"]
pub type COMP4POL_R = crate::R<bool, COMP4POL_A>;
impl COMP4POL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4POL_A {
match self.bits {
false => COMP4POL_A::NOTINVERTED,
true => COMP4POL_A::INVERTED,
}
}
#[doc = "Checks if the value of the field is `NOTINVERTED`"]
#[inline(always)]
pub fn is_not_inverted(&self) -> bool {
*self == COMP4POL_A::NOTINVERTED
}
#[doc = "Checks if the value of the field is `INVERTED`"]
#[inline(always)]
pub fn is_inverted(&self) -> bool {
*self == COMP4POL_A::INVERTED
}
}
#[doc = "Write proxy for field `COMP4POL`"]
pub struct COMP4POL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4POL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP4POL_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Output is not inverted"]
#[inline(always)]
pub fn not_inverted(self) -> &'a mut W {
self.variant(COMP4POL_A::NOTINVERTED)
}
#[doc = "Output is inverted"]
#[inline(always)]
pub fn inverted(self) -> &'a mut W {
self.variant(COMP4POL_A::INVERTED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Comparator 4 blanking source\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum COMP4_BLANKING_A {
#[doc = "0: No blanking"]
NOBLANKING = 0,
#[doc = "1: TIM3 OC4 selected as blanking source"]
TIM3OC4 = 1,
#[doc = "3: TIM15 OC1 selected as blanking source"]
TIM15OC1 = 3,
}
impl From<COMP4_BLANKING_A> for u8 {
#[inline(always)]
fn from(variant: COMP4_BLANKING_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `COMP4_BLANKING`"]
pub type COMP4_BLANKING_R = crate::R<u8, COMP4_BLANKING_A>;
impl COMP4_BLANKING_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, COMP4_BLANKING_A> {
use crate::Variant::*;
match self.bits {
0 => Val(COMP4_BLANKING_A::NOBLANKING),
1 => Val(COMP4_BLANKING_A::TIM3OC4),
3 => Val(COMP4_BLANKING_A::TIM15OC1),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `NOBLANKING`"]
#[inline(always)]
pub fn is_no_blanking(&self) -> bool {
*self == COMP4_BLANKING_A::NOBLANKING
}
#[doc = "Checks if the value of the field is `TIM3OC4`"]
#[inline(always)]
pub fn is_tim3oc4(&self) -> bool {
*self == COMP4_BLANKING_A::TIM3OC4
}
#[doc = "Checks if the value of the field is `TIM15OC1`"]
#[inline(always)]
pub fn is_tim15oc1(&self) -> bool {
*self == COMP4_BLANKING_A::TIM15OC1
}
}
#[doc = "Write proxy for field `COMP4_BLANKING`"]
pub struct COMP4_BLANKING_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4_BLANKING_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP4_BLANKING_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "No blanking"]
#[inline(always)]
pub fn no_blanking(self) -> &'a mut W {
self.variant(COMP4_BLANKING_A::NOBLANKING)
}
#[doc = "TIM3 OC4 selected as blanking source"]
#[inline(always)]
pub fn tim3oc4(self) -> &'a mut W {
self.variant(COMP4_BLANKING_A::TIM3OC4)
}
#[doc = "TIM15 OC1 selected as blanking source"]
#[inline(always)]
pub fn tim15oc1(self) -> &'a mut W {
self.variant(COMP4_BLANKING_A::TIM15OC1)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 18)) | (((value as u32) & 0x07) << 18);
self.w
}
}
#[doc = "Comparator 4 output\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMP4OUT_A {
#[doc = "0: Non-inverting input below inverting input"]
LOW = 0,
#[doc = "1: Non-inverting input above inverting input"]
HIGH = 1,
}
impl From<COMP4OUT_A> for bool {
#[inline(always)]
fn from(variant: COMP4OUT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `COMP4OUT`"]
pub type COMP4OUT_R = crate::R<bool, COMP4OUT_A>;
impl COMP4OUT_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4OUT_A {
match self.bits {
false => COMP4OUT_A::LOW,
true => COMP4OUT_A::HIGH,
}
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == COMP4OUT_A::LOW
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == COMP4OUT_A::HIGH
}
}
#[doc = "Comparator 4 lock\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMP4LOCK_A {
#[doc = "0: Comparator CSR bits are read-write"]
UNLOCKED = 0,
#[doc = "1: Comparator CSR bits are read-only"]
LOCKED = 1,
}
impl From<COMP4LOCK_A> for bool {
#[inline(always)]
fn from(variant: COMP4LOCK_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `COMP4LOCK`"]
pub type COMP4LOCK_R = crate::R<bool, COMP4LOCK_A>;
impl COMP4LOCK_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4LOCK_A {
match self.bits {
false => COMP4LOCK_A::UNLOCKED,
true => COMP4LOCK_A::LOCKED,
}
}
#[doc = "Checks if the value of the field is `UNLOCKED`"]
#[inline(always)]
pub fn is_unlocked(&self) -> bool {
*self == COMP4LOCK_A::UNLOCKED
}
#[doc = "Checks if the value of the field is `LOCKED`"]
#[inline(always)]
pub fn is_locked(&self) -> bool {
*self == COMP4LOCK_A::LOCKED
}
}
#[doc = "Write proxy for field `COMP4LOCK`"]
pub struct COMP4LOCK_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4LOCK_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP4LOCK_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Comparator CSR bits are read-write"]
#[inline(always)]
pub fn unlocked(self) -> &'a mut W {
self.variant(COMP4LOCK_A::UNLOCKED)
}
#[doc = "Comparator CSR bits are read-only"]
#[inline(always)]
pub fn locked(self) -> &'a mut W {
self.variant(COMP4LOCK_A::LOCKED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
#[doc = "Reader of field `COMP4INMSEL3`"]
pub type COMP4INMSEL3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `COMP4INMSEL3`"]
pub struct COMP4INMSEL3_W<'a> {
w: &'a mut W,
}
impl<'a> COMP4INMSEL3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
impl R {
#[doc = "Bit 0 - Comparator 4 enable"]
#[inline(always)]
pub fn comp4en(&self) -> COMP4EN_R {
COMP4EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 4:6 - Comparator 4 inverting input selection"]
#[inline(always)]
pub fn comp4inmsel(&self) -> COMP4INMSEL_R {
COMP4INMSEL_R::new(((self.bits >> 4) & 0x07) as u8)
}
#[doc = "Bits 10:13 - Comparator 4 output selection"]
#[inline(always)]
pub fn comp4outsel(&self) -> COMP4OUTSEL_R {
COMP4OUTSEL_R::new(((self.bits >> 10) & 0x0f) as u8)
}
#[doc = "Bit 15 - Comparator 4 output polarity"]
#[inline(always)]
pub fn comp4pol(&self) -> COMP4POL_R {
COMP4POL_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bits 18:20 - Comparator 4 blanking source"]
#[inline(always)]
pub fn comp4_blanking(&self) -> COMP4_BLANKING_R {
COMP4_BLANKING_R::new(((self.bits >> 18) & 0x07) as u8)
}
#[doc = "Bit 30 - Comparator 4 output"]
#[inline(always)]
pub fn comp4out(&self) -> COMP4OUT_R {
COMP4OUT_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - Comparator 4 lock"]
#[inline(always)]
pub fn comp4lock(&self) -> COMP4LOCK_R {
COMP4LOCK_R::new(((self.bits >> 31) & 0x01) != 0)
}
#[doc = "Bit 22 - Comparator 4 inverting input selection"]
#[inline(always)]
pub fn comp4inmsel3(&self) -> COMP4INMSEL3_R {
COMP4INMSEL3_R::new(((self.bits >> 22) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Comparator 4 enable"]
#[inline(always)]
pub fn comp4en(&mut self) -> COMP4EN_W {
COMP4EN_W { w: self }
}
#[doc = "Bits 4:6 - Comparator 4 inverting input selection"]
#[inline(always)]
pub fn comp4inmsel(&mut self) -> COMP4INMSEL_W {
COMP4INMSEL_W { w: self }
}
#[doc = "Bits 10:13 - Comparator 4 output selection"]
#[inline(always)]
pub fn comp4outsel(&mut self) -> COMP4OUTSEL_W {
COMP4OUTSEL_W { w: self }
}
#[doc = "Bit 15 - Comparator 4 output polarity"]
#[inline(always)]
pub fn comp4pol(&mut self) -> COMP4POL_W {
COMP4POL_W { w: self }
}
#[doc = "Bits 18:20 - Comparator 4 blanking source"]
#[inline(always)]
pub fn comp4_blanking(&mut self) -> COMP4_BLANKING_W {
COMP4_BLANKING_W { w: self }
}
#[doc = "Bit 31 - Comparator 4 lock"]
#[inline(always)]
pub fn comp4lock(&mut self) -> COMP4LOCK_W {
COMP4LOCK_W { w: self }
}
#[doc = "Bit 22 - Comparator 4 inverting input selection"]
#[inline(always)]
pub fn comp4inmsel3(&mut self) -> COMP4INMSEL3_W {
COMP4INMSEL3_W { w: self }
}
}
|
#[doc = "Reader of register APB2RSTR"]
pub type R = crate::R<u32, super::APB2RSTR>;
#[doc = "Writer for register APB2RSTR"]
pub type W = crate::W<u32, super::APB2RSTR>;
#[doc = "Register APB2RSTR `reset()`'s with value 0"]
impl crate::ResetValue for super::APB2RSTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "TIM1 block reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIM1RST_A {
#[doc = "1: Reset the selected module"]
RESET = 1,
}
impl From<TIM1RST_A> for bool {
#[inline(always)]
fn from(variant: TIM1RST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TIM1RST`"]
pub type TIM1RST_R = crate::R<bool, TIM1RST_A>;
impl TIM1RST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, TIM1RST_A> {
use crate::Variant::*;
match self.bits {
true => Val(TIM1RST_A::RESET),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RESET`"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == TIM1RST_A::RESET
}
}
#[doc = "Write proxy for field `TIM1RST`"]
pub struct TIM1RST_W<'a> {
w: &'a mut W,
}
impl<'a> TIM1RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM1RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "TIM8 block reset"]
pub type TIM8RST_A = TIM1RST_A;
#[doc = "Reader of field `TIM8RST`"]
pub type TIM8RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `TIM8RST`"]
pub struct TIM8RST_W<'a> {
w: &'a mut W,
}
impl<'a> TIM8RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM8RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "USART1 block reset"]
pub type USART1RST_A = TIM1RST_A;
#[doc = "Reader of field `USART1RST`"]
pub type USART1RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `USART1RST`"]
pub struct USART1RST_W<'a> {
w: &'a mut W,
}
impl<'a> USART1RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART1RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "USART6 block reset"]
pub type USART6RST_A = TIM1RST_A;
#[doc = "Reader of field `USART6RST`"]
pub type USART6RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `USART6RST`"]
pub struct USART6RST_W<'a> {
w: &'a mut W,
}
impl<'a> USART6RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART6RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "SPI1 block reset"]
pub type SPI1RST_A = TIM1RST_A;
#[doc = "Reader of field `SPI1RST`"]
pub type SPI1RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `SPI1RST`"]
pub struct SPI1RST_W<'a> {
w: &'a mut W,
}
impl<'a> SPI1RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI1RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "SPI4 block reset"]
pub type SPI4RST_A = TIM1RST_A;
#[doc = "Reader of field `SPI4RST`"]
pub type SPI4RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `SPI4RST`"]
pub struct SPI4RST_W<'a> {
w: &'a mut W,
}
impl<'a> SPI4RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI4RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "TIM15 block reset"]
pub type TIM15RST_A = TIM1RST_A;
#[doc = "Reader of field `TIM15RST`"]
pub type TIM15RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `TIM15RST`"]
pub struct TIM15RST_W<'a> {
w: &'a mut W,
}
impl<'a> TIM15RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM15RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "TIM16 block reset"]
pub type TIM16RST_A = TIM1RST_A;
#[doc = "Reader of field `TIM16RST`"]
pub type TIM16RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `TIM16RST`"]
pub struct TIM16RST_W<'a> {
w: &'a mut W,
}
impl<'a> TIM16RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM16RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "TIM17 block reset"]
pub type TIM17RST_A = TIM1RST_A;
#[doc = "Reader of field `TIM17RST`"]
pub type TIM17RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `TIM17RST`"]
pub struct TIM17RST_W<'a> {
w: &'a mut W,
}
impl<'a> TIM17RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM17RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "SPI5 block reset"]
pub type SPI5RST_A = TIM1RST_A;
#[doc = "Reader of field `SPI5RST`"]
pub type SPI5RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `SPI5RST`"]
pub struct SPI5RST_W<'a> {
w: &'a mut W,
}
impl<'a> SPI5RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI5RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "SAI1 block reset"]
pub type SAI1RST_A = TIM1RST_A;
#[doc = "Reader of field `SAI1RST`"]
pub type SAI1RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `SAI1RST`"]
pub struct SAI1RST_W<'a> {
w: &'a mut W,
}
impl<'a> SAI1RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI1RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "SAI2 block reset"]
pub type SAI2RST_A = TIM1RST_A;
#[doc = "Reader of field `SAI2RST`"]
pub type SAI2RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `SAI2RST`"]
pub struct SAI2RST_W<'a> {
w: &'a mut W,
}
impl<'a> SAI2RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI2RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "SAI3 block reset"]
pub type SAI3RST_A = TIM1RST_A;
#[doc = "Reader of field `SAI3RST`"]
pub type SAI3RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `SAI3RST`"]
pub struct SAI3RST_W<'a> {
w: &'a mut W,
}
impl<'a> SAI3RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI3RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "DFSDM1 block reset"]
pub type DFSDM1RST_A = TIM1RST_A;
#[doc = "Reader of field `DFSDM1RST`"]
pub type DFSDM1RST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `DFSDM1RST`"]
pub struct DFSDM1RST_W<'a> {
w: &'a mut W,
}
impl<'a> DFSDM1RST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DFSDM1RST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "HRTIM block reset"]
pub type HRTIMRST_A = TIM1RST_A;
#[doc = "Reader of field `HRTIMRST`"]
pub type HRTIMRST_R = crate::R<bool, TIM1RST_A>;
#[doc = "Write proxy for field `HRTIMRST`"]
pub struct HRTIMRST_W<'a> {
w: &'a mut W,
}
impl<'a> HRTIMRST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HRTIMRST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut W {
self.variant(TIM1RST_A::RESET)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
impl R {
#[doc = "Bit 0 - TIM1 block reset"]
#[inline(always)]
pub fn tim1rst(&self) -> TIM1RST_R {
TIM1RST_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TIM8 block reset"]
#[inline(always)]
pub fn tim8rst(&self) -> TIM8RST_R {
TIM8RST_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 4 - USART1 block reset"]
#[inline(always)]
pub fn usart1rst(&self) -> USART1RST_R {
USART1RST_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - USART6 block reset"]
#[inline(always)]
pub fn usart6rst(&self) -> USART6RST_R {
USART6RST_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 12 - SPI1 block reset"]
#[inline(always)]
pub fn spi1rst(&self) -> SPI1RST_R {
SPI1RST_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - SPI4 block reset"]
#[inline(always)]
pub fn spi4rst(&self) -> SPI4RST_R {
SPI4RST_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 16 - TIM15 block reset"]
#[inline(always)]
pub fn tim15rst(&self) -> TIM15RST_R {
TIM15RST_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - TIM16 block reset"]
#[inline(always)]
pub fn tim16rst(&self) -> TIM16RST_R {
TIM16RST_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - TIM17 block reset"]
#[inline(always)]
pub fn tim17rst(&self) -> TIM17RST_R {
TIM17RST_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 20 - SPI5 block reset"]
#[inline(always)]
pub fn spi5rst(&self) -> SPI5RST_R {
SPI5RST_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 22 - SAI1 block reset"]
#[inline(always)]
pub fn sai1rst(&self) -> SAI1RST_R {
SAI1RST_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - SAI2 block reset"]
#[inline(always)]
pub fn sai2rst(&self) -> SAI2RST_R {
SAI2RST_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - SAI3 block reset"]
#[inline(always)]
pub fn sai3rst(&self) -> SAI3RST_R {
SAI3RST_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 28 - DFSDM1 block reset"]
#[inline(always)]
pub fn dfsdm1rst(&self) -> DFSDM1RST_R {
DFSDM1RST_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - HRTIM block reset"]
#[inline(always)]
pub fn hrtimrst(&self) -> HRTIMRST_R {
HRTIMRST_R::new(((self.bits >> 29) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM1 block reset"]
#[inline(always)]
pub fn tim1rst(&mut self) -> TIM1RST_W {
TIM1RST_W { w: self }
}
#[doc = "Bit 1 - TIM8 block reset"]
#[inline(always)]
pub fn tim8rst(&mut self) -> TIM8RST_W {
TIM8RST_W { w: self }
}
#[doc = "Bit 4 - USART1 block reset"]
#[inline(always)]
pub fn usart1rst(&mut self) -> USART1RST_W {
USART1RST_W { w: self }
}
#[doc = "Bit 5 - USART6 block reset"]
#[inline(always)]
pub fn usart6rst(&mut self) -> USART6RST_W {
USART6RST_W { w: self }
}
#[doc = "Bit 12 - SPI1 block reset"]
#[inline(always)]
pub fn spi1rst(&mut self) -> SPI1RST_W {
SPI1RST_W { w: self }
}
#[doc = "Bit 13 - SPI4 block reset"]
#[inline(always)]
pub fn spi4rst(&mut self) -> SPI4RST_W {
SPI4RST_W { w: self }
}
#[doc = "Bit 16 - TIM15 block reset"]
#[inline(always)]
pub fn tim15rst(&mut self) -> TIM15RST_W {
TIM15RST_W { w: self }
}
#[doc = "Bit 17 - TIM16 block reset"]
#[inline(always)]
pub fn tim16rst(&mut self) -> TIM16RST_W {
TIM16RST_W { w: self }
}
#[doc = "Bit 18 - TIM17 block reset"]
#[inline(always)]
pub fn tim17rst(&mut self) -> TIM17RST_W {
TIM17RST_W { w: self }
}
#[doc = "Bit 20 - SPI5 block reset"]
#[inline(always)]
pub fn spi5rst(&mut self) -> SPI5RST_W {
SPI5RST_W { w: self }
}
#[doc = "Bit 22 - SAI1 block reset"]
#[inline(always)]
pub fn sai1rst(&mut self) -> SAI1RST_W {
SAI1RST_W { w: self }
}
#[doc = "Bit 23 - SAI2 block reset"]
#[inline(always)]
pub fn sai2rst(&mut self) -> SAI2RST_W {
SAI2RST_W { w: self }
}
#[doc = "Bit 24 - SAI3 block reset"]
#[inline(always)]
pub fn sai3rst(&mut self) -> SAI3RST_W {
SAI3RST_W { w: self }
}
#[doc = "Bit 28 - DFSDM1 block reset"]
#[inline(always)]
pub fn dfsdm1rst(&mut self) -> DFSDM1RST_W {
DFSDM1RST_W { w: self }
}
#[doc = "Bit 29 - HRTIM block reset"]
#[inline(always)]
pub fn hrtimrst(&mut self) -> HRTIMRST_W {
HRTIMRST_W { w: self }
}
}
|
use kind::*;
use square::*;
use castle::Castle;
use castle;
use std::fmt::{Display, Formatter, Result};
#[derive(Eq, Hash, Debug, Copy, Clone, PartialEq)]
pub struct Move {
pub from: Square,
pub to: Square,
pub promote: Kind,
pub castle: Castle,
}
const CASTLE_Q: Move = Move {
from: UNDEFINED_SQUARE,
to: UNDEFINED_SQUARE,
promote: UNKNOWN,
castle: castle::Q,
};
const CASTLE_K: Move = Move {
from: UNDEFINED_SQUARE,
to: UNDEFINED_SQUARE,
promote: UNKNOWN,
castle: castle::K,
};
impl Move {
pub fn new(from: Square, to: Square) -> Self {
Move {
from: from,
to: to,
promote: UNKNOWN,
castle: castle::NONE,
}
}
pub fn promote(from: Square, to: Square, promote: Kind) -> Self {
Move {
from: from,
to: to,
promote: promote,
castle: castle::NONE,
}
}
pub fn parse(input: &str) -> Self {
parse_move(input.as_bytes()).unwrap().1
}
}
impl Display for Move {
fn fmt(&self, f: &mut Formatter) -> Result {
if self.castle != castle::NONE {
return write!(f, "{}", if self.castle == castle::Q {
"O-O-O"
} else {
"O-O"
});
}
write!(f, "{}-{}", self.from, self.to)?;
if self.promote != UNKNOWN {
write!(f, "={}", self.promote)?;
}
Ok(())
}
}
named!(parse_promotion(&[u8]) -> Kind,
complete!(chain!(
char!('=') ~
result: alt!(
value!(KNIGHT, char!('N')) |
value!(BISHOP, char!('B')) |
value!(ROOK, char!('R')) |
value!(QUEEN, char!('Q')) ),
|| result)));
named!(parse_straight(&[u8]) -> Move,
chain!(
from: parse_square ~
alt!(char!('-') | char!(':')) ? ~
to: parse_square ~
promotion: opt!(parse_promotion),
|| Move::promote(from, to, promotion
.unwrap_or(UNKNOWN)))
);
named!(parse_castle(&[u8]) -> Move,
alt!(
complete!(value!(CASTLE_Q, tag!("o-o-o"))) |
complete!(value!(CASTLE_Q, tag!("0-0-0"))) |
complete!(value!(CASTLE_Q, tag!("O-O-O"))) |
value!(CASTLE_K, tag!("o-o")) |
value!(CASTLE_K, tag!("0-0")) |
value!(CASTLE_K, tag!("O-O"))
));
named!(pub parse_move(&[u8]) -> Move,
alt!(parse_straight | parse_castle));
#[cfg(test)]
mod test {
use square::*;
use super::*;
#[test]
fn usual_move() {
let m = Move::new(E2, E4);
assert_eq!(format!("{:?}", m),
"Move { from: Square(52), to: Square(36), promote: Kind(16), castle: NONE }");
}
#[test]
fn promotion_move() {
let m = Move::promote(E2, E4, QUEEN);
assert_eq!(format!("{:?}", m),
"Move { from: Square(52), to: Square(36), promote: Kind(4), castle: NONE }");
}
#[test]
fn parse_usual() {
assert_eq!(format!("{}", Move::parse("e2e4")), "e2-e4");
assert_eq!(format!("{}", Move::parse("a1a8")), "a1-a8");
assert_eq!(format!("{}", Move::parse("c3-f2")), "c3-f2");
assert_eq!(format!("{}", Move::parse("a8:h1")), "a8-h1");
}
#[test]
fn parse_short_castle() {
assert_eq!(format!("{}", Move::parse("O-O")), "O-O");
assert_eq!(format!("{}", Move::parse("0-0")), "O-O");
assert_eq!(format!("{}", Move::parse("o-o")), "O-O");
}
#[test]
fn parse_long_castle() {
assert_eq!(format!("{}", Move::parse("O-O-O")), "O-O-O");
assert_eq!(format!("{}", Move::parse("0-0-0")), "O-O-O");
assert_eq!(format!("{}", Move::parse("o-o-o")), "O-O-O");
}
#[test]
fn parse_promotion() {
assert_eq!(format!("{}", Move::parse("e2-e4=Q")), "e2-e4=Q");
}
}
|
use std::{fmt, mem, usize};
use std::iter::IntoIterator;
use std::ops::{Index, IndexMut};
use token::Token;
/// A preallocated chunk of memory for storing objects of the same type.
pub struct Slab<T> {
// Chunk of memory
entries: Vec<Entry<T>>,
// Number of elements currently in the slab
len: usize,
// The token offset
off: usize,
// Offset of the next available slot in the slab. Set to the slab's
// capacity when the slab is full.
nxt: usize,
}
const MAX: usize = usize::MAX;
unsafe impl<T> Send for Slab<T> where T: Send {}
// TODO: Once NonZero lands, use it to optimize the layout
impl<T> Slab<T> {
pub fn new(cap: usize) -> Slab<T> {
Slab::new_starting_at(Token(0), cap)
}
pub fn new_starting_at(offset: Token, cap: usize) -> Slab<T> {
assert!(cap <= MAX, "capacity too large");
// TODO:
// - Rename to with_capacity
// - Use a power of 2 capacity
// - Ensure that mem size is less than usize::MAX
let entries = Vec::with_capacity(cap);
Slab {
entries: entries,
len: 0,
off: offset.as_usize(),
nxt: 0,
}
}
#[inline]
pub fn count(&self) -> usize {
self.len as usize
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn remaining(&self) -> usize {
(self.entries.capacity() - self.len) as usize
}
#[inline]
pub fn has_remaining(&self) -> bool {
self.remaining() > 0
}
#[inline]
pub fn contains(&self, idx: Token) -> bool {
if idx.as_usize() < self.off {
return false;
}
let idx = self.token_to_idx(idx);
if idx < self.entries.len() {
return self.entries[idx].in_use();
}
false
}
pub fn get(&self, idx: Token) -> Option<&T> {
let idx = self.token_to_idx(idx);
if idx <= MAX {
if idx < self.entries.len() {
return self.entries[idx].val.as_ref();
}
}
None
}
pub fn get_mut(&mut self, idx: Token) -> Option<&mut T> {
let idx = self.token_to_idx(idx);
if idx <= MAX {
if idx < self.entries.len() {
return self.entries[idx].val.as_mut();
}
}
None
}
pub fn insert(&mut self, val: T) -> Result<Token, T> {
let idx = self.nxt;
if idx == self.entries.len() {
// Using an uninitialized entry
if idx == self.entries.capacity() {
// No more capacity
debug!("slab out of capacity; cap={}", self.entries.capacity());
return Err(val);
}
self.entries.push(Entry {
nxt: MAX,
val: Some(val),
});
self.len += 1;
self.nxt = self.len;
}
else {
self.len += 1;
self.nxt = self.entries[idx].put(val);
}
Ok(self.idx_to_token(idx))
}
/// Releases the given slot
pub fn remove(&mut self, idx: Token) -> Option<T> {
// Cast to usize
let idx = self.token_to_idx(idx);
if idx > self.entries.len() {
return None;
}
match self.entries[idx].remove(self.nxt) {
Some(v) => {
self.nxt = idx;
self.len -= 1;
Some(v)
}
None => None
}
}
pub fn replace(&mut self, idx: Token, t : T) -> Option<T> {
let idx = self.token_to_idx(idx);
if idx > self.entries.len() {
return None;
}
if idx <= MAX {
if idx < self.entries.len() {
let val = self.entries[idx].val.as_mut().unwrap();
return Some(mem::replace(val, t))
}
}
None
}
pub fn iter(&self) -> SlabIter<T> {
SlabIter {
slab: self,
cur_idx: 0,
yielded: 0
}
}
pub fn iter_mut(&mut self) -> SlabMutIter<T> {
SlabMutIter { iter: self.iter() }
}
#[inline]
fn validate_idx(&self, idx: usize) -> usize {
if idx < self.entries.len() {
return idx;
}
panic!("invalid index {} -- greater than capacity {}", idx, self.entries.capacity());
}
fn token_to_idx(&self, token: Token) -> usize {
token.as_usize() - self.off
}
fn idx_to_token(&self, idx: usize) -> Token {
Token(idx as usize + self.off)
}
}
impl<T> Index<Token> for Slab<T> {
type Output = T;
fn index<'a>(&'a self, idx: Token) -> &'a T {
let idx = self.token_to_idx(idx);
let idx = self.validate_idx(idx);
self.entries[idx].val.as_ref()
.expect("invalid index")
}
}
impl<T> IndexMut<Token> for Slab<T> {
fn index_mut<'a>(&'a mut self, idx: Token) -> &'a mut T {
let idx = self.token_to_idx(idx);
let idx = self.validate_idx(idx);
self.entries[idx].val.as_mut()
.expect("invalid index")
}
}
impl<T> fmt::Debug for Slab<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Slab {{ len: {}, cap: {} }}", self.len, self.entries.capacity())
}
}
// Holds the values in the slab.
struct Entry<T> {
nxt: usize,
val: Option<T>,
}
impl<T> Entry<T> {
#[inline]
fn put(&mut self, val: T) -> usize{
let ret = self.nxt;
self.val = Some(val);
ret
}
fn remove(&mut self, nxt: usize) -> Option<T> {
if self.in_use() {
self.nxt = nxt;
self.val.take()
} else {
None
}
}
#[inline]
fn in_use(&self) -> bool {
self.val.is_some()
}
}
pub struct SlabIter<'a, T: 'a> {
slab: &'a Slab<T>,
cur_idx: usize,
yielded: usize
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.yielded < self.slab.len {
match self.slab.entries[self.cur_idx].val {
Some(ref v) => {
self.cur_idx += 1;
self.yielded += 1;
return Some(v);
}
None => {
self.cur_idx += 1;
}
}
}
None
}
}
pub struct SlabMutIter<'a, T: 'a> {
iter: SlabIter<'a, T>,
}
impl<'a, T> Iterator for SlabMutIter<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
unsafe { mem::transmute(self.iter.next()) }
}
}
impl<'a, T> IntoIterator for &'a Slab<T> {
type Item = &'a T;
type IntoIter = SlabIter<'a, T>;
fn into_iter(self) -> SlabIter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Slab<T> {
type Item = &'a mut T;
type IntoIter = SlabMutIter<'a, T>;
fn into_iter(self) -> SlabMutIter<'a, T> {
self.iter_mut()
}
}
#[cfg(test)]
mod tests {
use super::Slab;
use {Token};
#[test]
fn test_insertion() {
let mut slab = Slab::new(1);
let token = slab.insert(10).ok().expect("Failed to insert");
assert_eq!(slab[token], 10);
}
#[test]
fn test_repeated_insertion() {
let mut slab = Slab::new(10);
for i in (0..10) {
let token = slab.insert(i + 10).ok().expect("Failed to insert");
assert_eq!(slab[token], i + 10);
}
slab.insert(20).err().expect("Inserted when full");
}
#[test]
fn test_repeated_insertion_and_removal() {
let mut slab = Slab::new(10);
let mut tokens = vec![];
for i in (0..10) {
let token = slab.insert(i + 10).ok().expect("Failed to insert");
tokens.push(token);
assert_eq!(slab[token], i + 10);
}
for &i in tokens.iter() {
slab.remove(i);
}
slab.insert(20).ok().expect("Failed to insert in newly empty slab");
}
#[test]
fn test_insertion_when_full() {
let mut slab = Slab::new(1);
slab.insert(10).ok().expect("Failed to insert");
slab.insert(10).err().expect("Inserted into a full slab");
}
#[test]
fn test_removal_is_successful() {
let mut slab = Slab::new(1);
let t1 = slab.insert(10).ok().expect("Failed to insert");
slab.remove(t1);
let t2 = slab.insert(20).ok().expect("Failed to insert");
assert_eq!(slab[t2], 20);
}
#[test]
fn test_mut_retrieval() {
let mut slab = Slab::new(1);
let t1 = slab.insert("foo".to_string()).ok().expect("Failed to insert");
slab[t1].push_str("bar");
assert_eq!(&slab[t1][..], "foobar");
}
#[test]
#[should_panic]
fn test_reusing_slots_1() {
let mut slab = Slab::new(16);
let t0 = slab.insert(123).unwrap();
let t1 = slab.insert(456).unwrap();
assert!(slab.count() == 2);
assert!(slab.remaining() == 14);
slab.remove(t0);
assert!(slab.count() == 1, "actual={}", slab.count());
assert!(slab.remaining() == 15);
slab.remove(t1);
assert!(slab.count() == 0);
assert!(slab.remaining() == 16);
let _ = slab[t1];
}
#[test]
fn test_reusing_slots_2() {
let mut slab = Slab::new(16);
let t0 = slab.insert(123).unwrap();
assert!(slab[t0] == 123);
assert!(slab.remove(t0) == Some(123));
let t0 = slab.insert(456).unwrap();
assert!(slab[t0] == 456);
let t1 = slab.insert(789).unwrap();
assert!(slab[t0] == 456);
assert!(slab[t1] == 789);
assert!(slab.remove(t0).unwrap() == 456);
assert!(slab.remove(t1).unwrap() == 789);
assert!(slab.count() == 0);
}
#[test]
#[should_panic]
fn test_accessing_out_of_bounds() {
let slab = Slab::<usize>::new(16);
slab[Token(0)];
}
#[test]
fn test_contains() {
let mut slab = Slab::new_starting_at(Token(5),16);
assert!(!slab.contains(Token(0)));
let tok = slab.insert(111).unwrap();
assert!(slab.contains(tok));
}
#[test]
fn test_iter() {
let mut slab: Slab<u32> = Slab::new_starting_at(Token(0), 4);
for i in (0..4) {
slab.insert(i).unwrap();
}
let vals: Vec<u32> = slab.iter().map(|r| *r).collect();
assert_eq!(vals, vec![0, 1, 2, 3]);
slab.remove(Token(1));
let vals: Vec<u32> = slab.iter().map(|r| *r).collect();
assert_eq!(vals, vec![0, 2, 3]);
}
#[test]
fn test_iter_mut() {
let mut slab: Slab<u32> = Slab::new_starting_at(Token(0), 4);
for i in (0..4) {
slab.insert(i).unwrap();
}
for e in slab.iter_mut() {
*e = *e + 1;
}
let vals: Vec<u32> = slab.iter().map(|r| *r).collect();
assert_eq!(vals, vec![1, 2, 3, 4]);
slab.remove(Token(2));
for e in slab.iter_mut() {
*e = *e + 1;
}
let vals: Vec<u32> = slab.iter().map(|r| *r).collect();
assert_eq!(vals, vec![2, 3, 5]);
}
#[test]
fn test_get() {
let mut slab = Slab::new(16);
let tok = slab.insert(5).unwrap();
assert_eq!(slab.get(tok), Some(&5));
assert_eq!(slab.get(Token(1)), None);
assert_eq!(slab.get(Token(23)), None);
}
#[test]
fn test_get_mut() {
let mut slab = Slab::new(16);
let tok = slab.insert(5u32).unwrap();
{
let mut_ref = slab.get_mut(tok).unwrap();
assert_eq!(*mut_ref, 5);
*mut_ref = 12;
}
assert_eq!(slab[tok], 12);
assert_eq!(slab.get_mut(Token(1)), None);
assert_eq!(slab.get_mut(Token(23)), None);
}
}
|
use crate::datastore::RECENT_FILES_IN_MEMORY;
use crate::stdio_server::handler::CachedPreviewImpl;
use crate::stdio_server::provider::{ClapProvider, Context};
use anyhow::Result;
use parking_lot::Mutex;
use paths::AbsPathBuf;
use printer::Printer;
use serde_json::{json, Value};
use std::sync::Arc;
use types::{ClapItem, MatchedItem, RankCalculator, Score};
use super::BaseArgs;
#[derive(Debug, Clone)]
pub struct RecentFilesProvider {
args: BaseArgs,
printer: Printer,
lines: Arc<Mutex<Vec<MatchedItem>>>,
}
impl RecentFilesProvider {
pub async fn new(ctx: &Context) -> Result<Self> {
let args = ctx.parse_provider_args().await?;
let icon = if ctx.env.icon.enabled() {
icon::Icon::Enabled(icon::IconKind::File)
} else {
icon::Icon::Null
};
let printer = Printer::new(ctx.env.display_winwidth, icon);
Ok(Self {
args,
printer,
lines: Default::default(),
})
}
fn process_query(
self,
cwd: AbsPathBuf,
query: String,
preview_size: Option<usize>,
lnum: usize,
) -> Result<Value> {
let cwd = cwd.to_string();
let mut recent_files = RECENT_FILES_IN_MEMORY.lock();
let ranked = if query.is_empty() {
// Sort the initial list according to the cwd.
//
// This changes the order of existing recent file entries.
recent_files.sort_by_cwd(&cwd);
let mut cwd = cwd.clone();
cwd.push(std::path::MAIN_SEPARATOR);
let rank_calculator = RankCalculator::default();
recent_files
.entries
.iter()
.map(|entry| {
let item: Arc<dyn ClapItem> = Arc::new(entry.fpath.clone());
// frecent_score will not be larger than i32::MAX.
let score = entry.frecent_score as Score;
let rank = rank_calculator.calculate_rank(score, 0, 0, item.raw_text().len());
let mut matched_item = MatchedItem::new(item, rank, Default::default());
matched_item
.output_text
.replace(entry.fpath.replacen(&cwd, "", 1));
matched_item
})
.collect::<Vec<_>>()
} else {
recent_files.filter_on_query(&query, cwd.clone())
};
let processed = recent_files.len();
let matched = ranked.len();
drop(recent_files);
// process the new preview
let preview = match (preview_size, ranked.get(lnum - 1)) {
(Some(size), Some(new_entry)) => {
let new_curline = new_entry.display_text().to_string();
if let Ok((lines, fname)) =
crate::previewer::preview_file(new_curline, size, self.printer.line_width)
{
Some(json!({ "lines": lines, "fname": fname }))
} else {
None
}
}
_ => None,
};
let printer::DisplayLines {
lines,
indices,
truncated_map,
icon_added,
} = self
.printer
.to_display_lines(ranked.iter().take(200).cloned().collect());
let mut cwd = cwd;
cwd.push(std::path::MAIN_SEPARATOR);
let lines = lines
.into_iter()
.map(|abs_path| abs_path.replacen(&cwd, "", 1))
.collect::<Vec<_>>();
// The indices are empty on the empty query.
let indices = indices
.into_iter()
.filter(|i| !i.is_empty())
.collect::<Vec<_>>();
let mut value = json!({
"lines": lines,
"indices": indices,
"matched": matched,
"processed": processed,
"icon_added": icon_added,
"preview": preview,
});
if !truncated_map.is_empty() {
value
.as_object_mut()
.expect("Value is constructed as an Object")
.insert("truncated_map".into(), json!(truncated_map));
}
let mut lines = self.lines.lock();
*lines = ranked;
Ok(value)
}
}
#[async_trait::async_trait]
impl ClapProvider for RecentFilesProvider {
async fn on_initialize(&mut self, ctx: &mut Context) -> Result<()> {
if self.args.query.is_none() {
let preview_size = if ctx.env.preview_enabled {
Some(ctx.preview_size().await?)
} else {
None
};
let response =
self.clone()
.process_query(ctx.cwd.clone(), "".into(), preview_size, 1)?;
ctx.vim
.exec("clap#state#process_response_on_typed", response)?;
} else {
ctx.handle_base_args(&self.args).await?;
}
Ok(())
}
async fn on_move(&mut self, ctx: &mut Context) -> Result<()> {
let lnum = ctx.vim.display_getcurlnum().await?;
let maybe_curline = self
.lines
.lock()
.get(lnum - 1)
.map(|r| r.item.raw_text().to_string());
if let Some(curline) = maybe_curline {
let preview_height = ctx.preview_height().await?;
let (preview_target, preview) = CachedPreviewImpl::new(curline, preview_height, ctx)?
.get_preview()
.await?;
ctx.preview_manager.reset_scroll();
ctx.render_preview(preview)?;
ctx.preview_manager.set_preview_target(preview_target);
}
Ok(())
}
async fn on_typed(&mut self, ctx: &mut Context) -> Result<()> {
let query = ctx.vim.input_get().await?;
let response = tokio::task::spawn_blocking({
let query = query.clone();
let recent_files = self.clone();
let cwd = ctx.cwd.clone();
let preview_size = if ctx.env.preview_enabled {
Some(ctx.preview_size().await?)
} else {
None
};
let lnum = ctx.vim.display_getcurlnum().await?;
move || recent_files.process_query(cwd, query, preview_size, lnum)
})
.await??;
let current_query = ctx.vim.input_get().await?;
if current_query == query {
ctx.vim
.exec("clap#state#process_response_on_typed", response)?;
}
Ok(())
}
}
|
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
pub struct Config {
pub db_url: String,
pub uid: u32,
pub gid: u32,
pub pid_file: String,
pub working_dir: String,
pub socket: String,
}
#[derive(Serialize, Deserialize)]
pub enum Action {
Stop,
Alive,
Subscribe,
}
#[derive(Serialize, Deserialize)]
pub struct Command {
pub action: Action,
pub originator: String,
pub list_name: Option<String>,
pub data: Option<String>,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct DaemonState {
pub config: Config,
pub start_time: chrono::DateTime<chrono::Utc>,
pub server_version: String,
}
pub struct Subscription {
pub email: String,
pub uuid: String,
}
impl DaemonState {
pub fn new(
config: &Config,
start_time: &chrono::DateTime<chrono::Utc>,
server_version: &str,
) -> DaemonState {
DaemonState {
config: config.clone(),
start_time: *start_time,
server_version: server_version.to_string(),
}
}
}
|
use{
crate::{
structs::{CustomerData,DriverData,RecordInstruction,SingleInstruction}
}
};
pub const DUMMY_TX_ID: &str = "0000000000000000000000000000000000000000000";
pub const DUMMY_CREATED_ON: &str = "0000000000000000";
pub const DUMMY_LATLONG: &str="00000000";
pub const DUMMY_COST: &str="000000000000";
pub const DUMMY_ADDRESS: &str = "00000000000000000000000000000000000000000000";
pub const DUMMY_DISTANCE : &str="0000";
pub const KM_RATE: f32=0.01 ; //Sol
pub const DUMMY_CUSTOMER_CONFIRMED_RIDES: &str="0000";
pub const DUMMY_INSTRUCTION: &str = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
pub fn get_init_acccount() -> CustomerData {
return CustomerData{
profile_hash:String::from(DUMMY_TX_ID),updated_on:String::from(DUMMY_CREATED_ON),from_lat:String::from(DUMMY_LATLONG)
,to_lat:String::from(DUMMY_LATLONG),from_long:String::from(DUMMY_LATLONG),to_long:String::from(DUMMY_LATLONG),
distance:String::from(DUMMY_DISTANCE),
final_cost:String::from(DUMMY_COST),driver_address_1:String::from(DUMMY_ADDRESS),cost_1:String::from(DUMMY_COST)
,driver_address_2:String::from(DUMMY_ADDRESS),cost_2:String::from(DUMMY_COST)
,driver_address_3:String::from(DUMMY_ADDRESS),cost_3:String::from(DUMMY_COST)
,driver_address_4:String::from(DUMMY_ADDRESS),cost_4:String::from(DUMMY_COST)
,cost_1_max:String::from(DUMMY_COST),cost_2_max:String::from(DUMMY_COST),cost_3_max:String::from(DUMMY_COST),cost_4_max:String::from(DUMMY_COST)
,driver_select:String::from("0"),driver_confirm:String::from("0")
,to_pay:String::from(DUMMY_COST)
,ride_state:String::from("0") // 0 not started , 1 as pending , 2 as started, 3 as end, 4 as paid
,driver_pub_key:String::from(DUMMY_ADDRESS)
};
}
pub fn get_init_driver() -> DriverData {
return DriverData{profile_hash:String::from(DUMMY_TX_ID),
updated_on:String::from(DUMMY_CREATED_ON),
from_lat:String::from(DUMMY_LATLONG)
,to_lat:String::from(DUMMY_LATLONG),
from_long:String::from(DUMMY_LATLONG),
to_long:String::from(DUMMY_LATLONG),
dist:String::from(DUMMY_DISTANCE),
cost:String::from(DUMMY_COST),
customer_1:String::from(DUMMY_ADDRESS),customer_1_confirm:String::from("0"),
customer_2:String::from(DUMMY_ADDRESS),customer_2_confirm:String::from("0"),
customer_3:String::from(DUMMY_ADDRESS),customer_3_confirm:String::from("0"),
//customer_confirmed_rides:String::from(DUMMY_CUSTOMER_CONFIRMED_RIDES),
customer_rides_to_finish:String::from(DUMMY_CUSTOMER_CONFIRMED_RIDES),
customer_rides_paid:String::from(DUMMY_CUSTOMER_CONFIRMED_RIDES),
ride_state:String::from("0")
};
}
pub fn get_empty_instruction() -> RecordInstruction {
return RecordInstruction{
profile_hash:String::from(DUMMY_TX_ID),
record_type:String::from("0"),
user_type:String::from("0"),
from_lat:String::from(DUMMY_LATLONG)
,to_lat:String::from(DUMMY_LATLONG),
// from_long:String::from(DUMMY_LATLONG),
// to_long:String::from(DUMMY_LATLONG),
// distance:String::from(DUMMY_DISTANCE),
// customer_count:String::from("0"),
updated_on:String::from(DUMMY_CREATED_ON),
// driver_address:String::from(DUMMY_ADDRESS),
// customer_address:String::from(DUMMY_ADDRESS)
};
}
pub fn get_empty_single_instruction() -> SingleInstruction {
return SingleInstruction {
full_instruction: String::from(DUMMY_INSTRUCTION)
}
}
pub fn pad_cost(num: f32, pad_str: &str)-> String{
let pad_string: String=String::from(pad_str);
let length: usize=pad_string.len();
let num_text: String=num.to_string();
let mut nt2 ;
if num_text.len()<length {
nt2=String::from(&String::from(pad_str)[..length-num_text.len()]);
nt2.push_str(&num_text[..]);
println!(" {}" ,nt2);
}else{
nt2=String::from(&num_text[..length]);
println!(" {}" ,nt2);
}
return nt2;
} |
#![no_main]
#![no_std]
extern crate bme280;
extern crate cortex_m;
extern crate cortex_m_rt as rt;
extern crate cortex_m_rtfm as rtfm;
extern crate embedded_hal;
extern crate heapless;
extern crate il3820;
#[cfg(not(test))]
extern crate panic_semihosting;
extern crate portable;
extern crate pwm_speaker;
extern crate stm32f103xx_hal as hal;
extern crate stm32f103xx_rtc as rtc;
use hal::prelude::*;
use heapless::consts::*;
use heapless::Vec;
use portable::datetime::DateTime;
use portable::{alarm, button, datetime, ui};
use pwm_speaker::songs::SO_WHAT;
use rt::{exception, ExceptionFrame};
use rtfm::{app, Resource, Threshold};
mod msg_queue;
mod sound;
type I2C = hal::i2c::BlockingI2c<
hal::stm32f103xx::I2C1,
(
hal::gpio::gpiob::PB6<hal::gpio::Alternate<hal::gpio::OpenDrain>>,
hal::gpio::gpiob::PB7<hal::gpio::Alternate<hal::gpio::OpenDrain>>,
),
>;
type Button0Pin = hal::gpio::gpioa::PA6<hal::gpio::Input<hal::gpio::PullUp>>;
type Button1Pin = hal::gpio::gpioa::PA7<hal::gpio::Input<hal::gpio::PullUp>>;
type Button2Pin = hal::gpio::gpiob::PB0<hal::gpio::Input<hal::gpio::PullUp>>;
type Button3Pin = hal::gpio::gpiob::PB1<hal::gpio::Input<hal::gpio::PullUp>>;
type Spi = hal::spi::Spi<
hal::stm32f103xx::SPI2,
(
hal::gpio::gpiob::PB13<hal::gpio::Alternate<hal::gpio::PushPull>>,
hal::gpio::gpiob::PB14<hal::gpio::Input<hal::gpio::Floating>>,
hal::gpio::gpiob::PB15<hal::gpio::Alternate<hal::gpio::PushPull>>,
),
>;
type EPaperDisplay = il3820::Il3820<
Spi,
hal::gpio::gpiob::PB12<hal::gpio::Output<hal::gpio::PushPull>>,
hal::gpio::gpioa::PA8<hal::gpio::Output<hal::gpio::PushPull>>,
hal::gpio::gpioa::PA9<hal::gpio::Output<hal::gpio::PushPull>>,
hal::gpio::gpioa::PA10<hal::gpio::Input<hal::gpio::Floating>>,
>;
app! {
device: hal::stm32f103xx,
resources: {
static RTC_DEV: rtc::Rtc;
static BME280: bme280::BME280<I2C, hal::delay::Delay>;
static ALARM_MANAGER: alarm::AlarmManager;
static SOUND: sound::Sound;
static BUTTON0: button::Button<Button0Pin>;
static BUTTON1: button::Button<Button1Pin>;
static BUTTON2: button::Button<Button2Pin>;
static BUTTON3: button::Button<Button3Pin>;
static DISPLAY: EPaperDisplay;
static SPI: Spi;
static UI: ui::Model;
static FULL_UPDATE: bool;
static MSG_QUEUE: msg_queue::MsgQueue;
},
tasks: {
EXTI1: {
path: render,
resources: [UI, DISPLAY, SPI, FULL_UPDATE],
priority: 1,
},
EXTI2: {
path: msgs,
resources: [UI, MSG_QUEUE, RTC_DEV, FULL_UPDATE, ALARM_MANAGER],
priority: 2,
},
RTC: {
path: handle_rtc,
resources: [RTC_DEV, BME280, ALARM_MANAGER, SOUND, MSG_QUEUE],
priority: 3,
},
TIM3: {
path: one_khz,
resources: [BUTTON0, BUTTON1, BUTTON2, BUTTON3, SOUND, MSG_QUEUE],
priority: 4,
},
},
}
fn init(mut p: init::Peripherals) -> init::LateResources {
let mut flash = p.device.FLASH.constrain();
let mut rcc = p.device.RCC.constrain();
let mut afio = p.device.AFIO.constrain(&mut rcc.apb2);
let clocks = rcc.cfgr.freeze(&mut flash.acr);
let mut gpioa = p.device.GPIOA.split(&mut rcc.apb2);
let mut gpiob = p.device.GPIOB.split(&mut rcc.apb2);
let c1 = gpioa.pa0.into_alternate_push_pull(&mut gpioa.crl);
let mut pwm = p
.device
.TIM2
.pwm(c1, &mut afio.mapr, 440.hz(), clocks, &mut rcc.apb1);
pwm.enable();
let speaker = pwm_speaker::Speaker::new(pwm, clocks);
let button0_pin = gpioa.pa6.into_pull_up_input(&mut gpioa.crl);
let button1_pin = gpioa.pa7.into_pull_up_input(&mut gpioa.crl);
let button2_pin = gpiob.pb0.into_pull_up_input(&mut gpiob.crl);
let button3_pin = gpiob.pb1.into_pull_up_input(&mut gpiob.crl);
let mut timer = hal::timer::Timer::tim3(p.device.TIM3, 1.khz(), clocks, &mut rcc.apb1);
timer.listen(hal::timer::Event::Update);
p.core.NVIC.enable(hal::stm32f103xx::Interrupt::TIM3);
let mut rtc = rtc::Rtc::new(p.device.RTC, &mut rcc.apb1, &mut p.device.PWR);
if rtc.get_cnt() < 100 {
let today = DateTime {
year: 2018,
month: 9,
day: 1,
hour: 23,
min: 15,
sec: 40,
day_of_week: datetime::DayOfWeek::Wednesday,
};
if let Some(epoch) = today.to_epoch() {
rtc.set_cnt(epoch);
}
}
rtc.enable_second_interrupt(&mut p.core.NVIC);
use alarm::Mode;
let mut alarm_manager = alarm::AlarmManager::default();
alarm_manager.alarms[0].is_enable = true;
alarm_manager.alarms[0].set_hour(7);
alarm_manager.alarms[0].set_min(25);
alarm_manager.alarms[0].mode = Mode::MONDAY | Mode::TUESDAY | Mode::THURSDAY | Mode::FRIDAY;
alarm_manager.alarms[1].is_enable = true;
alarm_manager.alarms[1].set_hour(8);
alarm_manager.alarms[1].set_min(15);
alarm_manager.alarms[1].mode = Mode::WEDNESDAY;
alarm_manager.alarms[4].set_hour(13);
alarm_manager.alarms[4].set_min(37);
alarm_manager.alarms[4].mode = Mode::all() - Mode::ONE_TIME;
let mut delay = hal::delay::Delay::new(p.core.SYST, clocks);
let sck = gpiob.pb13.into_alternate_push_pull(&mut gpiob.crh);
let miso = gpiob.pb14;
let mosi = gpiob.pb15.into_alternate_push_pull(&mut gpiob.crh);
let mut spi = hal::spi::Spi::spi2(
p.device.SPI2,
(sck, miso, mosi),
il3820::MODE,
4.mhz(),
clocks,
&mut rcc.apb1,
);
let mut il3820 = il3820::Il3820::new(
&mut spi,
gpiob.pb12.into_push_pull_output(&mut gpiob.crh),
gpioa.pa8.into_push_pull_output(&mut gpioa.crh),
gpioa.pa9.into_push_pull_output(&mut gpioa.crh),
gpioa.pa10.into_floating_input(&mut gpioa.crh),
&mut delay,
);
il3820.clear(&mut spi).unwrap();
let pb6 = gpiob.pb6.into_alternate_open_drain(&mut gpiob.crl);
let pb7 = gpiob.pb7.into_alternate_open_drain(&mut gpiob.crl);
let i2c = hal::i2c::I2c::i2c1(
p.device.I2C1,
(pb6, pb7),
&mut afio.mapr,
hal::i2c::Mode::Fast {
frequency: 400_000,
duty_cycle: hal::i2c::DutyCycle::Ratio16to9,
},
clocks,
&mut rcc.apb1,
);
let i2c = hal::i2c::blocking_i2c(i2c, clocks, 100, 100, 100, 100);
let mut bme280 = bme280::BME280::new_primary(i2c, delay);
bme280.init().unwrap();
let mut msg_queue = msg_queue::MsgQueue::new();
msg_queue.push(ui::Msg::AlarmManager(alarm_manager.clone()));
init::LateResources {
RTC_DEV: rtc,
BME280: bme280,
SOUND: sound::Sound::new(speaker),
BUTTON0: button::Button::new(button0_pin),
BUTTON1: button::Button::new(button1_pin),
BUTTON2: button::Button::new(button2_pin),
BUTTON3: button::Button::new(button3_pin),
DISPLAY: il3820,
SPI: spi,
UI: ui::Model::init(),
FULL_UPDATE: false,
MSG_QUEUE: msg_queue,
ALARM_MANAGER: alarm_manager,
}
}
pub fn msgs(t: &mut rtfm::Threshold, mut r: EXTI2::Resources) {
loop {
let msgs = r.MSG_QUEUE.claim_mut(t, |q, _| q.get());
if msgs.is_empty() {
break;
}
let cmds: Vec<_, U16> = msgs.into_iter().flat_map(|msg| r.UI.update(msg)).collect();
for cmd in cmds {
use ui::Cmd::*;
match cmd {
UpdateRtc(dt) => if let Some(epoch) = dt.to_epoch() {
r.RTC_DEV.claim_mut(t, |rtc, _| {
let _ = rtc.set_cnt(epoch);
});
r.MSG_QUEUE
.claim_mut(t, |q, _| q.push(ui::Msg::DateTime(dt)));
},
UpdateAlarm(alarm, i) => {
let manager = r.ALARM_MANAGER.claim_mut(t, |m, _| {
m.alarms[i] = alarm;
m.clone()
});
r.MSG_QUEUE
.claim_mut(t, |q, _| q.push(ui::Msg::AlarmManager(manager)));
}
FullUpdate => *r.FULL_UPDATE = true,
}
}
}
rtfm::set_pending(hal::stm32f103xx::Interrupt::EXTI1);
}
fn render(t: &mut rtfm::Threshold, mut r: EXTI1::Resources) {
while r.DISPLAY.is_busy() {}
let model = r.UI.claim(t, |model, _| model.clone());
let display = model.view();
let full_update = r.FULL_UPDATE.claim_mut(t, |fu, _| {
let full_update = *fu;
*fu = false;
full_update
});
if full_update {
r.DISPLAY.set_full();
}
r.DISPLAY.set_display(&mut *r.SPI, &display).unwrap();
r.DISPLAY.update(&mut *r.SPI).unwrap();
r.DISPLAY.set_partial();
}
fn handle_rtc(t: &mut rtfm::Threshold, mut r: RTC::Resources) {
r.RTC_DEV.clear_second_interrupt();
r.RTC_DEV.sync();
let datetime = DateTime::new(r.RTC_DEV.get_cnt());
if datetime.sec == 0 && r.ALARM_MANAGER.must_ring(&datetime) {
r.SOUND
.claim_mut(t, |alarm, _t| alarm.play(&SO_WHAT, 10 * 60));
let manager = r.ALARM_MANAGER.clone();
r.MSG_QUEUE
.claim_mut(t, |q, _| q.push(ui::Msg::AlarmManager(manager)));
}
r.MSG_QUEUE
.claim_mut(t, |q, _| q.push(ui::Msg::DateTime(datetime)));
let measurements = r.BME280.measure().unwrap();
let measurements = ::ui::Environment {
pressure: measurements.pressure as u32,
temperature: (measurements.temperature * 100.) as i16,
humidity: measurements.humidity as u8,
};
r.MSG_QUEUE
.claim_mut(t, |q, _| q.push(ui::Msg::Environment(measurements)));
}
fn one_khz(_t: &mut rtfm::Threshold, mut r: TIM3::Resources) {
unsafe {
(*hal::stm32f103xx::TIM3::ptr())
.sr
.modify(|_, w| w.uif().clear_bit());
};
if let button::Event::Pressed = r.BUTTON0.poll() {
r.SOUND.stop();
r.MSG_QUEUE.push(ui::Msg::ButtonCancel);
}
if let button::Event::Pressed = r.BUTTON1.poll() {
r.MSG_QUEUE.push(ui::Msg::ButtonMinus);
}
if let button::Event::Pressed = r.BUTTON2.poll() {
r.MSG_QUEUE.push(ui::Msg::ButtonPlus);
}
if let button::Event::Pressed = r.BUTTON3.poll() {
r.MSG_QUEUE.push(ui::Msg::ButtonOk);
}
r.SOUND.poll();
}
fn idle() -> ! {
loop {
rtfm::wfi();
}
}
#[exception]
fn HardFault(ef: &ExceptionFrame) -> ! {
panic!("{:#?}", ef);
}
#[exception]
fn DefaultHandler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
}
|
use std::collections::HashMap;
use std::net::{SocketAddr, UdpSocket};
use std::sync::{Arc, mpsc, Mutex};
use std::thread;
use std::time::Instant;
use crate::event::NetworkEvent;
use crate::event::core::ShutdownEvent;
use crate::network::MAX_PACKET_SIZE;
use crate::network::connection_data::{
ConnectionData,
PING_SMOOTHING,
wrapped_distance,
};
use crate::network::packet_header::PacketHeader;
pub fn network_interface_receive_thread(
socket: UdpSocket,
receive_queue: mpsc::Sender<(SocketAddr, Box<dyn NetworkEvent>)>,
connections: Arc<Mutex<HashMap<SocketAddr, ConnectionData>>>,
) {
log!("{} started.", thread::current().name().unwrap());
loop {
let (sender, events) = if let Some(complete_payload) = receive_events(&socket, connections.clone()) {
complete_payload
} else {
continue
};
if sender == socket.local_addr().unwrap() {
if events.iter().any(|e| e.as_any().is::<ShutdownEvent>()) {
log!("{} received a shutdown event.", thread::current().name().unwrap());
break;
}
}
for event in events {
receive_queue.send((sender, event)).unwrap();
}
}
log!("{} exiting.", thread::current().name().unwrap());
}
fn receive_events(
socket: &UdpSocket,
connections: Arc<Mutex<HashMap<SocketAddr, ConnectionData>>>,
) -> Option<(SocketAddr, Vec<Box<dyn NetworkEvent>>)> {
let mut buffer = vec![0u8; MAX_PACKET_SIZE];
let (size, sender) = match socket.recv_from(&mut buffer) {
Ok(packet_info) => packet_info,
Err(error) => {
log!(ERROR, "{}: Could not receive packet: {:?}", thread::current().name().unwrap(), error);
return None;
}
};
let from_self = sender == socket.local_addr().unwrap();
buffer.truncate(size);
let (header, payload) = match decode_packet(&buffer) {
Ok(packet) => packet,
Err(error) => {
log!(ERROR, "{}: Received a bad header from {}: {:?}", thread::current().name().unwrap(), sender, error);
return None;
},
};
let mut connections_guard = connections.lock().unwrap();
let decodable_events = if !from_self {
let from_new_sender = !connections_guard.contains_key(&sender);
// Setup new connection if necessary
let mut connection_data = connections_guard
.entry(sender)
.or_insert(ConnectionData::new());
// Offset new connection send times by half a send period
if from_new_sender {
connection_data.send_accumulator += 500_000_000 / connection_data.frequency as u128;
}
// Measure ping
let now = Instant::now();
let mut removed_indices = 0;
for i in 0..connection_data.packet_times.len() {
let current_index = i - removed_indices;
let (sequence, send_time) = connection_data.packet_times[current_index];
if header.acked(&[sequence]) {
const EMA_WEIGHT: f32 = 2.0 / (PING_SMOOTHING as f32 + 1.0);
let new_ping = (now - send_time).as_nanos() as f32 / 1_000_000.0;
connection_data.ping = new_ping * EMA_WEIGHT + (1.0 - EMA_WEIGHT) * connection_data.ping;
connection_data.packet_times.remove(current_index);
removed_indices += 1;
}
}
// Check for newly acked events
let mut removed_indices = 0;
for i in 0..connection_data.unacked_events.len() {
let current_index = i - removed_indices;
let (ref sequences, _, _) = connection_data.unacked_events[current_index];
if header.acked(sequences) {
connection_data.unacked_events.remove(current_index);
removed_indices += 1;
}
}
// Ignore the payload if we're out of ack range
if wrapped_distance(header.sequence, connection_data.remote_sequence) >= 32 {
return None;
}
connection_data.ack_sequence(header.sequence);
connection_data.last_response_time = now;
let sequence_group = header.get_sequence_group();
if sequence_group.len() == 1 {
// The whole payload is contained in this packet, so return that
Some((header, payload))
} else {
// Otherwise, the payload is spread over a few packets, so collect the parts
let packet_group = connection_data.incomplete_payloads
.entry(sequence_group)
.or_insert((Instant::now(), vec![None; header.total as usize]));
if packet_group.1[header.part as usize].is_none() {
packet_group.1[header.part as usize] = Some((header.clone(), payload));
// If we have all the parts, join them and return the full payload
if packet_group.1.iter().all(|p| p.is_some()) {
let (header, mut payload) = packet_group.1.remove(0).unwrap();
let additional_size = packet_group.1.iter().fold(0, |sum, p| sum + p.as_ref().unwrap().1.len());
payload.reserve_exact(additional_size);
for (_, payload_part) in packet_group.1.drain(..).map(|p| p.unwrap()) {
payload.extend_from_slice(&payload_part);
}
Some((header, payload))
} else {
None
}
} else {
log!(ERROR, "{}: Received a duplicate payload section!", thread::current().name().unwrap());
None
}
}
} else {
Some((header, payload))
};
if let Some((header, payload)) = decodable_events {
let events = decode_events(header, payload);
if !events.is_empty() {
Some((sender, events))
} else {
None
}
} else {
None
}
}
fn decode_packet(buffer: &[u8]) -> Result<(PacketHeader, Vec<u8>), String> {
let header = PacketHeader::from_slice_beginning(buffer)?;
let payload = buffer[header.size()..].to_vec();
Ok((header, payload))
}
fn decode_events(header: PacketHeader, payload: Vec<u8>) -> Vec<Box<dyn NetworkEvent>> {
let mut events = Vec::with_capacity(header.sizes.len());
let mut position = 0;
for &size in header.sizes.iter() {
let range = position..position + size as usize;
position += size as usize;
events.push(match serde_cbor::from_slice(&payload[range]) {
Ok(event) => event,
Err(error) => {
log!(ERROR, "{}: Received a bad payload: {:?}", thread::current().name().unwrap(), error);
continue;
},
});
}
events
} |
use std::error::Error as StdError;
use std::io::stdin;
use std::result::Result as StdResult;
type Result<T> = StdResult<T, Box<StdError>>;
fn main() -> Result<()> {
println!("Hello, there! What is your name?");
let buffer = &mut String::new();
stdin().read_line(buffer)?; // <- API requires buffer param as of Rust 1.0; returns `Result` of bytes read
let res = match buffer.trim_end() {
"" => "aight faq u den".to_owned(),
name => format!("Hello, {}. Nice to meet you!", name),
};
println!("{}", res);
Ok(())
}
|
use std::{
borrow::{Borrow, Cow},
cell::UnsafeCell,
cmp::Ordering,
collections::HashMap,
fmt::{Debug, Display, Formatter, Result as FmtResult},
io::Write,
sync::Arc,
};
pub trait WithChromSet<H: ChromSetHandle> {
type Result;
fn with_chrom_set(self, handle: &mut H) -> Self::Result;
}
pub trait ChromName: Ord + Clone {
fn to_string(&self) -> Cow<str>;
fn write<W: Write>(&self, w: W) -> std::io::Result<()>;
}
impl ChromName for String {
fn to_string(&self) -> Cow<str> {
Cow::Borrowed(self)
}
fn write<W: Write>(&self, mut w: W) -> std::io::Result<()> {
w.write_all(self.as_bytes())
}
}
impl<'a> ChromName for &'a str {
fn to_string(&self) -> Cow<str> {
Cow::Borrowed(*self)
}
fn write<W: Write>(&self, mut w: W) -> std::io::Result<()> {
w.write_all(self.as_bytes())
}
}
pub trait ChromSetHandle {
type RefType: ChromName;
fn query_or_insert(&mut self, name: &str) -> Self::RefType;
}
pub trait ChromSet {
type RefType: ChromName;
type Handle: ChromSetHandle<RefType = Self::RefType>;
fn get_handle(&self) -> Self::Handle;
}
#[derive(Default)]
struct StringPool {
s2i_map: HashMap<String, usize>,
i2s_map: Vec<String>,
}
impl StringPool {
fn query_id(&self, s: &str) -> Option<usize> {
if let Some(id) = self.s2i_map.get(s) {
Some(*id)
} else {
None
}
}
fn query_id_or_insert<T: Borrow<str>>(&mut self, s: T) -> usize {
let sref = s.borrow();
if Some(sref) == self.i2s_map.last().map(Borrow::borrow) {
return self.i2s_map.len() - 1;
}
if let Some(id) = self.query_id(sref) {
id
} else {
self.s2i_map
.insert(s.borrow().to_string(), self.i2s_map.len());
self.i2s_map.push(s.borrow().to_string());
self.i2s_map.len() - 1
}
}
}
type SharedStringPool = Arc<UnsafeCell<StringPool>>;
pub struct LexicalChromSet {
pool: SharedStringPool,
}
#[derive(Clone)]
pub struct LexicalChromRef {
pool: SharedStringPool,
idx: usize,
}
impl Debug for LexicalChromRef {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
let value = ChromName::to_string(self);
write!(f, "{}(Id={})", value, self.idx)
}
}
impl Display for LexicalChromRef {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
let value = ChromName::to_string(self);
write!(f, "{}", value)
}
}
pub struct LexicalChromHandle {
pool: SharedStringPool,
}
impl LexicalChromRef {
// This is unsafe, since it returns the a reference of the string pool
// However, our contract is we doesn't allow any long living string pool reference
// So the only correct way to use this method is DO NOT release this reference.
unsafe fn get_string_ref(&self) -> &str {
let pool_ref = &*self.pool.get();
pool_ref.i2s_map[self.idx].as_ref()
}
}
impl PartialEq for LexicalChromRef {
fn eq(&self, other: &Self) -> bool {
if self.pool.get() == other.pool.get() {
return self.idx == other.idx;
}
unsafe { self.get_string_ref() == other.get_string_ref() }
}
}
impl PartialEq<str> for LexicalChromRef {
fn eq(&self, other: &str) -> bool {
unsafe { self.get_string_ref() == other }
}
}
impl PartialOrd for LexicalChromRef {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.pool.get() == other.pool.get() && self.idx == other.idx {
return Some(Ordering::Equal);
}
unsafe { Some(Ord::cmp(self.get_string_ref(), other.get_string_ref())) }
}
}
impl Eq for LexicalChromRef {}
impl Ord for LexicalChromRef {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl ChromName for LexicalChromRef {
// Note we don't awllow any long live reference to the internal string poll
// so that we need to copy it
fn to_string(&self) -> Cow<str> {
let ret = unsafe { self.get_string_ref().to_string() };
Cow::Owned(ret)
}
fn write<W: Write>(&self, mut w: W) -> std::io::Result<()> {
let name = unsafe { self.get_string_ref() };
w.write_all(name.as_bytes())
}
}
impl ChromSetHandle for LexicalChromHandle {
type RefType = LexicalChromRef;
fn query_or_insert(&mut self, name: &str) -> Self::RefType {
let pool = unsafe { self.pool.get().as_mut().unwrap() };
let idx = pool.query_id_or_insert(name);
LexicalChromRef {
pool: self.pool.clone(),
idx,
}
}
}
impl LexicalChromSet {
pub fn new() -> Self {
Self {
pool: Arc::new(UnsafeCell::new(StringPool::default())),
}
}
}
impl ChromSet for LexicalChromSet {
type Handle = LexicalChromHandle;
type RefType = LexicalChromRef;
fn get_handle(&self) -> Self::Handle {
LexicalChromHandle {
pool: self.pool.clone(),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_lexical_chrom_set() {
let chrom_set = LexicalChromSet::new();
let mut handle_1 = chrom_set.get_handle();
let mut handle_2 = chrom_set.get_handle();
let ref1 = handle_1.query_or_insert("chr1");
let ref2 = handle_2.query_or_insert("chr1");
assert_eq!(ref1, ref2);
assert_eq!(ref1.idx, ref2.idx);
let ref3 = handle_1.query_or_insert("chr2");
assert_ne!(ref1, ref3);
assert!(ref3 > ref1);
}
}
|
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet, VecDeque};
use itertools::Itertools;
use whiteread::parse_line;
fn main() {
let (h, w): (usize, usize) = parse_line().unwrap();
let mut map: Vec<Vec<char>> = vec![];
for _ in 0..h {
let line: String = parse_line().unwrap();
map.push(line.chars().collect_vec());
}
let mut queue: VecDeque<(usize, usize, usize)> = VecDeque::new();
queue.push_back((0, 0, 0));
let mut already: Vec<Vec<bool>> = vec![vec![false; w]; h];
already[0][0] = true;
let mut ans = 0;
while !queue.is_empty() {
let (si, sj, now) = queue.pop_front().unwrap();
if si == h - 1 && sj == w - 1 {
ans = now;
break;
}
if si > 0 && !already[si - 1][sj] && map[si - 1][sj] == '.' {
queue.push_back((si - 1, sj, now + 1));
already[si - 1][sj] = true;
}
if sj > 0 && !already[si][sj - 1] && map[si][sj - 1] == '.' {
queue.push_back((si, sj - 1, now + 1));
already[si][sj - 1] = true;
}
if si < h - 1 && !already[si + 1][sj] && map[si + 1][sj] == '.' {
queue.push_back((si + 1, sj, now + 1));
already[si + 1][sj] = true;
}
if sj < w - 1 && !already[si][sj + 1] && map[si][sj + 1] == '.' {
queue.push_back((si, sj + 1, now + 1));
already[si][sj + 1] = true;
}
}
let mut kabe = 0;
for i in 0..h {
for j in 0..w {
if map[i][j] == '#' {
kabe += 1;
}
}
}
if ans == 0 {
println!("{}", -1);
} else {
println!("{}", h * w - 2 - (ans - 1) - kabe);
}
}
|
mod file_list;
mod line_by_line;
mod page;
mod side_by_side;
pub(crate) mod utils;
pub use self::file_list::FileListPrinter;
pub use self::line_by_line::LineByLinePrinter;
pub use self::page::PagePrinter;
pub use self::side_by_side::SideBySidePrinter;
|
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use cosmwasm_std::Addr;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
pub count: i32,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
Increment {},
Reset { count: i32 },
ChangeOwner { new_owner: Addr },
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
// GetCount returns the current count as a json-encoded number
GetCount {},
GetOwner {},
}
// We define a custom struct for each query response
// Adding this # and [] adds additional functionality over the ConuntResponse Struct we have here
// Setialize,Deserialize and JsonSchema are some of the params that are REQUIRED by cosmwasm to
// work correctly
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct CountResponse {
pub count: i32,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct OwnerResponse {
pub owner: Addr,
}
|
use serde::{Deserialize};
use serde_json;
#[derive(Deserialize)]
pub struct Configuration {
pub account_name: String,
pub cookie: String,
}
pub fn load_configuration(file: &str) -> Result<Configuration, String> {
let res = std::fs::read_to_string(file);
match res {
Ok(contents) => {
let json_value = serde_json::from_str(&contents);
match json_value {
Ok(v) => Ok(v),
Err(e) => Err(
format!("Couldn't parse json value: {}", e).to_string()
),
}
}
Err(e) => Err(format!("Couldn't read configuration file: {}", e).to_string())
}
} |
// MinIO Rust Library for Amazon S3 Compatible Cloud Storage
// Copyright 2022 MinIO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use async_std::task;
use chrono::Duration;
use hyper::http::Method;
use minio::s3::types::NotificationRecords;
use rand::distributions::{Alphanumeric, DistString};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::io::BufReader;
use std::{fs, io};
use tokio::sync::mpsc;
use minio::s3::args::*;
use minio::s3::client::Client;
use minio::s3::creds::StaticProvider;
use minio::s3::http::BaseUrl;
use minio::s3::types::{
CsvInputSerialization, CsvOutputSerialization, DeleteObject, FileHeaderInfo,
NotificationConfig, ObjectLockConfig, PrefixFilterRule, QueueConfig, QuoteFields,
RetentionMode, SelectRequest, SuffixFilterRule,
};
use minio::s3::utils::{to_iso8601utc, utc_now};
struct RandReader {
size: usize,
}
impl RandReader {
fn new(size: usize) -> RandReader {
RandReader { size: size }
}
}
impl std::io::Read for RandReader {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
let bytes_read = match self.size > buf.len() {
true => buf.len(),
false => self.size,
};
if bytes_read > 0 {
let random: &mut dyn rand::RngCore = &mut rand::thread_rng();
random.fill_bytes(&mut buf[0..bytes_read]);
}
self.size -= bytes_read;
Ok(bytes_read)
}
}
fn rand_bucket_name() -> String {
Alphanumeric
.sample_string(&mut rand::thread_rng(), 8)
.to_lowercase()
}
fn rand_object_name() -> String {
Alphanumeric.sample_string(&mut rand::thread_rng(), 8)
}
struct ClientTest<'a> {
base_url: BaseUrl,
access_key: String,
secret_key: String,
ignore_cert_check: bool,
ssl_cert_file: String,
client: Client<'a>,
test_bucket: String,
}
impl<'a> ClientTest<'_> {
const SQS_ARN: &str = "arn:minio:sqs::miniojavatest:webhook";
fn new(
base_url: BaseUrl,
access_key: String,
secret_key: String,
static_provider: &'a StaticProvider,
ignore_cert_check: bool,
ssl_cert_file: String,
) -> ClientTest<'a> {
let mut client = Client::new(base_url.clone(), Some(static_provider));
client.ignore_cert_check = ignore_cert_check;
client.ssl_cert_file = ssl_cert_file.to_string();
ClientTest {
base_url: base_url,
access_key: access_key,
secret_key: secret_key,
ignore_cert_check: ignore_cert_check,
ssl_cert_file: ssl_cert_file,
client: client,
test_bucket: rand_bucket_name(),
}
}
async fn init(&self) {
self.client
.make_bucket(&MakeBucketArgs::new(&self.test_bucket).unwrap())
.await
.unwrap();
}
async fn drop(&self) {
self.client
.remove_bucket(&RemoveBucketArgs::new(&self.test_bucket).unwrap())
.await
.unwrap();
}
async fn bucket_exists(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let exists = self
.client
.bucket_exists(&BucketExistsArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(exists, true);
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn list_buckets(&self) {
let mut names: Vec<String> = Vec::new();
for _ in 1..=3 {
names.push(rand_bucket_name());
}
for b in names.iter() {
self.client
.make_bucket(&MakeBucketArgs::new(&b).unwrap())
.await
.unwrap();
}
let mut count = 0;
let resp = self
.client
.list_buckets(&ListBucketsArgs::new())
.await
.unwrap();
for bucket in resp.buckets.iter() {
if names.contains(&bucket.name) {
count += 1;
}
}
assert_eq!(count, 3);
for b in names.iter() {
self.client
.remove_bucket(&RemoveBucketArgs::new(&b).unwrap())
.await
.unwrap();
}
}
async fn put_object(&self) {
let object_name = rand_object_name();
let size = 16_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
let resp = self
.client
.stat_object(&StatObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
assert_eq!(resp.bucket_name, self.test_bucket);
assert_eq!(resp.object_name, object_name);
assert_eq!(resp.size, size);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
}
async fn put_object_multipart(&self) {
let object_name = rand_object_name();
let size: usize = 16 + 5 * 1024 * 1024;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
let resp = self
.client
.stat_object(&StatObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
assert_eq!(resp.bucket_name, self.test_bucket);
assert_eq!(resp.object_name, object_name);
assert_eq!(resp.size, size);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
}
async fn get_object(&self) {
let object_name = rand_object_name();
let data = "hello, world";
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut BufReader::new(data.as_bytes()),
Some(data.len()),
None,
)
.unwrap(),
)
.await
.unwrap();
let resp = self
.client
.get_object(&GetObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
let got = resp.text().await.unwrap();
assert_eq!(got, data);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
}
fn get_hash(filename: &String) -> String {
let mut hasher = Sha256::new();
let mut file = fs::File::open(filename).unwrap();
io::copy(&mut file, &mut hasher).unwrap();
return format!("{:x}", hasher.finalize());
}
async fn upload_download_object(&self) {
let object_name = rand_object_name();
let size = 16_usize;
let mut file = fs::File::create(&object_name).unwrap();
io::copy(&mut RandReader::new(size), &mut file).unwrap();
file.sync_all().unwrap();
self.client
.upload_object(
&mut UploadObjectArgs::new(&self.test_bucket, &object_name, &object_name).unwrap(),
)
.await
.unwrap();
let filename = rand_object_name();
self.client
.download_object(
&DownloadObjectArgs::new(&self.test_bucket, &object_name, &filename).unwrap(),
)
.await
.unwrap();
assert_eq!(
ClientTest::get_hash(&object_name) == ClientTest::get_hash(&filename),
true
);
fs::remove_file(&object_name).unwrap();
fs::remove_file(&filename).unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
let object_name = rand_object_name();
let size: usize = 16 + 5 * 1024 * 1024;
let mut file = fs::File::create(&object_name).unwrap();
io::copy(&mut RandReader::new(size), &mut file).unwrap();
file.sync_all().unwrap();
self.client
.upload_object(
&mut UploadObjectArgs::new(&self.test_bucket, &object_name, &object_name).unwrap(),
)
.await
.unwrap();
let filename = rand_object_name();
self.client
.download_object(
&DownloadObjectArgs::new(&self.test_bucket, &object_name, &filename).unwrap(),
)
.await
.unwrap();
assert_eq!(
ClientTest::get_hash(&object_name) == ClientTest::get_hash(&filename),
true
);
fs::remove_file(&object_name).unwrap();
fs::remove_file(&filename).unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
}
async fn remove_objects(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let mut names: Vec<String> = Vec::new();
for _ in 1..=3 {
let object_name = rand_object_name();
let size = 0_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
names.push(object_name);
}
let mut objects: Vec<DeleteObject> = Vec::new();
for name in names.iter() {
objects.push(DeleteObject {
name: &name,
version_id: None,
});
}
self.client
.remove_objects(
&mut RemoveObjectsArgs::new(&self.test_bucket, &mut objects.iter()).unwrap(),
)
.await
.unwrap();
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn list_objects(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let mut names: Vec<String> = Vec::new();
for _ in 1..=3 {
let object_name = rand_object_name();
let size = 0_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
names.push(object_name);
}
self.client
.list_objects(
&mut ListObjectsArgs::new(&self.test_bucket, &|items| {
for item in items.iter() {
assert_eq!(names.contains(&item.name), true);
}
true
})
.unwrap(),
)
.await
.unwrap();
let mut objects: Vec<DeleteObject> = Vec::new();
for name in names.iter() {
objects.push(DeleteObject {
name: &name,
version_id: None,
});
}
self.client
.remove_objects(
&mut RemoveObjectsArgs::new(&self.test_bucket, &mut objects.iter()).unwrap(),
)
.await
.unwrap();
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn select_object_content(&self) {
let object_name = rand_object_name();
let mut data = String::new();
data.push_str("1997,Ford,E350,\"ac, abs, moon\",3000.00\n");
data.push_str("1999,Chevy,\"Venture \"\"Extended Edition\"\"\",,4900.00\n");
data.push_str("1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\"\",,5000.00\n");
data.push_str("1996,Jeep,Grand Cherokee,\"MUST SELL!\n");
data.push_str("air, moon roof, loaded\",4799.00\n");
let body = String::from("Year,Make,Model,Description,Price\n") + &data;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut BufReader::new(body.as_bytes()),
Some(body.len()),
None,
)
.unwrap(),
)
.await
.unwrap();
let request = SelectRequest::new_csv_input_output(
"select * from S3Object",
CsvInputSerialization {
compression_type: None,
allow_quoted_record_delimiter: false,
comments: None,
field_delimiter: None,
file_header_info: Some(FileHeaderInfo::USE),
quote_character: None,
quote_escape_character: None,
record_delimiter: None,
},
CsvOutputSerialization {
field_delimiter: None,
quote_character: None,
quote_escape_character: None,
quote_fields: Some(QuoteFields::ASNEEDED),
record_delimiter: None,
},
)
.unwrap();
let mut resp = self
.client
.select_object_content(
&SelectObjectContentArgs::new(&self.test_bucket, &object_name, &request).unwrap(),
)
.await
.unwrap();
let mut got = String::new();
let mut buf = [0_u8; 512];
loop {
let size = resp.read(&mut buf).await.unwrap();
if size == 0 {
break;
}
got += &String::from_utf8(buf[..size].to_vec()).unwrap();
}
assert_eq!(got, data);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
}
async fn listen_bucket_notification(&self) {
let object_name = rand_object_name();
let name = object_name.clone();
let (sender, mut receiver): (mpsc::UnboundedSender<bool>, mpsc::UnboundedReceiver<bool>) =
mpsc::unbounded_channel();
let access_key = self.access_key.clone();
let secret_key = self.secret_key.clone();
let base_url = self.base_url.clone();
let ignore_cert_check = self.ignore_cert_check;
let ssl_cert_file = self.ssl_cert_file.clone();
let test_bucket = self.test_bucket.clone();
let listen_task = move || async move {
let static_provider = StaticProvider::new(&access_key, &secret_key, None);
let mut client = Client::new(base_url, Some(&static_provider));
client.ignore_cert_check = ignore_cert_check;
client.ssl_cert_file = ssl_cert_file;
let event_fn = |event: NotificationRecords| {
for record in event.records.iter() {
if let Some(s3) = &record.s3 {
if let Some(object) = &s3.object {
if let Some(key) = &object.key {
if name == *key {
sender.send(true).unwrap();
}
return false;
}
}
}
}
sender.send(false).unwrap();
return false;
};
let args = &ListenBucketNotificationArgs::new(&test_bucket, &event_fn).unwrap();
client.listen_bucket_notification(&args).await.unwrap();
};
let spawned_task = task::spawn(listen_task());
task::sleep(std::time::Duration::from_millis(100)).await;
let size = 16_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
spawned_task.await;
assert_eq!(receiver.recv().await.unwrap(), true);
}
async fn copy_object(&self) {
let src_object_name = rand_object_name();
let size = 16_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&src_object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
let object_name = rand_object_name();
self.client
.copy_object(
&CopyObjectArgs::new(
&self.test_bucket,
&object_name,
CopySource::new(&self.test_bucket, &src_object_name).unwrap(),
)
.unwrap(),
)
.await
.unwrap();
let resp = self
.client
.stat_object(&StatObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
assert_eq!(resp.size, size);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &src_object_name).unwrap())
.await
.unwrap();
}
async fn compose_object(&self) {
let src_object_name = rand_object_name();
let size = 16_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&src_object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
let mut s1 = ComposeSource::new(&self.test_bucket, &src_object_name).unwrap();
s1.offset = Some(3);
s1.length = Some(5);
let mut sources: Vec<ComposeSource> = Vec::new();
sources.push(s1);
let object_name = rand_object_name();
self.client
.compose_object(
&mut ComposeObjectArgs::new(&self.test_bucket, &object_name, &mut sources).unwrap(),
)
.await
.unwrap();
let resp = self
.client
.stat_object(&StatObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
assert_eq!(resp.size, 5);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &src_object_name).unwrap())
.await
.unwrap();
}
async fn set_get_delete_bucket_notification(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
self.client
.set_bucket_notification(
&SetBucketNotificationArgs::new(
&bucket_name,
&NotificationConfig {
cloud_func_config_list: None,
queue_config_list: Some(vec![QueueConfig {
events: vec![
String::from("s3:ObjectCreated:Put"),
String::from("s3:ObjectCreated:Copy"),
],
id: None,
prefix_filter_rule: Some(PrefixFilterRule {
value: String::from("images"),
}),
suffix_filter_rule: Some(SuffixFilterRule {
value: String::from("pg"),
}),
queue: String::from(ClientTest::SQS_ARN),
}]),
topic_config_list: None,
},
)
.unwrap(),
)
.await
.unwrap();
let resp = self
.client
.get_bucket_notification(&GetBucketNotificationArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(resp.config.queue_config_list.as_ref().unwrap().len(), 1);
assert_eq!(
resp.config.queue_config_list.as_ref().unwrap()[0]
.events
.contains(&String::from("s3:ObjectCreated:Put")),
true
);
assert_eq!(
resp.config.queue_config_list.as_ref().unwrap()[0]
.events
.contains(&String::from("s3:ObjectCreated:Copy")),
true
);
assert_eq!(
resp.config.queue_config_list.as_ref().unwrap()[0]
.prefix_filter_rule
.as_ref()
.unwrap()
.value,
"images"
);
assert_eq!(
resp.config.queue_config_list.as_ref().unwrap()[0]
.suffix_filter_rule
.as_ref()
.unwrap()
.value,
"pg"
);
assert_eq!(
resp.config.queue_config_list.as_ref().unwrap()[0].queue,
ClientTest::SQS_ARN
);
self.client
.delete_bucket_notification(&DeleteBucketNotificationArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_notification(&GetBucketNotificationArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(resp.config.queue_config_list.is_none(), true);
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn set_get_delete_bucket_policy(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let config = r#"
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Principal": {
"AWS": [
"*"
]
},
"Resource": [
"arn:aws:s3:::<BUCKET>/myobject*"
],
"Sid": ""
}
]
}
"#
.replace("<BUCKET>", &bucket_name);
self.client
.set_bucket_policy(&SetBucketPolicyArgs::new(&bucket_name, &config).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_policy(&GetBucketPolicyArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(resp.config.is_empty(), false);
self.client
.delete_bucket_policy(&DeleteBucketPolicyArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_policy(&GetBucketPolicyArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(resp.config, "{}");
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn set_get_delete_bucket_tags(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let tags = HashMap::from([
(String::from("Project"), String::from("Project One")),
(String::from("User"), String::from("jsmith")),
]);
self.client
.set_bucket_tags(&SetBucketTagsArgs::new(&bucket_name, &tags).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_tags(&GetBucketTagsArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(
resp.tags.len() == tags.len() && resp.tags.keys().all(|k| tags.contains_key(k)),
true
);
self.client
.delete_bucket_tags(&DeleteBucketTagsArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_tags(&GetBucketTagsArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(resp.tags.is_empty(), true);
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn set_get_delete_object_lock_config(&self) {
let bucket_name = rand_bucket_name();
let mut args = MakeBucketArgs::new(&bucket_name).unwrap();
args.object_lock = true;
self.client.make_bucket(&args).await.unwrap();
self.client
.set_object_lock_config(
&SetObjectLockConfigArgs::new(
&bucket_name,
&ObjectLockConfig::new(RetentionMode::GOVERNANCE, Some(7), None).unwrap(),
)
.unwrap(),
)
.await
.unwrap();
let resp = self
.client
.get_object_lock_config(&GetObjectLockConfigArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(
match resp.config.retention_mode {
Some(r) => match r {
RetentionMode::GOVERNANCE => true,
_ => false,
},
_ => false,
},
true
);
assert_eq!(resp.config.retention_duration_days == Some(7), true);
assert_eq!(resp.config.retention_duration_years.is_none(), true);
self.client
.delete_object_lock_config(&DeleteObjectLockConfigArgs::new(&bucket_name).unwrap())
.await
.unwrap();
let resp = self
.client
.get_object_lock_config(&GetObjectLockConfigArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(resp.config.retention_mode.is_none(), true);
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn set_get_delete_object_tags(&self) {
let object_name = rand_object_name();
let size = 16_usize;
self.client
.put_object(
&mut PutObjectArgs::new(
&self.test_bucket,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
let tags = HashMap::from([
(String::from("Project"), String::from("Project One")),
(String::from("User"), String::from("jsmith")),
]);
self.client
.set_object_tags(
&SetObjectTagsArgs::new(&self.test_bucket, &object_name, &tags).unwrap(),
)
.await
.unwrap();
let resp = self
.client
.get_object_tags(&GetObjectTagsArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
assert_eq!(
resp.tags.len() == tags.len() && resp.tags.keys().all(|k| tags.contains_key(k)),
true
);
self.client
.delete_object_tags(
&DeleteObjectTagsArgs::new(&self.test_bucket, &object_name).unwrap(),
)
.await
.unwrap();
let resp = self
.client
.get_object_tags(&GetObjectTagsArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
assert_eq!(resp.tags.is_empty(), true);
self.client
.remove_object(&RemoveObjectArgs::new(&self.test_bucket, &object_name).unwrap())
.await
.unwrap();
}
async fn set_get_bucket_versioning(&self) {
let bucket_name = rand_bucket_name();
self.client
.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
self.client
.set_bucket_versioning(&SetBucketVersioningArgs::new(&bucket_name, true).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_versioning(&GetBucketVersioningArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(
match resp.status {
Some(v) => v,
_ => false,
},
true
);
self.client
.set_bucket_versioning(&SetBucketVersioningArgs::new(&bucket_name, false).unwrap())
.await
.unwrap();
let resp = self
.client
.get_bucket_versioning(&GetBucketVersioningArgs::new(&bucket_name).unwrap())
.await
.unwrap();
assert_eq!(
match resp.status {
Some(v) => v,
_ => false,
},
false
);
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn set_get_object_retention(&self) {
let bucket_name = rand_bucket_name();
let mut args = MakeBucketArgs::new(&bucket_name).unwrap();
args.object_lock = true;
self.client.make_bucket(&args).await.unwrap();
let object_name = rand_object_name();
let size = 16_usize;
let obj_resp = self
.client
.put_object(
&mut PutObjectArgs::new(
&bucket_name,
&object_name,
&mut RandReader::new(size),
Some(size),
None,
)
.unwrap(),
)
.await
.unwrap();
let mut args = SetObjectRetentionArgs::new(&bucket_name, &object_name).unwrap();
args.retention_mode = Some(RetentionMode::GOVERNANCE);
let retain_until_date = utc_now() + Duration::days(1);
args.retain_until_date = Some(retain_until_date);
self.client.set_object_retention(&args).await.unwrap();
let resp = self
.client
.get_object_retention(&GetObjectRetentionArgs::new(&bucket_name, &object_name).unwrap())
.await
.unwrap();
assert_eq!(
match resp.retention_mode {
Some(v) => match v {
RetentionMode::GOVERNANCE => true,
_ => false,
},
_ => false,
},
true
);
assert_eq!(
match resp.retain_until_date {
Some(v) => to_iso8601utc(v) == to_iso8601utc(retain_until_date),
_ => false,
},
true,
);
let mut args = SetObjectRetentionArgs::new(&bucket_name, &object_name).unwrap();
args.bypass_governance_mode = true;
self.client.set_object_retention(&args).await.unwrap();
let resp = self
.client
.get_object_retention(&GetObjectRetentionArgs::new(&bucket_name, &object_name).unwrap())
.await
.unwrap();
assert_eq!(resp.retention_mode.is_none(), true);
assert_eq!(resp.retain_until_date.is_none(), true);
let mut args = RemoveObjectArgs::new(&bucket_name, &object_name).unwrap();
let version_id = obj_resp.version_id.unwrap().clone();
args.version_id = Some(version_id.as_str());
self.client.remove_object(&args).await.unwrap();
self.client
.remove_bucket(&RemoveBucketArgs::new(&bucket_name).unwrap())
.await
.unwrap();
}
async fn get_presigned_object_url(&self) {
let object_name = rand_object_name();
let resp = self
.client
.get_presigned_object_url(
&GetPresignedObjectUrlArgs::new(&self.test_bucket, &object_name, Method::GET)
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.url.contains("X-Amz-Signature="), true);
}
async fn get_presigned_post_form_data(&self) {
let object_name = rand_object_name();
let expiration = utc_now() + Duration::days(5);
let mut policy = PostPolicy::new(&self.test_bucket, &expiration).unwrap();
policy.add_equals_condition("key", &object_name).unwrap();
policy
.add_content_length_range_condition(1 * 1024 * 1024, 4 * 1024 * 1024)
.unwrap();
let form_data = self
.client
.get_presigned_post_form_data(&policy)
.await
.unwrap();
assert_eq!(form_data.contains_key("x-amz-signature"), true);
assert_eq!(form_data.contains_key("policy"), true);
}
}
#[tokio::main]
#[test]
async fn s3_tests() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let host = std::env::var("SERVER_ENDPOINT")?;
let access_key = std::env::var("ACCESS_KEY")?;
let secret_key = std::env::var("SECRET_KEY")?;
let secure = std::env::var("ENABLE_HTTPS").is_ok();
let ssl_cert_file = std::env::var("SSL_CERT_FILE")?;
let ignore_cert_check = std::env::var("IGNORE_CERT_CHECK").is_ok();
let region = std::env::var("SERVER_REGION").ok();
let mut base_url = BaseUrl::from_string(host).unwrap();
base_url.https = secure;
if let Some(v) = region {
base_url.region = v;
}
let static_provider = StaticProvider::new(&access_key, &secret_key, None);
let ctest = ClientTest::new(
base_url,
access_key,
secret_key,
&static_provider,
ignore_cert_check,
ssl_cert_file,
);
ctest.init().await;
println!("make_bucket() + bucket_exists() + remove_bucket()");
ctest.bucket_exists().await;
println!("list_buckets()");
ctest.list_buckets().await;
println!("put_object() + stat_object() + remove_object()");
ctest.put_object().await;
println!("[Multipart] put_object()");
ctest.put_object_multipart().await;
println!("get_object()");
ctest.get_object().await;
println!("{{upload,download}}_object()");
ctest.upload_download_object().await;
println!("remove_objects()");
ctest.remove_objects().await;
println!("list_objects()");
ctest.list_objects().await;
println!("select_object_content()");
ctest.select_object_content().await;
println!("listen_bucket_notification()");
ctest.listen_bucket_notification().await;
println!("copy_object()");
ctest.copy_object().await;
println!("compose_object()");
ctest.compose_object().await;
println!("{{set,get,delete}}_bucket_notification()");
ctest.set_get_delete_bucket_notification().await;
println!("{{set,get,delete}}_bucket_policy()");
ctest.set_get_delete_bucket_policy().await;
println!("{{set,get,delete}}_bucket_tags()");
ctest.set_get_delete_bucket_tags().await;
println!("{{set,get,delete}}_object_lock_config()");
ctest.set_get_delete_object_lock_config().await;
println!("{{set,get,delete}}_object_tags()");
ctest.set_get_delete_object_tags().await;
println!("{{set,get}}_bucket_versioning()");
ctest.set_get_bucket_versioning().await;
println!("{{set,get}}_object_retention()");
ctest.set_get_object_retention().await;
println!("get_presigned_object_url()");
ctest.get_presigned_object_url().await;
println!("get_presigned_post_form_data()");
ctest.get_presigned_post_form_data().await;
ctest.drop().await;
Ok(())
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Devices_I2c_Provider")]
pub mod Provider;
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct I2cBusSpeed(pub i32);
impl I2cBusSpeed {
pub const StandardMode: Self = Self(0i32);
pub const FastMode: Self = Self(1i32);
}
impl ::core::marker::Copy for I2cBusSpeed {}
impl ::core::clone::Clone for I2cBusSpeed {
fn clone(&self) -> Self {
*self
}
}
pub type I2cConnectionSettings = *mut ::core::ffi::c_void;
pub type I2cController = *mut ::core::ffi::c_void;
pub type I2cDevice = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct I2cSharingMode(pub i32);
impl I2cSharingMode {
pub const Exclusive: Self = Self(0i32);
pub const Shared: Self = Self(1i32);
}
impl ::core::marker::Copy for I2cSharingMode {}
impl ::core::clone::Clone for I2cSharingMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct I2cTransferResult {
pub Status: I2cTransferStatus,
pub BytesTransferred: u32,
}
impl ::core::marker::Copy for I2cTransferResult {}
impl ::core::clone::Clone for I2cTransferResult {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct I2cTransferStatus(pub i32);
impl I2cTransferStatus {
pub const FullTransfer: Self = Self(0i32);
pub const PartialTransfer: Self = Self(1i32);
pub const SlaveAddressNotAcknowledged: Self = Self(2i32);
pub const ClockStretchTimeout: Self = Self(3i32);
pub const UnknownError: Self = Self(4i32);
}
impl ::core::marker::Copy for I2cTransferStatus {}
impl ::core::clone::Clone for I2cTransferStatus {
fn clone(&self) -> Self {
*self
}
}
pub type II2cDeviceStatics = *mut ::core::ffi::c_void;
|
#![allow(dead_code)] // Not yet in use.
use crate::graphics::{render_target, DrawMode, Drawable};
use gl_bindings::{Buffer, BufferType};
use na::Matrix4;
use std::f32;
const POINTS: usize = 40;
/// Represents a drawable circle.
pub struct Circle {
pos: (f32, f32, f32),
rotation: f32,
rotation_axis: (f32, f32, f32),
radius: f32,
filled: bool,
color: (f32, f32, f32),
vertices: Buffer<f32>,
indices: Buffer<u16>,
draw_mode: DrawMode,
}
impl Circle {
/// Creates a new circle with the chosen parameters.
pub fn new(
x: f32,
y: f32,
z: f32,
radius: f32,
rotation: f32,
rotation_axis: (f32, f32, f32),
filled: bool,
) -> Self {
let vertices: Buffer<f32> = Buffer::new(BufferType::Array);
let indices: Buffer<u16> = Buffer::new(BufferType::IndexArray);
let mut result = Circle {
pos: (x, y, z),
rotation,
rotation_axis,
radius,
filled,
color: (1.0, 1.0, 1.0),
vertices,
indices,
draw_mode: DrawMode::LINES,
};
result.rebuild_data();
result
}
pub fn set_rotation(&mut self, rotation: f32, rotation_axis: (f32, f32, f32)) {
self.rotation = rotation;
self.rotation_axis = rotation_axis;
}
pub fn set_color(&mut self, r: f32, g: f32, b: f32) {
self.color = (r, g, b);
}
pub fn set_radius(&mut self, radius: f32) {
self.radius = radius;
}
pub fn set_center(&mut self, center: (f32, f32, f32)) {
self.pos = center;
}
pub fn get_center(&self) -> (f32, f32, f32) {
self.pos
}
pub fn rebuild_data(&mut self) {
let mut vertex_data = Vec::new();
let mut index_data = Vec::new();
let (x, y, z) = self.pos;
let rot = self.rotation;
let (ax, ay, az) = self.rotation_axis;
let radius = self.radius;
if self.filled {
vertex_data.extend_from_slice(&[x, y, z, 1.0, 1.0, 1.0, 0.5, 0.5]);
for i in 0..POINTS {
let progress = i as f32 / POINTS as f32;
let dt = progress * f32::consts::PI * 2.0;
let dx = x + radius * dt.cos();
let dy = y + radius * dt.sin();
let dz = z;
vertex_data.extend_from_slice(&[
dx,
dy,
dz,
1.0,
1.0,
1.0,
dx / 2.0 + 0.5,
dy / 2.0 + 0.5,
]);
if i > 0 {
let idx = i as u16;
index_data.extend_from_slice(&[0, idx + 1, idx]);
}
}
index_data.extend_from_slice(&[0, 1, POINTS as u16]);
self.draw_mode = DrawMode::TRIANGLES;
//TODO: implement
} else {
for i in 0..POINTS {
let progress = i as f32 / POINTS as f32;
let dt = progress * f32::consts::PI * 2.0;
let dts = radius * dt.sin();
let dtc = radius * dt.cos();
let dx = x + dtc * ax + dts * ay * rot.sin() + dts * az * rot.cos();
let dy = y + dts * ax * rot.cos() + dtc * ay + dts * az * rot.sin();
let dz = z + dts * ax * rot.sin() + dts * ay * rot.cos() + dtc * az;
vertex_data.extend_from_slice(&[
dx,
dy,
dz,
self.color.0,
self.color.1,
self.color.2,
dx / 2.0 + 0.5,
dy / 2.0 + 0.5,
]);
if i > 0 {
let idx = i as u16;
index_data.extend_from_slice(&[idx - 1, idx]);
}
}
index_data.extend_from_slice(&[0, POINTS as u16 - 1]);
self.draw_mode = DrawMode::LINES;
}
self.vertices.set_data(&vertex_data[..]);
self.indices.set_data(&index_data[..]);
self.vertices.bind();
let len = self.vertices.len();
self.vertices.upload_data(0, len, true);
self.indices.bind();
let len = self.indices.len();
self.indices.upload_data(0, len, true);
}
}
impl Drawable for Circle {
fn draw_transformed(&self, view_matrix: &Matrix4<f32>) {
render_target::draw_indices(
self.draw_mode,
&self.vertices,
&self.indices,
&self.render_states(),
view_matrix,
);
}
}
|
use jwt::{self, Header, Algorithm, errors::Result, Validation, TokenData};
const KEY: &str = "secret";
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub user_id: String,
}
pub fn encode(claim: &Claims) -> Result<String> {
jwt::encode(&Header::default(), claim, KEY.as_ref())
}
pub fn decode(token: &String) -> Result<TokenData<Claims>> {
let validation = Validation {
validate_exp: false,
..Default::default()
};
jwt::decode(token, KEY.as_ref(), &validation)
}
|
use eosio::*;
pub struct StoredChainParams {
pub chain_id: Checksum256,
pub chain_name: String,
pub icon: Checksum256,
pub hash: Checksum256,
pub next_unique_id: u64,
}
pub struct ContractAction {
pub contract: AccountName,
pub action: ActionName,
}
pub struct StoredManifest {
pub unique_id: u64,
pub id: Checksum256,
pub account: AccountName,
pub domain: String,
pub appmeta: String,
pub whitelist: Vec<ContractAction>,
}
pub struct AbiHash {
pub owner: AccountName,
pub hash: Checksum256,
}
#[eosio::action]
pub fn setchain(
_chain_id: Ignore<Checksum256>,
_chain_name: Ignore<String>,
_icon: Ignore<Checksum256>,
) {
require_auth(n!("eosio"));
}
// #[eosio::action("add.manifest")]
pub fn add_manifest(
account: Ignore<AccountName>,
domain: Ignore<String>,
appmeta: Ignore<String>,
whitelist: Ignore<Vec<ContractAction>>,
) {
}
// #[eosio::action("del.manifest")]
pub fn del_manifest(id: Checksum256) {}
// #[eosio::action]
pub fn require(
chain_params_hash: Checksum256,
manifest_id: Checksum256,
actions: Vec<ContractAction>,
abi_hashes: Vec<Checksum256>,
) {
}
|
#![allow(dead_code)]
use abi_stable::{
abi_stability::abi_checking::check_layout_compatibility, erased_types::IteratorItem,
std_types::*, DynTrait, StableAbi,
};
macro_rules! mod_iter_ty {
(
mod $module:ident;
type Item<$lt:lifetime>=$ty:ty;
) => {
pub mod $module {
use super::*;
#[repr(C)]
#[derive(abi_stable::StableAbi)]
#[sabi(impl_InterfaceType(Send, Sync, Iterator))]
pub struct Interface;
impl<$lt> IteratorItem<$lt> for Interface {
type Item = $ty;
}
}
};
}
mod no_iterator_interface {
#[repr(C)]
#[derive(abi_stable::StableAbi)]
#[sabi(impl_InterfaceType(Send, Sync))]
pub struct Interface;
}
mod_iter_ty! {
mod rstr_interface;
type Item<'a>=RStr<'a>;
}
mod_iter_ty! {
mod rstring_interface;
type Item<'a>=RString;
}
mod_iter_ty! {
mod u8_interface;
type Item<'a>=u8;
}
mod_iter_ty! {
mod unit_interface;
type Item<'a>=();
}
type BoxTrait<'a, I> = DynTrait<'a, RBox<()>, I>;
#[cfg(not(miri))]
#[test]
fn check_subsets() {
let pref_zero = <DynTrait<'_, RBox<()>, no_iterator_interface::Interface>>::LAYOUT;
let pref_iter_0 = <BoxTrait<'_, rstring_interface::Interface>>::LAYOUT;
let pref_iter_1 = <BoxTrait<'_, rstr_interface::Interface>>::LAYOUT;
let pref_iter_2 = <BoxTrait<'_, u8_interface::Interface>>::LAYOUT;
let pref_iter_3 = <BoxTrait<'_, unit_interface::Interface>>::LAYOUT;
let prefs = vec![pref_iter_0, pref_iter_1, pref_iter_2, pref_iter_3];
assert_eq!(check_layout_compatibility(pref_zero, pref_zero), Ok(()));
for impl_ in prefs.iter().cloned() {
assert_eq!(check_layout_compatibility(pref_zero, impl_), Ok(()));
assert_ne!(check_layout_compatibility(impl_, pref_zero), Ok(()));
}
for (interf_i, interf) in prefs.iter().cloned().enumerate() {
for (impl_i, impl_) in prefs.iter().cloned().enumerate() {
if interf_i == impl_i {
assert_eq!(check_layout_compatibility(interf, impl_), Ok(()));
} else {
assert_ne!(
check_layout_compatibility(interf, impl_),
Ok(()),
"interf:\n{:#?}\n\n\nimpl:\n{:#?}",
interf,
impl_,
);
}
}
}
}
#[cfg(miri)]
#[test]
fn check_subsets_for_miri() {
let pref_iter_0 = <BoxTrait<'_, u8_interface::Interface>>::LAYOUT;
let pref_iter_1 = <BoxTrait<'_, unit_interface::Interface>>::LAYOUT;
assert_eq!(check_layout_compatibility(pref_iter_0, pref_iter_0), Ok(()));
assert_ne!(check_layout_compatibility(pref_iter_0, pref_iter_1), Ok(()));
}
|
/// Construct a [`CloudEvent`] according to spec version 0.2.
///
/// # Errors
///
/// If some of the required fields are missing, or if some of the fields
/// have invalid content an error is returned.
///
/// # Example
///
/// ```
/// use cloudevents::cloudevent_v0_2;
/// use std::error::Error;
///
/// fn main() -> Result<(), Box<Error>> {
/// let cloudevent = cloudevent_v0_2!(
/// event_type: "com.example.object.delete.v2",
/// source: "https://github.com/cloudevents/spec/pull/123",
/// event_id: "0e72b6bd-1341-46b5-9907-efde752682c4",
/// contenttype: "application/json"
/// )?;
/// Ok(())
/// }
///
/// ```
/// [`CloudEvent`]: struct.CloudEventV0_2.html
#[macro_export]
macro_rules! cloudevent_v0_2 {
($( $name:ident: $value:expr $(,)* )+) => {
$crate::v0_2::CloudEventV0_2Builder::default()
$(
.$name($value)
)*
.build()
};
}
|
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![feature(asm)]
extern crate peridot_public_lib_ledger_fidl;
extern crate peridot_bin_ledger_fidl;
extern crate fidl;
extern crate futures;
extern crate garnet_public_lib_app_fidl;
extern crate garnet_public_lib_app_fidl_service_provider;
extern crate fuchsia_zircon as zircon;
extern crate fuchsia_zircon_sys as zircon_sys;
extern crate mxruntime;
extern crate tokio_core;
mod fuchsia;
mod ledger;
use zircon::ClockId;
use tokio_core::reactor;
use fuchsia::{ApplicationContext, Launcher, install_panic_backtrace_hook};
use peridot_public_lib_ledger_fidl::*;
use futures::Future;
pub fn main() {
println!("# installing panic hook");
install_panic_backtrace_hook();
let mut core = reactor::Core::new().unwrap();
let handle = core.handle();
println!("# getting app context");
let mut app_context: ApplicationContext = ApplicationContext::new(&handle).unwrap();
println!("# getting launcher");
let mut launcher = Launcher::new(&mut app_context, &handle).unwrap();
println!("# getting ledger");
let ledger_id = "rust_ledger_example".to_owned().into_bytes();
let repo_path = "/data/test/rust_ledger_example".to_owned();
let key = vec![0];
let future = ledger::LedgerInstance::new(&mut launcher, repo_path, ledger_id, &handle)
.and_then(|instance| {
println!("# getting root page");
Page::new_pair(&handle)
.map(|pair| (pair, instance))
.map_err(ledger::LedgerError::FidlError)
}).and_then(|((page, page_request), mut instance)|
instance.proxy.get_root_page(page_request)
.then(ledger::map_ledger_error)
.map(|()| (instance, page))
).and_then(|(instance, page)| {
// get the current value
println!("# getting page snapshot");
PageSnapshot::new_pair(&handle)
.map_err(ledger::LedgerError::FidlError)
.map(|pair| ((instance, page), pair))
}).and_then(|((instance, mut page), (snap, snap_request))|
page.get_snapshot(snap_request, Some(key.clone()), None)
.then(ledger::map_ledger_error)
.map(|()| (instance, page, snap))
).and_then(|(instance, page, mut snap)| {
println!("# getting key value");
snap.get(key.clone()).then(ledger::map_value_result)
.map(|value_opt| (instance, page, value_opt))
}).and_then(|(instance, mut page, value_opt)| {
println!("got value: {:?}", value_opt);
let as_str = value_opt.and_then(|s| String::from_utf8(s).ok());
println!("got value string: {:?}", as_str);
// put a new value
println!("# putting key value");
let cur_time = zircon::time_get(ClockId::Monotonic);
page.put(key.clone(), cur_time.to_string().into_bytes())
.then(ledger::map_ledger_error)
.map(|put_status| (instance, put_status))
}).map(|(_instance, put_status)| {
println!("put key with put_status: {:?}", put_status);
});
core.run(future).unwrap();
}
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2021-2022 brainpower <brainpower at mailbox dot org>
#![allow(dead_code)]
use std::collections::BTreeMap;
use crate::{CheckArg, Opt, ValueType, RC};
type CheckArgFP = dyn Fn(&CheckArg, &str, &str) -> Result<(), ()>;
impl<'a> CheckArg<'a> {
pub fn new(appname: &str) -> Self {
Self {
appname: String::from(appname),
appendix: None,
descr: None,
usage: format!("{} [options]", appname),
posarg_help_descr: None,
posarg_help_usage: None,
next_is_val_of: None,
valid_options: BTreeMap::new(),
short2long: BTreeMap::new(),
callname: String::new(),
posargs: Vec::new(),
posarg_sep: false,
cleared: true,
}
}
/*
pub fn autonamed(argv: &Vec<&str>) -> Self {
use std::path::Path;
let name = args[0]
.expect("argv must have at least one element");
Self::new(name);
}
pub fn new_with_argv(argv: &Vec<&str>) -> Self {}
// these 2 constructors dont work well with current API,
// which has argv passed to parse, instead of passing them to constructors
// which would enable multiple parsings with the same CheckArg object
// currently incomplete, since parse should return a Result wit isset() and value()
// instead of saving the results directly inside CheckArg.
*/
pub fn add(
&mut self,
sopt: char,
lopt: &str,
help: &str,
value_type: ValueType,
value_name: Option<&str>,
) {
let opt = Opt {
sopt,
lopt: String::from(lopt), // not needed?
help: String::from(help),
value: None,
value_name: match value_name {
None => match &value_type {
ValueType::None => String::new(),
_ => lopt.to_uppercase(),
},
Some(v) => String::from(v),
},
value_type,
cb: None,
};
self.short2long.insert(sopt, opt.lopt.clone());
self.valid_options.insert(opt.lopt.clone(), opt);
}
pub fn add_cb(
&mut self,
sopt: char,
lopt: &str,
help: &str,
cb: impl 'a + FnMut(&CheckArg, &str, &str) -> Result<(), ()>,
value_type: ValueType,
value_name: Option<&str>,
) {
let opt = Opt {
sopt,
lopt: String::from(lopt),
help: String::from(help),
value: None,
value_name: match value_name {
None => match &value_type {
ValueType::None => String::new(),
_ => lopt.to_uppercase(),
},
Some(v) => String::from(v),
},
value_type,
cb: Some(Box::new(cb)),
};
self.short2long.insert(sopt, opt.lopt.clone());
self.valid_options.insert(opt.lopt.clone(), opt);
}
pub fn add_long(
&mut self,
lopt: &str,
help: &str,
value_type: ValueType,
value_name: Option<&str>,
) {
let opt = Opt {
sopt: 0 as char,
lopt: String::from(lopt),
help: String::from(help),
value: None,
value_name: match value_name {
None => match &value_type {
ValueType::None => String::new(),
_ => lopt.to_uppercase(),
},
Some(v) => String::from(v),
},
value_type,
cb: None,
};
self.valid_options.insert(lopt.to_string(), opt);
}
pub fn add_long_cb(
&mut self,
lopt: &str,
help: &str,
cb: impl 'a + FnMut(&CheckArg, &str, &str) -> Result<(), ()>,
value_type: ValueType,
value_name: Option<&str>,
) {
let opt = Opt {
sopt: 0 as char,
lopt: String::from(lopt),
help: String::from(help),
value: None,
value_name: match value_name {
None => match &value_type {
ValueType::None => String::new(),
_ => lopt.to_uppercase(),
},
Some(v) => String::from(v),
},
value_type,
cb: Some(Box::new(cb)),
};
self.valid_options.insert(lopt.to_string(), opt);
}
pub fn add_autohelp(&mut self) {
let opt = Opt {
sopt: 'h',
lopt: String::from("help"),
help: String::from("show this help message and exit"),
value: None,
value_type: ValueType::None,
value_name: String::from(""),
cb: Some(Box::new(|ca, _k, _v| -> Result<(), ()> {
ca.show_help();
std::process::exit(0);
})),
};
self.short2long.insert('h', opt.lopt.clone());
self.valid_options.insert(opt.lopt.clone(), opt);
}
pub fn set_appendix(&mut self, appendix: &str) { self.appendix = Some(String::from(appendix)); }
pub fn set_description(&mut self, desc: &str) { self.descr = Some(String::from(desc)); }
pub fn set_posarg_help(&mut self, usage: &str, desc: &str) {
self.posarg_help_usage = Some(String::from(usage));
self.posarg_help_descr = Some(String::from(desc));
}
pub fn set_usage_line(&mut self, usage: &str) { self.usage = String::from(usage); }
pub fn callname(&self) -> &str { self.callname.as_str() }
pub fn argv0(&self) -> &str { &self.callname[..] }
pub fn pos_args(&self) -> &Vec<String> { &self.posargs }
pub fn value(&self, option: &str) -> Option<&str> {
// println!("option: {}", option);
match self.valid_options.get(option) {
Some(o) => match &o.value {
Some(v) => Some(&v[..]),
None => None,
},
None => None,
}
}
pub fn isset(&self, option: &str) -> bool {
// println!("option: {}", option);
match self.valid_options.get(option) {
Some(opt) => match &opt.value {
Some(_) => true,
None => false,
},
None => false,
}
}
pub fn strerr(code: &RC) -> &'static str {
match code {
RC::Ok => "Everything is fine",
RC::Err => "An error occurred",
RC::InvOpt => "Unknown command line option",
RC::InvVal => "Value given to non-value option",
RC::MissVal => "Missing value of option",
RC::Callback => "Callback returned with error code",
}
}
fn ca_error(code: RC, message: &str) -> RC {
eprintln!("Error: {}: {}", Self::strerr(&code), message);
code
}
pub fn usage(&self) -> String {
match &self.posarg_help_usage {
None => format!("Usage: {}", self.usage),
Some(s) => format!("Usage: {} {}", self.usage, s),
}
}
pub fn autohelp(&self) -> String {
let mut ss: String;
let mut space: usize = 0;
for (lopt, opt) in &self.valid_options {
let vsize: usize = match opt.value_type {
ValueType::None => 0,
_ => match opt.value_name.len() {
0 => 0,
l => l + 1, // account for the '=' sign
},
};
space = std::cmp::max(space, vsize + lopt.len());
}
space += 2; // add space between options and help messages
ss = format!("{}\n", self.usage());
// generously allocate space, shrink_to_fit later,
ss.reserve(self.valid_options.len() * (space + 255));
// add description if exists
if let Some(desc) = &self.descr {
ss += format!("\n{}\n", desc).as_str();
}
// add options with their help messages
ss.push_str("\nOptions:\n");
for (lopt, opt) in &self.valid_options {
match opt.sopt {
'\0' => ss += " ",
_ => ss += format!(" -{},", opt.sopt).as_str(),
}
ss += " --";
ss += lopt.as_str();
ss += match opt.value_type {
ValueType::None => std::iter::repeat(' ')
.take(space - lopt.len())
.collect::<String>(),
ValueType::Required => match opt.value_name.len() {
0 => std::iter::repeat(' ')
.take(space - lopt.len())
.collect::<String>(),
x => format!("={}{:2$}", opt.value_name, " ", space - x - 1 - lopt.len()),
},
}
.as_str();
ss += opt.help.as_str();
ss += "\n";
}
if let Some(ph) = &self.posarg_help_descr {
ss += format!("\nPositional Arguments:\n{}\n", ph).as_str();
}
if let Some(ap) = &self.appendix {
ss += format!("\n{}\n", ap).as_str()
}
ss.shrink_to_fit();
ss
}
pub fn show_help(&self) {
println!("{}", self.autohelp());
}
pub fn show_usage(&self) {
println!("{}", self.usage());
}
fn produce_error(&self) -> RC { RC::Err }
pub fn reset(&mut self) {
// clear and reset positional args in case of reuse / a second parse
self.posarg_sep = false;
self.posargs.clear();
self.next_is_val_of = None;
for (_, opt) in &mut self.valid_options {
opt.value = None;
}
self.cleared = true;
}
pub fn parse(&mut self, argv: &Vec<&str>) -> RC {
let mut ret = RC::Ok;
assert!(argv.len() > 0, "argv must have at least one element"); // the "callname"
// clear and reset state in case of reuse / a second parse
if !self.cleared {
self.reset();
}
self.cleared = false;
self.callname = argv
.first()
.expect("argv must have at least one element")
.to_string();
for arg in &argv[1..] {
//println!("Found: {:?}", arg);
ret = self.arg(arg);
}
if matches!(ret, RC::Ok) && !matches!(self.next_is_val_of, None) {
self.next_is_val_of = None; // reset before returning, in case of reuse / a second parse
return Self::ca_error(
RC::MissVal,
match argv.last() {
Some(s) => s,
_ => "",
},
);
}
ret
}
fn arg(&mut self, arg: &str) -> RC {
if !self.posarg_sep {
let next_is_val_of = self.next_is_val_of.take();
//println!("next_is_val_of: {:?}, arg: {}", next_is_val_of, arg);
// arg is expected to be the value of the previous option
if let Some(lopt) = &next_is_val_of {
//println!("is value of {:?}: {:?}", lopt, arg);
let opt = self
.valid_options
.get_mut(lopt)
.expect("BUG: next_is_val_of should always contain a valid option or None");
opt.value = Some(String::from(arg));
let ret = self.call_cb(&lopt);
self.next_is_val_of = None;
return ret;
}
// check for options
if arg.starts_with('-') {
if arg.starts_with("--") {
//println!("is long opt: {:?}", arg);
return self.arg_long(&arg[2..]);
}
//println!("is short opt: {:?}", arg);
return self.arg_short(&arg[1..]);
}
}
//println!("debug: adding posarg: {}", arg);
// everything else is a positional argument
self.posargs.push(String::from(arg));
RC::Ok
}
fn arg_short(&mut self, arg: &str) -> RC {
for (i, c) in arg.char_indices() {
let lopt = match self.short2long.get(&c) {
None => return Self::ca_error(RC::InvOpt, String::from(c).as_str()),
Some(lopt) => lopt,
};
let opt = self
.valid_options
.get_mut(lopt)
.expect("BUG: this should never happen");
// println!("{}: fount matching long opt: {}", c, lopt);
if let ValueType::None = opt.value_type {
//println!("short opt has no value: -{}", arg);
opt.value = Some(String::new());
let cbopt = lopt.clone();
if let RC::Callback = self.call_cb(&cbopt) {
return RC::Callback;
}
}
else {
// println!("{}: short opt has value: {}", c, arg);
// option has value, treat the rest of arg as value
// if we're not at the end
let mut j = i + 1;
//println!("j: {}, i: {}, arg.len(): {}", j, i, arg.len());
if j >= arg.len() {
// println!("{}: value is next arg", c);
self.next_is_val_of = Some(lopt.clone());
}
else {
//println!("value stuck to option: -{}", arg);
while !arg.is_char_boundary(j) {
j += 1;
}
opt.value = Some(String::from(&arg[j..]));
let cbopt = lopt.clone();
return self.call_cb(&cbopt);
}
return RC::Ok;
}
}
RC::Ok
}
fn arg_long(&mut self, arg: &str) -> RC {
// println!("longarg: {}", arg);
if arg.is_empty() {
// got '--', the positional args separator
self.posarg_sep = true;
return RC::Ok;
}
let (opt, val) = match arg.split_once('=') {
None => (arg, None),
Some((o, v)) => (o, Some(v)),
};
//println!("opt: {}, val: {}", opt, val.unwrap());
let vopt = match self.valid_options.get_mut(opt) {
None => return Self::ca_error(RC::InvOpt, format!("--{}!", arg).as_str()),
Some(o) => o,
};
if let ValueType::Required = vopt.value_type {
// println!("{}: has required value", opt);
if let Some(val) = val {
// value was given using '='
vopt.value = Some(val.to_string());
// println!("{}: value was given using '='", opt);
return self.call_cb(&opt.to_string());
}
else {
// value is in the next arg, clone because of borrow and lifetime checker :(
// opts will live as long as CheckArg anyway, there is no removal functions!
// but I have not found a good way to convince rustc of that :/
self.next_is_val_of = Some(vopt.lopt.clone());
}
}
else {
// option has no value
if val.is_some() {
// but a value was given!
return Self::ca_error(RC::InvVal, format!("--{}!", opt).as_str());
}
vopt.value = Some(String::new());
if self.next_is_val_of.is_none() {
return self.call_cb(&opt.to_string());
}
}
RC::Ok
}
fn call_cb(&mut self, lopt: &String) -> RC {
let opt = self
.valid_options
.get_mut(lopt)
// we have checked the existence of lopt before using it here
// possible to pass value as parameter here?
.expect("BUG: this should always get a valid lopt");
let val = match &opt.value {
None => String::new(),
Some(v) => v.clone(),
};
let callback = opt.cb.take();
match callback {
None => RC::Ok,
Some(mut cb) => match cb(self, lopt.as_str(), val.as_str()) {
Result::Ok(()) => RC::Ok,
Result::Err(()) => RC::Callback,
},
}
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::parser_common::{
all_consuming, bool_literal, compound_identifier, map_err, numeric_literal, string_literal,
using_list, ws, BindParserError, CompoundIdentifier, Include,
};
use nom::{
branch::alt,
bytes::complete::tag,
combinator::{map, opt, value},
multi::{many1, separated_nonempty_list},
sequence::{delimited, preceded, terminated, tuple},
IResult,
};
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq)]
pub struct Ast {
pub using: Vec<Include>,
pub statements: Vec<Statement>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ConditionOp {
Equals,
NotEquals,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
NumericLiteral(u64),
StringLiteral(String),
BoolLiteral(bool),
Identifier(CompoundIdentifier),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
lhs: CompoundIdentifier,
op: ConditionOp,
rhs: Value,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
ConditionStatement(Condition),
Accept { identifier: CompoundIdentifier, values: Vec<Value> },
If { blocks: Vec<(Condition, Vec<Statement>)>, else_block: Vec<Statement> },
}
// TODO(fxb/35146): Improve error reporting here.
impl FromStr for Ast {
type Err = BindParserError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
match program(input) {
Ok((_, ast)) => Ok(ast),
Err(nom::Err::Error(e)) => Err(e),
Err(nom::Err::Failure(e)) => Err(e),
Err(nom::Err::Incomplete(_)) => {
unreachable!("Parser should never generate Incomplete errors")
}
}
}
}
fn condition_op(input: &str) -> IResult<&str, ConditionOp, BindParserError> {
let equals = value(ConditionOp::Equals, tag("=="));
let not_equals = value(ConditionOp::NotEquals, tag("!="));
map_err(alt((equals, not_equals)), BindParserError::ConditionOp)(input)
}
fn condition_value(input: &str) -> IResult<&str, Value, BindParserError> {
let string = map(ws(string_literal), Value::StringLiteral);
let number = map(ws(numeric_literal), Value::NumericLiteral);
let boolean = map(ws(bool_literal), Value::BoolLiteral);
let identifer = map(ws(compound_identifier), Value::Identifier);
alt((string, number, boolean, identifer))(input)
.or(Err(nom::Err::Error(BindParserError::ConditionValue(input.to_string()))))
}
fn condition(input: &str) -> IResult<&str, Condition, BindParserError> {
let (input, lhs) = ws(compound_identifier)(input)?;
let (input, op) = condition_op(input)?;
let (input, rhs) = condition_value(input)?;
Ok((input, Condition { lhs, op, rhs }))
}
fn condition_statement(input: &str) -> IResult<&str, Statement, BindParserError> {
let terminator = map_err(ws(tag(";")), BindParserError::Semicolon);
map(terminated(condition, terminator), Statement::ConditionStatement)(input)
}
fn keyword_if(input: &str) -> IResult<&str, &str, BindParserError> {
map_err(ws(tag("if")), BindParserError::IfKeyword)(input)
}
fn keyword_else(input: &str) -> IResult<&str, &str, BindParserError> {
map_err(ws(tag("else")), BindParserError::ElseKeyword)(input)
}
fn if_statement(input: &str) -> IResult<&str, Statement, BindParserError> {
let if_block = tuple((preceded(keyword_if, condition), statement_block));
let if_blocks = separated_nonempty_list(keyword_else, if_block);
let else_block = preceded(keyword_else, statement_block);
let (input, blocks) = if_blocks(input)?;
let (input, else_block) = else_block(input)?;
Ok((input, Statement::If { blocks, else_block }))
}
fn statement_block(input: &str) -> IResult<&str, Vec<Statement>, BindParserError> {
let block_start = map_err(tag("{"), BindParserError::IfBlockStart);
let block_end = map_err(tag("}"), BindParserError::IfBlockEnd);
delimited(block_start, many1(ws(statement)), block_end)(input)
}
fn keyword_accept(input: &str) -> IResult<&str, &str, BindParserError> {
map_err(ws(tag("accept")), BindParserError::AcceptKeyword)(input)
}
fn accept(input: &str) -> IResult<&str, Statement, BindParserError> {
let list_start = map_err(tag("{"), BindParserError::ListStart);
let list_end = map_err(tag("}"), BindParserError::ListEnd);
let separator = || map_err(ws(tag(",")), BindParserError::ListSeparator);
let values = separated_nonempty_list(separator(), ws(condition_value));
// Lists may optionally be terminated by an additional trailing separator.
let values = terminated(values, opt(separator()));
let value_list = delimited(list_start, values, list_end);
map(
preceded(keyword_accept, tuple((ws(compound_identifier), value_list))),
|(identifier, values)| Statement::Accept { identifier, values },
)(input)
}
fn statement(input: &str) -> IResult<&str, Statement, BindParserError> {
alt((condition_statement, if_statement, accept))(input)
}
fn program(input: &str) -> IResult<&str, Ast, BindParserError> {
let statements = many1(ws(statement));
map(all_consuming(tuple((ws(using_list), statements))), |(using, statements)| Ast {
using,
statements,
})(input)
}
#[cfg(test)]
mod test {
use super::*;
use crate::make_identifier;
mod condition_ops {
use super::*;
#[test]
fn equality() {
assert_eq!(condition_op("=="), Ok(("", ConditionOp::Equals)));
}
#[test]
fn inequality() {
assert_eq!(condition_op("!="), Ok(("", ConditionOp::NotEquals)));
}
#[test]
fn invalid() {
assert_eq!(
condition_op(">="),
Err(nom::Err::Error(BindParserError::ConditionOp(">=".to_string())))
);
}
#[test]
fn empty() {
assert_eq!(
condition_op(""),
Err(nom::Err::Error(BindParserError::ConditionOp("".to_string())))
);
}
}
mod condition_values {
use super::*;
#[test]
fn string() {
assert_eq!(
condition_value(r#""abc""#),
Ok(("", Value::StringLiteral("abc".to_string())))
);
}
#[test]
fn bool() {
assert_eq!(condition_value("true"), Ok(("", Value::BoolLiteral(true))));
}
#[test]
fn number() {
assert_eq!(condition_value("123"), Ok(("", Value::NumericLiteral(123))));
}
#[test]
fn identifier() {
assert_eq!(
condition_value("abc"),
Ok(("", Value::Identifier(make_identifier!["abc"])))
);
}
#[test]
fn empty() {
// Does not match empty string.
assert_eq!(
condition_value(""),
Err(nom::Err::Error(BindParserError::ConditionValue("".to_string())))
);
}
}
mod conditions {
use super::*;
#[test]
fn equality_condition() {
assert_eq!(
condition("abc == true"),
Ok((
"",
Condition {
lhs: make_identifier!["abc"],
op: ConditionOp::Equals,
rhs: Value::BoolLiteral(true),
}
))
);
}
#[test]
fn empty() {
assert_eq!(
condition(""),
Err(nom::Err::Error(BindParserError::Identifier("".to_string())))
);
}
}
mod if_statements {
use super::*;
#[test]
fn simple() {
assert_eq!(
if_statement("if a == b { c == 1; } else { d == 2; }"),
Ok((
"",
Statement::If {
blocks: vec![(
Condition {
lhs: make_identifier!["a"],
op: ConditionOp::Equals,
rhs: Value::Identifier(make_identifier!["b"]),
},
vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["c"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(1),
})]
)],
else_block: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["d"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(2),
})],
}
))
);
}
#[test]
fn else_if() {
assert_eq!(
if_statement("if a == b { c == 1; } else if e == 3 { d == 2; } else { f != 4; }"),
Ok((
"",
Statement::If {
blocks: vec![
(
Condition {
lhs: make_identifier!["a"],
op: ConditionOp::Equals,
rhs: Value::Identifier(make_identifier!["b"]),
},
vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["c"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(1),
})]
),
(
Condition {
lhs: make_identifier!["e"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(3),
},
vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["d"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(2),
})]
),
],
else_block: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["f"],
op: ConditionOp::NotEquals,
rhs: Value::NumericLiteral(4),
})],
}
))
);
}
#[test]
fn nested() {
assert_eq!(
if_statement(
"if a == 1 { if b == 2 { c != 3; } else { c == 3; } } else { d == 2; }"
),
Ok((
"",
Statement::If {
blocks: vec![(
Condition {
lhs: make_identifier!["a"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(1),
},
vec![Statement::If {
blocks: vec![(
Condition {
lhs: make_identifier!["b"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(2),
},
vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["c"],
op: ConditionOp::NotEquals,
rhs: Value::NumericLiteral(3),
})],
)],
else_block: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["c"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(3),
})],
}]
)],
else_block: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["d"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(2),
})],
}
))
);
}
#[test]
fn invalid() {
// Must have 'if' keyword.
assert_eq!(
if_statement("a == b { c == 1; }"),
Err(nom::Err::Error(BindParserError::IfKeyword("a == b { c == 1; }".to_string())))
);
// Must have condition.
assert_eq!(
if_statement("if { c == 1; }"),
Err(nom::Err::Error(BindParserError::Identifier("{ c == 1; }".to_string())))
);
// Must have else block.
assert_eq!(
if_statement("if a == b { c == 1; }"),
Err(nom::Err::Error(BindParserError::ElseKeyword("".to_string())))
);
assert_eq!(
if_statement("if a == b { c == 1; } else if e == 3 { d == 2; }"),
Err(nom::Err::Error(BindParserError::ElseKeyword("".to_string())))
);
// Must delimit blocks with {}s.
assert_eq!(
if_statement("if a == b c == 1; }"),
Err(nom::Err::Error(BindParserError::IfBlockStart("c == 1; }".to_string())))
);
assert_eq!(
if_statement("if a == b { c == 1;"),
Err(nom::Err::Error(BindParserError::IfBlockEnd("".to_string())))
);
}
#[test]
fn empty() {
assert_eq!(
if_statement(""),
Err(nom::Err::Error(BindParserError::IfKeyword("".to_string())))
);
}
}
mod accepts {
use super::*;
#[test]
fn simple() {
assert_eq!(
accept("accept a { 1 }"),
Ok((
"",
Statement::Accept {
identifier: make_identifier!["a"],
values: vec![Value::NumericLiteral(1)],
}
))
);
}
#[test]
fn multiple_values() {
assert_eq!(
accept("accept a { 1, 2 }"),
Ok((
"",
Statement::Accept {
identifier: make_identifier!["a"],
values: vec![Value::NumericLiteral(1), Value::NumericLiteral(2),],
}
))
);
}
#[test]
fn trailing_comma() {
assert_eq!(
accept("accept a { 1, 2, }"),
Ok((
"",
Statement::Accept {
identifier: make_identifier!["a"],
values: vec![Value::NumericLiteral(1), Value::NumericLiteral(2),],
}
))
);
}
#[test]
fn invalid() {
// Must have accept keyword.
assert_eq!(
accept("a { 1 }"),
Err(nom::Err::Error(BindParserError::AcceptKeyword("a { 1 }".to_string())))
);
// Must have identifier.
assert_eq!(
accept("accept { 1 }"),
Err(nom::Err::Error(BindParserError::Identifier("{ 1 }".to_string())))
);
// Must have at least one value.
assert_eq!(
accept("accept a { }"),
Err(nom::Err::Error(BindParserError::ConditionValue("}".to_string())))
);
// Must delimit blocks with {}s.
assert_eq!(
accept("accept a 1 }"),
Err(nom::Err::Error(BindParserError::ListStart("1 }".to_string())))
);
assert_eq!(
accept("accept a { 1"),
Err(nom::Err::Error(BindParserError::ListEnd("".to_string())))
);
}
#[test]
fn empty() {
assert_eq!(
accept(""),
Err(nom::Err::Error(BindParserError::AcceptKeyword("".to_string())))
);
}
}
mod programs {
use super::*;
#[test]
fn simple() {
assert_eq!(
program("using a; x == 1;"),
Ok((
"",
Ast {
using: vec![Include { name: make_identifier!["a"], alias: None }],
statements: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["x"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(1),
})]
}
))
);
}
#[test]
fn empty() {
// TODO(fxb/35146): Improve the error type that is returned here.
assert_eq!(
program(""),
Err(nom::Err::Error(BindParserError::AcceptKeyword("".to_string())))
);
}
#[test]
fn requires_statement() {
// Must have an statement.
assert_eq!(
program("using a;"),
Err(nom::Err::Error(BindParserError::AcceptKeyword("".to_string())))
);
}
#[test]
fn using_list_optional() {
assert_eq!(
program("x == 1;"),
Ok((
"",
Ast {
using: vec![],
statements: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["x"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(1),
})]
}
))
);
}
#[test]
fn requires_semicolons() {
// TODO(fxb/35146): Improve the error type that is returned here.
assert_eq!(
program("x == 1"),
Err(nom::Err::Error(BindParserError::AcceptKeyword("x == 1".to_string())))
);
}
#[test]
fn multiple_statements() {
assert_eq!(
program("x == 1; accept y { true } if z == 2 { a != 3; } else { a == 3; }"),
Ok((
"",
Ast {
using: vec![],
statements: vec![
Statement::ConditionStatement(Condition {
lhs: make_identifier!["x"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(1),
}),
Statement::Accept {
identifier: make_identifier!["y"],
values: vec![Value::BoolLiteral(true)],
},
Statement::If {
blocks: vec![(
Condition {
lhs: make_identifier!["z"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(2),
},
vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["a"],
op: ConditionOp::NotEquals,
rhs: Value::NumericLiteral(3),
})]
)],
else_block: vec![Statement::ConditionStatement(Condition {
lhs: make_identifier!["a"],
op: ConditionOp::Equals,
rhs: Value::NumericLiteral(3),
})],
}
]
}
))
);
}
}
}
|
#![recursion_limit = "256"]
#![doc(html_root_url = "https://docs.rs/auto_enums_derive/0.6.3")]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code))
))]
#![warn(unsafe_code)]
#![warn(rust_2018_idioms, unreachable_pub)]
#![warn(single_use_lifetimes)]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::use_self)]
#[cfg(all(feature = "try_trait", not(feature = "unstable")))]
compile_error!(
"The `try_trait` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
#[cfg(all(feature = "futures", not(feature = "unstable")))]
compile_error!(
"The `futures` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
#[cfg(all(feature = "generator_trait", not(feature = "unstable")))]
compile_error!(
"The `generator_trait` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
#[cfg(all(feature = "fn_traits", not(feature = "unstable")))]
compile_error!(
"The `fn_traits` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
#[cfg(all(feature = "trusted_len", not(feature = "unstable")))]
compile_error!(
"The `trusted_len` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
#[cfg(all(feature = "exact_size_is_empty", not(feature = "unstable")))]
compile_error!(
"The `exact_size_is_empty` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
#[cfg(all(feature = "read_initializer", not(feature = "unstable")))]
compile_error!(
"The `read_initializer` feature requires the `unstable` feature as an explicit opt-in to unstable features"
);
extern crate proc_macro;
#[macro_use]
mod utils;
mod derive;
mod enum_derive;
use proc_macro::TokenStream;
/// An attribute macro like a wrapper of `#[derive]`, implementing
/// the supported traits and passing unsupported traits to `#[derive]`.
#[proc_macro_attribute]
pub fn enum_derive(args: TokenStream, input: TokenStream) -> TokenStream {
TokenStream::from(self::enum_derive::attribute(args.into(), input.into()))
}
|
#![allow(dead_code)]
use std::mem::transmute;
use std::ptr::copy_nonoverlapping;
macro_rules! write_num_bytes {
($ty:ty, $size:expr, $dst:expr, $n:expr, $which:ident) => ({
assert!($size <= $dst.len());
unsafe {
// N.B. https://github.com/rust-lang/rust/issues/22776
let bytes = transmute::<_, [u8; $size]>($n.$which());
copy_nonoverlapping((&bytes).as_ptr(), $dst.as_mut_ptr(), $size);
}
})
}
#[inline]
pub fn put_u8(buf:&mut[u8], n:u8) {
buf[0] = n;
}
#[inline]
pub fn put_i8(buf:&mut[u8], n:i8) {
buf[0] = n as u8;
}
#[inline]
pub fn put_u16l(buf:&mut[u8], n:u16) {
write_num_bytes!(u16, 2, buf, n, to_le);
}
#[inline]
pub fn put_u16b(buf:&mut[u8], n:u16) {
write_num_bytes!(u16, 2, buf, n, to_be);
}
#[inline]
pub fn put_u32l(buf:&mut[u8], n:u32) {
write_num_bytes!(u32, 4, buf, n, to_le);
}
#[inline]
pub fn put_u32b(buf:&mut[u8], n:u32) {
write_num_bytes!(u32, 4, buf, n, to_be);
}
#[inline]
pub fn put_u64l(buf:&mut[u8], n:u64) {
write_num_bytes!(u64, 8, buf, n, to_le);
}
#[inline]
pub fn put_u64b(buf:&mut[u8], n:u64) {
write_num_bytes!(u64, 8, buf, n, to_be);
}
#[inline]
pub fn put_i16l(buf:&mut[u8], n:i16) {
put_u16l(buf, n as u16);
}
#[inline]
pub fn put_i16b(buf:&mut[u8], n:i16) {
put_u16b(buf, n as u16);
}
#[inline]
pub fn put_i32l(buf:&mut[u8], n:i32) {
put_u32l(buf, n as u32);
}
#[inline]
pub fn put_i32b(buf:&mut[u8], n:i32) {
put_u32b(buf, n as u32);
}
#[inline]
pub fn put_i64l(buf:&mut[u8], n:i64) {
put_u64l(buf, n as u64);
}
#[inline]
pub fn put_i64b(buf:&mut[u8], n:i64) {
put_u64b(buf, n as u64);
}
#[inline]
pub fn put_f32l(buf:&mut[u8], n:f32) {
put_u32l(buf, unsafe { transmute(n) });
}
#[inline]
pub fn put_f32b(buf:&mut[u8], n:f32) {
put_u32b(buf, unsafe { transmute(n) });
}
#[inline]
pub fn put_f64l(buf:&mut[u8], n:f64) {
put_u64l(buf, unsafe { transmute(n) });
}
#[inline]
pub fn put_f64b(buf:&mut[u8], n:f64) {
put_u64b(buf, unsafe { transmute(n) });
}
#[cfg(test)]
mod test {
use super::*;
use byteread::*;
#[test]
fn put_and_get_u8() {
let mut buf = [0; 3];
put_u8(&mut buf, 1);
assert!(1 == get_u8(&mut buf));
put_u8(&mut buf[1..], 2);
assert!(2 == get_u8(&mut buf[1..]));
put_u8(&mut buf[2..], 255);
assert!(255 == get_u8(&mut buf[2..]));
}
#[test]
fn put_and_get_i8() {
let mut buf = [0; 3];
put_i8(&mut buf, 1);
assert!(1 == get_i8(&mut buf));
put_i8(&mut buf[1..], 2);
assert!(2 == get_i8(&mut buf[1..]));
put_i8(&mut buf[2..], -128);
assert!(-128 == get_i8(&mut buf[2..]));
}
}
|
use std::net::{SocketAddr, TcpListener};
use std::{thread, time};
use failure::Error;
use failure::ResultExt;
use rand::Rng;
// We do this shenanigans to (hopefully) avoid a race condition where
// two threads test that a port is "free" one after the other, but before
// either is able to start it's driver.
pub fn unused_port_no() -> Result<u16, Error> {
let mut rng = rand::thread_rng();
loop {
let port = rng.gen_range(4444u16, u16::max_value());
let a = SocketAddr::from(([127, 0, 0, 1], port));
debug!("Trying to bind to address: {:?}", a);
if let Some(l) = TcpListener::bind(a)
.map(Some)
.or_else(|e| {
if e.kind() == std::io::ErrorKind::AddrInUse {
info!("Retrying");
Ok(None)
} else {
warn!("Error binding to {:?}; kind:{:?}; {:?}", a, e.kind(), e);
Err(e)
}
})
.context("Binding to ephemeral port")?
{
let addr = l.local_addr().context("Listener local port")?;
info!("Available: {}", addr);
return Ok(addr.port());
}
}
}
pub(crate) fn wait_until<F: FnMut() -> Result<bool, Error>>(
deadline: time::Duration,
mut check: F,
) -> Result<bool, Error> {
let mut pause_time = time::Duration::from_millis(1);
let started_at = time::Instant::now();
while started_at.elapsed() < deadline && !check()? {
debug!("Pausing for {:?}", pause_time);
thread::sleep(pause_time);
pause_time *= 2;
}
Ok(check()?)
}
|
use std::old_io::TcpStream;
use std::old_io::IoResult;
use std::rand;
use std::rand::Rng;
use std::old_io::Timer;
use std::time::duration::Duration;
use std::os;
use std::num::Float;
fn main() {
let mut dbname = "house.floor1.room1.sensor1".to_string();
let args: Vec<String> = os::args();
if args.len() >= 2 {
dbname = args[1].clone();
}
let namespace: &str = dbname.as_slice();
let interval = Duration::milliseconds(1000);
let mut timer = Timer::new().unwrap();
let mut rng = rand::thread_rng();
let two_pi = 6.28318530718;
let mut socket: TcpStream = TcpStream::connect("localhost:8000").unwrap();
send_str(namespace, &mut socket).unwrap();
let v: Vec<f64> = rng.gen_iter::<f64>().take(250).collect();
for i in v.iter() {
// Start a one second timer
let oneshot = timer.oneshot(interval);
println!("Wait {} ms...", interval.num_milliseconds());
// Block the task until notification arrives (aka the timer is done)
oneshot.recv().unwrap();
// Generate a random number (alternates between -40 and 40 slowly)
let mid: f64 = (*i / two_pi).sin();
let num: f64 = rng.gen_range(mid * 40.0 - 1.0, mid * 40.0 + 1.0);
// Send the random number through sockets to the server
match socket.write_be_f64(num) {
Ok(x) => x,
Err(x) => {
println!("{}", x);
break;
},
}
println!("sent {}", num)
}
drop(socket)
}
fn send_str(string: &str, socket: &mut TcpStream) -> IoResult<()> {
let u32_length = string.len() as u32;
try!(socket.write_be_u32(u32_length));
socket.write(string.as_bytes())
} |
use crate::utils::*;
pub(crate) const NAME: &[&str] = &["futures01::Stream"];
pub(crate) fn derive(data: &Data, items: &mut Vec<ItemImpl>) -> Result<()> {
let crate_ = quote!(::futures);
derive_trait!(
data,
parse_quote!(#crate_::stream::Stream)?,
parse_quote! {
trait Stream {
type Item;
type Error;
#[inline]
fn poll(&mut self) -> #crate_::Poll<::core::option::Option<Self::Item>, Self::Error>;
}
}?,
)
.map(|item| items.push(item))
}
|
use std::fmt::Debug;
use std::fmt::Display;
//Trait可以让Rust编译器知道某个特定类型具有的功能,并可以与其他类型共享
//使用Trait可以以抽象的方式定义共享行为
//我们可以使用Trait界限来指定泛型可以是任何具有特定行为的类型
//类似于Java中的接口
pub fn trait_demo() {
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
};
println!("1 new tweet:{}", tweet.summarize());
let article = NewsArticle {
headline: String::from("Penguins win the Stanley Cup Championship!"),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from(
"The Pittsburgh Penguins once again are the best
hockey team in the NHL.",
),
};
println!("New article available! {}", article.summarize());
println!("New article available! {}", article.summarize_d());
println!("New article available! {}", article.summarize_d2());
notify(article);
//println!("{}", article.summarize()); //这里article的所有权已经move到notify中了,不能使用了
notify1(tweet);
//println!("{}", tweet.summarize()); //同上,没有了所有权
let tweet2 = Tweet {
username: String::from("世界之窗"),
content: String::from("hello,欢迎来到月球"),
reply: false,
retweet: false,
};
notify_without_ownership(&tweet2);
println!("tweet2.author:{}", tweet2.summarize_author());
}
//trait实现需要注意的一个限制是,只有当trait或类型是我们本地crate时,才能在类型上实现trait。
//例如,我们可以在自定义类型像Tweet上实现标准库中的Display trait,因为Tweet是我们本地crate的类型
//我们也可以在我们的crate中让Vec<T>实现Summary trait,因为Summary是本地crate中的
//但是我们不能在外部的类型上实现外部的trait。
//例如不能在Vec<T>类型上实现Display trait,因为这两个都是定义在标准库中,而不是本地crate中
//这个限制是程序属性的一部分,叫做“一致性”,更具体地说是“孤儿规则”,之所以这样命名是因为父类型不存在。
//该规则确保其他人的代码不会破坏你的代码,反之亦然。
//如果没有这个规则,两个crates可以为同一类型实现相同的特性,这时Rust不知道使用哪个实现。
//定义一个Trait
//文章概要接口
pub trait Summary {
fn summarize(&self) -> String;
//trait方法可以有默认实现
fn summarize_d(&self) -> String {
String::from("(Read more...)")
}
//trait方法默认实现可以调用trait中其他的方法,无论该方法是否默认实现
//这样可以帮助我们实现很多模版代码,而把小部分具体的工作交给实现类去做
fn summarize_author(&self) -> String;
fn summarize_d2(&self) -> String {
format!("(Read more from {} ...)", self.summarize_author())
}
}
//Trait可以作为参数,这样让函数可以接收任意实现了该Trait的类型
pub fn notify(item: impl Summary) {
//这里会take ownership
println!("Breaking news! {}", item.summarize());
}
//Trait作为边界语法
//上面作为参数的方法实际是trait边界的语法糖,trait bound 语法如下:
pub fn notify1<T: Summary>(item: T) {
println!("Breaking news! {}", item.summarize());
}
pub fn notify_without_ownership<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
//一些边界例子
pub fn notify2(item1: impl Summary, item2: impl Summary) {}
//两个相同类型的参数
pub fn notify2_2<T: Summary>(item1: T, item2: T) {}
//实现多个Trait
pub fn notify3(item: impl Summary + Display) {}
pub fn notify3_2<T: Summary + Display>(item: T) {}
//使用太多的trait界限有一定的负面影响。
//每个泛型都有自己的trait界限,因此具有多个泛型类型的函数可能在函数签名及其列表之间包含大量trait界限信息
//这使得函数签名很难阅读
//可以在函数签名后面使用where子句来指定trait界限
fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
//do something
0
}
//上面的函数签名真的难看,使用where句子来拯救函数签名:函数名称,参数列表和返回类型非常接近,就像没有trait边界一样
fn some_function2<T, U>(t: T, u: U) -> i32
where
T: Display + Clone,
U: Clone + Debug,
{
//do something
0
}
//可以在函数返回中返回Trait,这在闭包和迭代中很有用
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
}
}
//使用Trait界限来有条件的实现方法
struct Pair<T> {
x: T,
y: T,
}
//每个Pair类型都有一个new方法用于构建
impl<T> Pair<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
//只有实现了Display + PartialOrd类型的Pair才能使用cmp_display方法
impl<T: Display + PartialOrd> Pair<T> {
fn cmp_display(&self) {
if self.x >= self.y {
println!("The largest member is x = {}", self.x);
} else {
println!("The largest member is y = {}", self.y);
}
}
}
//还可以为实现了某个Trait的类型T实现另一个Trait
//任何类型上满足特征边界的特征的实现都称为全面实现,在Rust标准库中广泛使用
//例如,标准库对实现Display trait的任何类型都实现ToString trait。像下面这样:
// impl<T: Display> ToString for T {
// // --snip--
// }
//新闻
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
//为NewsArticle实现Summary Trait
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{},by {} ({})", self.headline, self.author, self.location)
}
fn summarize_author(&self) -> String {
format!("@{}", self.author)
}
}
//微博
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
//为Tweet实现Summary Trait
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
}
|
mod sort;
mod sort_test; |
pub const PINB: *mut u8 = 0x23 as *mut u8;
pub const DDRB: *mut u8 = 0x24 as *mut u8;
pub const PORTB: *mut u8 = 0x25 as *mut u8;
pub const PINC: *mut u8 = 0x26 as *mut u8;
pub const DDRC: *mut u8 = 0x27 as *mut u8;
pub const PORTC: *mut u8 = 0x28 as *mut u8;
pub const PIND: *mut u8 = 0x29 as *mut u8;
pub const DDRD: *mut u8 = 0x2a as *mut u8;
pub const PORTD: *mut u8 = 0x2b as *mut u8;
pub const TCCR1B: *mut u8 = 0x81 as *mut u8;
pub const TIMSK1: *mut u8 = 0x6f as *mut u8;
pub const OCR1A: *mut u16 = 0x88 as *mut u16;
// SPI
pub const SPCR: *mut u8 = 0x4c as *mut u8;
pub const SPSR: *mut u8 = 0x4d as *mut u8;
pub const SPDR: *mut u8 = 0x4e as *mut u8;
|
use proc_macro2::Span;
use syn::parse::{Parse, ParseStream, Result};
use syn::{LitInt, Path, Token};
pub enum Args {
None,
With(Path, LitInt),
}
impl Parse for Args {
fn parse(input: ParseStream) -> Result<Self> {
if input.is_empty() {
Ok(Args::None)
} else {
let path = input.parse::<Path>()?;
if input.is_empty() {
return Ok(Self::With(path, LitInt::new("0", Span::call_site())));
}
input.parse::<Token![,]>()?;
let weight = input.parse::<LitInt>()?;
Ok(Self::With(path, weight))
}
}
}
|
use models::node::{
closest_packable_fee_amount, is_fee_amount_packable, FranklinTx, Nonce, Token, TokenLike,
};
use num::BigUint;
use crate::{error::ClientError, operations::SyncTransactionHandle, wallet::Wallet};
#[derive(Debug)]
pub struct ChangePubKeyBuilder<'a> {
wallet: &'a Wallet,
onchain_auth: bool,
fee_token: Option<Token>,
fee: Option<BigUint>,
nonce: Option<Nonce>,
}
impl<'a> ChangePubKeyBuilder<'a> {
/// Initializes a transfer transaction building process.
pub fn new(wallet: &'a Wallet) -> Self {
Self {
wallet,
onchain_auth: false,
fee_token: None,
fee: None,
nonce: None,
}
}
/// Sends the transaction, returning the handle for its awaiting.
pub async fn send(self) -> Result<SyncTransactionHandle, ClientError> {
// Currently fees aren't supported by ChangePubKey tx, but they will be in the near future.
// let fee = match self.fee {
// Some(fee) => fee,
// None => {
// let fee = self
// .wallet
// .provider
// .get_tx_fee(TxFeeTypes::Transfer, self.wallet.address(), fee_token.id)
// .await?;
// fee.total_fee
// }
// };
// let _fee_token = self
// .fee_token
// .ok_or_else(|| ClientError::MissingRequiredField("token".into()))?;
let nonce = match self.nonce {
Some(nonce) => nonce,
None => {
let account_info = self
.wallet
.provider
.account_info(self.wallet.address())
.await?;
account_info.committed.nonce
}
};
let change_pubkey = self
.wallet
.signer
.sign_change_pubkey_tx(nonce, self.onchain_auth)
.map_err(ClientError::SigningError)?;
let tx = FranklinTx::ChangePubKey(Box::new(change_pubkey));
let tx_hash = self.wallet.provider.send_tx(tx, None).await?;
let handle = SyncTransactionHandle::new(tx_hash, self.wallet.provider.clone());
Ok(handle)
}
/// Sets the transaction fee token. Returns an error if token is not supported by zkSync.
pub fn fee_token(mut self, token: impl Into<TokenLike>) -> Result<Self, ClientError> {
let token_like = token.into();
let token = self
.wallet
.tokens
.resolve(token_like)
.ok_or(ClientError::UnknownToken)?;
self.fee_token = Some(token);
Ok(self)
}
/// Set the fee amount. If the amount provided is not packable,
/// rounds it to the closest packable fee amount.
///
/// For more details, see [utils](../utils/index.html) functions.
pub fn fee(mut self, fee: impl Into<BigUint>) -> Self {
let fee = closest_packable_fee_amount(&fee.into());
self.fee = Some(fee);
self
}
/// Set the fee amount. If the provided fee is not packable,
/// returns an error.
///
/// For more details, see [utils](../utils/index.html) functions.
pub fn fee_exact(mut self, fee: impl Into<BigUint>) -> Result<Self, ClientError> {
let fee = fee.into();
if !is_fee_amount_packable(&fee) {
return Err(ClientError::NotPackableValue);
}
self.fee = Some(fee);
Ok(self)
}
/// Sets the transaction nonce.
pub fn nonce(mut self, nonce: Nonce) -> Self {
self.nonce = Some(nonce);
self
}
}
|
//! Display images in your terminal, kind of
//!
//! 
//!
//! # Library doc
//!
//! This library is used by `termimage` itself for all its function and is therefore contains all necessary functions.
//!
//! ## Data flow
//!
//! ```plaintext
//! Options::parse()
//! |> guess_format()
//! |> load_image()
//! |> resize_image()
//! |> write_[no_]ansi()
//! ```
//!
//! # Executable manpage
//!
//! Exit values and possible errors:
//!
//! ```text
//! 1 - failed to guess the file's format
//! 2 - failed to open the image file
//! ```
//!
//! ## SYNOPSIS
//!
//! `termimage` [OPTIONS] <IMAGE>
//!
//! ## DESCRIPTION
//!
//! Show images in your terminal.
//!
//! The images are automatically downscaled to the terminal's size and their
//! colours are approximated to match the terminal's display colours.
//!
//! With ANSI output this means a 3-bit colour resolution, with WinAPI - 4-bit.
//!
//! With WinAPI output the output colours are acquired from the console itself,
//! with ANSI output a sane default is assumed.
//!
//! ## OPTIONS
//!
//! <IMAGE>
//!
//! ```text
//! Image to display, must end in a recognisable image format extension.
//! ```
//!
//! -s --size <size>
//!
//! ```text
//! Output image resolution.
//!
//! By default this is autodetected to match the output terminal's resolution,
//! but is required when outputting to a file.
//!
//! Format: NxM
//! ```
//!
//! -f --force
//!
//! ```text
//! By default the image's aspect ratio will be preserved when downscaling,
//! use this option to override that behaviour.
//! ```
//!
//! -a --ansi
//!
//! ```text
//! Force ANSI output.
//!
//! This really applies only on Windows, as there's no non-ANSI alternatives
//! on other platforms.
//! ```
//!
//! ## EXAMPLES
//!
//! `checksums` [`-s` *NxM*] [`-f`] *assets/image.png*
//!
//! ```text
//! Display assets/image.png in the terminal, optionally not preserving
//! the aspect ratio.
//! ```
#[macro_use]
extern crate lazy_static;
extern crate term_size;
#[cfg(target_os = "windows")]
extern crate kernel32;
#[cfg(target_os = "windows")]
extern crate winapi;
extern crate image;
extern crate regex;
#[macro_use]
extern crate clap;
mod options;
mod outcome;
pub mod ops;
pub mod util;
pub use options::Options;
pub use outcome::Outcome;
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use std::fs;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use storages_common_cache::DiskCacheError;
use storages_common_cache::DiskCacheKey;
use storages_common_cache::DiskCacheResult;
use storages_common_cache::LruDiskCache as DiskCache;
use tempfile::TempDir;
struct TestFixture {
/// Temp directory.
pub tempdir: TempDir,
}
// helper trait to simplify the test case
trait InsertSingleSlice {
fn insert_single_slice(&mut self, key: &str, bytes: &[u8]) -> DiskCacheResult<()>;
}
impl InsertSingleSlice for DiskCache {
fn insert_single_slice(&mut self, key: &str, bytes: &[u8]) -> DiskCacheResult<()> {
self.insert_bytes(key, &[bytes])
}
}
fn create_file<T: AsRef<Path>, F: FnOnce(File) -> io::Result<()>>(
dir: &Path,
path: T,
fill_contents: F,
) -> io::Result<PathBuf> {
let b = dir.join(path);
fs::create_dir_all(b.parent().unwrap())?;
let f = fs::File::create(&b)?;
fill_contents(f)?;
b.canonicalize()
}
fn read_all<R: Read>(r: &mut R) -> io::Result<Vec<u8>> {
let mut v = vec![];
r.read_to_end(&mut v)?;
Ok(v)
}
impl TestFixture {
pub fn new() -> TestFixture {
TestFixture {
tempdir: tempfile::Builder::new()
.prefix("lru-disk-cache-test")
.tempdir()
.unwrap(),
}
}
pub fn tmp(&self) -> &Path {
self.tempdir.path()
}
pub fn create_file<T: AsRef<Path>>(&self, path: T, size: usize) -> PathBuf {
create_file(self.tempdir.path(), path, |mut f| {
f.write_all(&vec![0; size])
})
.unwrap()
}
}
#[test]
fn test_empty_dir() {
let f = TestFixture::new();
DiskCache::new(f.tmp(), 1024).unwrap();
}
#[test]
fn test_missing_root() {
let f = TestFixture::new();
DiskCache::new(f.tmp().join("not-here"), 1024).unwrap();
}
#[test]
fn test_some_existing_files() {
let f = TestFixture::new();
let items = 10;
let sizes = (0..).take(items);
let total_bytes: u64 = sizes.clone().sum();
for i in sizes {
let file_name = format!("file-{i}");
let test_key = DiskCacheKey::from(file_name.as_str());
let test_path = PathBuf::from(&test_key);
f.create_file(test_path, i as usize);
}
let c = DiskCache::new(f.tmp(), total_bytes).unwrap();
assert_eq!(c.size(), total_bytes);
assert_eq!(c.len(), items);
}
#[test]
fn test_existing_file_too_large() {
let f = TestFixture::new();
let items_count = 10;
let items_count_shall_be_kept = 10 - 2;
let item_size = 10;
let capacity = items_count_shall_be_kept * item_size;
let sizes = (0..).take(items_count);
for i in sizes {
let file_name = format!("file-{i}");
let test_key = DiskCacheKey::from(file_name.as_str());
let test_path = PathBuf::from(&test_key);
f.create_file(test_path, item_size);
}
let c = DiskCache::new(f.tmp(), capacity as u64).unwrap();
assert_eq!(c.size(), capacity as u64);
assert_eq!(c.len(), items_count_shall_be_kept);
for i in (0..).take(items_count_shall_be_kept) {
let file_name = format!("file-{i}");
c.contains_key(file_name.as_str());
}
}
#[test]
fn test_insert_bytes() {
let f = TestFixture::new();
let mut c = DiskCache::new(f.tmp(), 25).unwrap();
c.insert_single_slice("a/b/c", &[0; 10]).unwrap();
assert!(c.contains_key("a/b/c"));
c.insert_single_slice("a/b/d", &[0; 10]).unwrap();
assert_eq!(c.size(), 20);
// Adding this third file should put the cache above the limit.
c.insert_single_slice("x/y/z", &[0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("a/b/c"));
let evicted_file_path = PathBuf::from(&DiskCacheKey::from("a/b/c"));
assert!(!f.tmp().join(evicted_file_path).exists());
}
#[test]
fn test_insert_bytes_exact() {
// Test that files adding up to exactly the size limit works.
let f = TestFixture::new();
let mut c = DiskCache::new(f.tmp(), 20).unwrap();
c.insert_single_slice("file1", &[1; 10]).unwrap();
c.insert_single_slice("file2", &[2; 10]).unwrap();
assert_eq!(c.size(), 20);
c.insert_single_slice("file3", &[3; 10]).unwrap();
assert_eq!(c.size(), 20);
assert!(!c.contains_key("file1"));
}
#[test]
fn test_add_get_lru() {
let f = TestFixture::new();
{
let mut c = DiskCache::new(f.tmp(), 25).unwrap();
c.insert_single_slice("file1", &[1; 10]).unwrap();
c.insert_single_slice("file2", &[2; 10]).unwrap();
// Get the file to bump its LRU status.
assert_eq!(
read_all(&mut File::open(c.get_cache_path("file1").unwrap()).unwrap()).unwrap(),
vec![1u8; 10]
);
// Adding this third file should put the cache above the limit.
c.insert_single_slice("file3", &[3; 10]).unwrap();
assert_eq!(c.size(), 20);
// The least-recently-used file should have been removed.
assert!(!c.contains_key("file2"));
}
}
#[test]
fn test_insert_bytes_too_large() {
let f = TestFixture::new();
let mut c = DiskCache::new(f.tmp(), 1).unwrap();
match c.insert_single_slice("a/b/c", &[0; 2]) {
Err(DiskCacheError::FileTooLarge) => {}
x => panic!("Unexpected result: {x:?}"),
}
}
|
use customer::Customer;
use fakedb;
/// Method to check eligibility of each card.
/// Returns a Vec<> of cards the customer is eligible for.
pub fn checker(customer: Customer) -> Vec<fakedb::Card> {
// create a vector to store eligible cards in
let mut eligible_cards = Vec::new();
//put a clone of each card in the vector to start with
for card in fakedb::all_cards() {
eligible_cards.push(card.clone());
// test eligibility based on the employment filter
match card.filters.employment {
Some(ref s) => {
// if the customer does not fit the employment requirement
if s.to_lowercase() != customer.employment.to_lowercase() {
// remove the card from the eligible list
eligible_cards.retain(|c| c != &card);
}},
None => () // do nothing if no filter exists
}
// test eligibility based on the minimum income filter
match card.filters.income_min {
Some(ref i) => {
// if the customer does not fit the income requirement
if i >= &customer.income {
// remove the card from the eligible list
eligible_cards.retain(|c| c != &card);
}},
None => () // do nothing if no filter exists
}
}
//return the list of eligible cards
eligible_cards
}
|
use clap::{App, Arg, AppSettings, SubCommand, Shell};
pub fn cli() -> App<'static, 'static> {
App::new("tdo")
.version(crate_version!())
.author("Felix Wittwer <dev@felixwittwer.de>, Felix Döring <development@felixdoering.com>")
.about("A todo list tool for the terminal")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::ArgsNegateSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
.arg(Arg::with_name("task")
.help("Task you want to add")
.takes_value(true))
.arg(Arg::with_name("list")
.help("List you want to add the task to")
.takes_value(true))
.subcommand(SubCommand::with_name("all").about("Lists all tasks."))
.subcommand(SubCommand::with_name("add")
.about("Add a task to a certain list or the default list.")
.arg(Arg::with_name("task")
.help("Task you want to add")
.takes_value(true)
.required(true))
.arg(Arg::with_name("list")
.help("List you want to add the task to")
.takes_value(true)))
.subcommand(SubCommand::with_name("edit")
.about("Edit a task description.")
.arg(Arg::with_name("id")
.help("ID of the task you want to edit")
.takes_value(true)
.required(true)))
.subcommand(SubCommand::with_name("done")
.about("Mark a task as 'done'.")
.arg(Arg::with_name("id")
.help("ID of the task you want to mark ad done")
.takes_value(true)
.required(true)))
.subcommand(SubCommand::with_name("move")
.about("Move a todo to another list.")
.arg(Arg::with_name("id")
.help("ID of the task you want to move")
.takes_value(true)
.required(true))
.arg(Arg::with_name("listname")
.help("Name of the new list the todo should be moved to")
.takes_value(true)
.required(true)))
.subcommand(SubCommand::with_name("github")
.about("Generate a new todo and a github issue")
.setting(AppSettings::ArgsNegateSubcommands)
.setting(AppSettings::SubcommandsNegateReqs)
.arg(Arg::with_name("repository")
.help("<username>/<repo> you want to create the issue")
.takes_value(true)
.required(true))
.arg(Arg::with_name("title")
.help("The issue title")
.takes_value(true)
.required(true))
.arg(Arg::with_name("body")
.help("Content of the issue")
.takes_value(true))
.subcommand(SubCommand::with_name("set")
.about("Set the GitHub Access Token")
.arg(Arg::with_name("token")
.help("GitHub Access Token")
.takes_value(true)))
.subcommand(SubCommand::with_name("update")
.about("Update all created Issues")))
.subcommand(SubCommand::with_name("newlist")
.about("Create a new todo list.")
.arg(Arg::with_name("listname")
.help("Name of the new list")
.takes_value(true)
.required(true)))
.subcommand(SubCommand::with_name("lists")
.about("Display done/undone statistics of all lists."))
.subcommand(SubCommand::with_name("clean")
.about("Removes all tasks that have been marked as done.")
.arg(Arg::with_name("listname")
.help("Clears only the given list")
.takes_value(true)))
.subcommand(SubCommand::with_name("remove")
.about("Remove a todo list and its contents.")
.arg(Arg::with_name("listname")
.help("Name of the list to be deleted")
.takes_value(true)
.required(true)))
.subcommand(SubCommand::with_name("export")
.about("Export your todos as markdown.")
.arg(Arg::with_name("destination")
.help("Location to export the markdown")
.takes_value(true)
.required(true))
.arg(Arg::with_name("undone").help("Export only undone tasks (default exports all)")))
.subcommand(SubCommand::with_name("reset")
.about("DANGER ZONE. Deletes all your todos and todo lists."))
.subcommand(SubCommand::with_name("completions")
.about("Generate completion scripts for your shell.")
.after_help(COMPLETION_HELP)
.setting(AppSettings::ArgRequiredElseHelp)
.arg(Arg::with_name("shell").possible_values(&Shell::variants())))
}
//
static COMPLETION_HELP: &'static str =
r"NOTICE:
One can generate a completion script for `tdo` that is
compatible with a given shell. The script is output on `stdout`
allowing one to re-direct the output to the file of their
choosing. Where you place the file will depend on which shell, and
which operating system you are using. Your particular
configuration may also determine where these scripts need to be
placed.
Here are some common set ups for the three supported shells under
Unix and similar operating systems (such as GNU/Linux).
BASH:
Completion files are commonly stored in `/etc/bash_completion.d/`
Run the command:
`tdo completions bash > /etc/bash_completion.d/tdo.bash-completion`
This installs the completion script. You may have to log out and
log back in to your shell session for the changes to take affect.
BASH (macOS/Homebrew):
Homebrew stores bash completion files within the Homebrew directory.
With the `bash-completion` brew formula installed, run the command:
`tdo completions bash > $(brew --prefix)/etc/bash_completion.d/tdo.bash-completion`
FISH:
Fish completion files are commonly stored in
`$HOME/.config/fish/completions`
Run the command:
`tdo completions fish > ~/.config/fish/completions/tdo.fish`
This installs the completion script. You may have to log out and
log back in to your shell session for the changes to take affect.
ZSH:
ZSH completions are commonly stored in any directory listed in
your `$fpath` variable. To use these completions, you must either
add the generated script to one of those directories, or add your
own to this list.
Adding a custom directory is often the safest best if you're
unsure of which directory to use. First create the directory, for
this example we'll create a hidden directory inside our `$HOME`
directory
`mkdir ~/.zfunc`
Then add the following lines to your `.zshrc` just before
`compinit`
`fpath+=~/.zfunc`
Now you can install the completions script using the following
command
`tdo completions zsh > ~/.zfunc/_tdo`
You must then either log out and log back in, or simply run
`exec zsh`
For the new completions to take affect.
CUSTOM LOCATIONS:
Alternatively, you could save these files to the place of your
choosing, such as a custom directory inside your $HOME. Doing so
will require you to add the proper directives, such as `source`ing
inside your login script. Consult your shells documentation for
how to add such directives.
POWERSHELL:
The powershell completion scripts require PowerShell v5.0+ (which
comes Windows 10, but can be downloaded separately for windows 7
or 8.1).
First, check if a profile has already been set
`PS C:\> Test-Path $profile`
If the above command returns `False` run the following
`PS C:\> New-Item -path $profile -type file -force`
Now open the file provided by `$profile` (if you used the
`New-Item` command it will be
`%USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1`
Next, we either save the completions file into our profile, or
into a separate file and source it inside our profile. To save the
completions into our profile simply use
`PS C:\> tdo completions powershell >> %USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1`";
|
use crate::{
app::config::{self},
coords::{ScreenCoords, XYCoords},
gui::{
plot_context::{PlotContext, PlotContextExt},
utility::plot_curve_from_points,
Drawable, DrawingArgs,
},
};
use gtk::cairo::{FontFace, FontSlant, FontWeight};
use metfor::{CelsiusDiff, Quantity};
mod fire_plume_height;
pub use fire_plume_height::FirePlumeContext;
mod fire_plume_energy;
pub use fire_plume_energy::FirePlumeEnergyContext;
fn convert_dt_to_x(dt: CelsiusDiff) -> f64 {
let min_dt = config::MIN_DELTA_T;
let max_dt = config::MAX_DELTA_T;
(dt - min_dt) / (max_dt - min_dt)
}
pub fn convert_x_to_dt(x: f64) -> CelsiusDiff {
let min_dt = config::MIN_DELTA_T.unpack();
let max_dt = config::MAX_DELTA_T.unpack();
CelsiusDiff(x * (max_dt - min_dt) + min_dt)
}
fn convert_xy_to_screen<T>(context: &T, coords: XYCoords) -> ScreenCoords
where
T: PlotContext,
{
let translate = context.get_translate();
// Apply translation first
let x = coords.x - translate.x;
let y = coords.y - translate.y;
// Apply scaling
// Use factor of two scaling because these are wider than tall
let x = context.get_zoom_factor() * x * 2.0;
let y = context.get_zoom_factor() * y;
ScreenCoords { x, y }
}
fn convert_screen_to_xy<T>(context: &T, coords: ScreenCoords) -> XYCoords
where
T: PlotContext,
{
// Screen coords go 0 -> 1 down the y axis and 0 -> aspect_ratio right along the x axis.
let translate = context.get_translate();
let x = coords.x / context.get_zoom_factor() / 2.0 + translate.x;
let y = coords.y / context.get_zoom_factor() + translate.y;
XYCoords { x, y }
}
fn prepare_to_make_text<T>(context: &T, args: DrawingArgs<'_, '_>)
where
T: Drawable,
{
let (cr, config) = (args.cr, args.ac.config.borrow());
let font_face =
&FontFace::toy_create(&config.font_name, FontSlant::Normal, FontWeight::Bold).unwrap();
cr.set_font_face(font_face);
context.set_font_size(config.label_font_size * 2.0, cr);
}
fn draw_iso_dts<T>(context: &T, config: &config::Config, cr: >k::cairo::Context)
where
T: PlotContextExt,
{
for pnts in config::FIRE_PLUME_DT_PNTS.iter() {
let pnts = pnts
.iter()
.map(|xy_coords| context.convert_xy_to_screen(*xy_coords));
plot_curve_from_points(cr, config.background_line_width, config.isobar_rgba, pnts);
}
}
|
use crate::content_disposition::ContentDisposition;
use crate::helpers;
use crate::state::{MultipartState, StreamingStage};
use bytes::{Bytes, BytesMut};
use encoding_rs::{Encoding, UTF_8};
use futures::stream::{Stream, TryStreamExt};
use http::header::HeaderMap;
#[cfg(feature = "json")]
use serde::de::DeserializeOwned;
#[cfg(feature = "json")]
use serde_json;
use std::borrow::Cow;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
/// A single field in a multipart stream.
///
/// Its content can be accessed via the [`Stream`](./struct.Field.html#impl-Stream) API or the methods defined in this type.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(field) = multipart.next_field().await.unwrap() {
/// let content = field.text().await.unwrap();
/// assert_eq!(content, "abcd");
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
///
/// ## Warning About Leaks
///
/// To avoid the next field being initialized before this one is done being read or dropped, only one instance per [`Multipart`](./struct.Multipart.html)
/// instance is allowed at a time. A [`Drop`](https://doc.rust-lang.org/nightly/std/ops/trait.Drop.html) implementation is used to
/// notify [`Multipart`](./struct.Multipart.html) that this field is done being read.
///
/// If this value is leaked (via [`std::mem::forget()`](https://doc.rust-lang.org/nightly/std/mem/fn.forget.html) or some other mechanism),
/// then the parent [`Multipart`](./struct.Multipart.html) will never be able to yield the next field in the stream.
/// The task waiting on the [`Multipart`](./struct.Multipart.html) will also never be notified, which, depending on the executor implementation,
/// may cause a deadlock.
pub struct Field {
state: Arc<Mutex<MultipartState>>,
headers: HeaderMap,
done: bool,
meta: FieldMeta,
}
struct FieldMeta {
content_disposition: ContentDisposition,
content_type: Option<mime::Mime>,
idx: usize,
}
impl Field {
pub(crate) fn new(
state: Arc<Mutex<MultipartState>>,
headers: HeaderMap,
idx: usize,
content_disposition: ContentDisposition,
) -> Self {
let content_type = helpers::parse_content_type(&headers);
Field {
state,
headers,
done: false,
meta: FieldMeta {
content_disposition,
content_type,
idx,
},
}
}
/// The field name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.
pub fn name(&self) -> Option<&str> {
self.meta
.content_disposition
.field_name
.as_ref()
.map(|name| name.as_str())
}
/// The file name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.
pub fn file_name(&self) -> Option<&str> {
self.meta
.content_disposition
.file_name
.as_ref()
.map(|file_name| file_name.as_str())
}
/// Get the content type of the field.
pub fn content_type(&self) -> Option<&mime::Mime> {
self.meta.content_type.as_ref()
}
/// Get a map of headers as [`HeaderMap`](https://docs.rs/http/0.2.1/http/header/struct.HeaderMap.html).
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
/// Get the full data of the field as [`Bytes`](https://docs.rs/bytes/0.5.4/bytes/struct.Bytes.html).
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(field) = multipart.next_field().await.unwrap() {
/// let bytes = field.bytes().await.unwrap();
/// assert_eq!(bytes.len(), 4);
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub async fn bytes(self) -> crate::Result<Bytes> {
let mut buf = BytesMut::new();
let mut this = self;
while let Some(bytes) = this.chunk().await? {
buf.extend_from_slice(&bytes);
}
Ok(buf.freeze())
}
/// Stream a chunk of the field data.
///
/// When the field data has been exhausted, this will return None.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// while let Some(chunk) = field.chunk().await.unwrap() {
/// println!("Chunk: {:?}", chunk);
/// }
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub async fn chunk(&mut self) -> crate::Result<Option<Bytes>> {
self.try_next().await
}
/// Try to deserialize the field data as JSON.
///
/// # Optional
///
/// This requires the optional `json` feature to be enabled.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
/// use serde::Deserialize;
///
/// // This `derive` requires the `serde` dependency.
/// #[derive(Deserialize)]
/// struct User {
/// name: String
/// }
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\n{ \"name\": \"Alice\" }\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(field) = multipart.next_field().await.unwrap() {
/// let user = field.json::<User>().await.unwrap();
/// println!("User Name: {}", user.name);
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
///
/// # Errors
///
/// This method fails if the field data is not in JSON format
/// or it cannot be properly deserialized to target type `T`. For more
/// details please see [`serde_json::from_slice`](https://docs.serde.rs/serde_json/fn.from_slice.html);
#[cfg(feature = "json")]
pub async fn json<T: DeserializeOwned>(self) -> crate::Result<T> {
self.bytes()
.await
.and_then(|bytes| serde_json::from_slice(&bytes).map_err(|err| crate::Error::DecodeJson(err.into())))
}
/// Get the full field data as text.
///
/// This method decodes the field data with `BOM sniffing` and with malformed sequences replaced with the `REPLACEMENT CHARACTER`.
/// Encoding is determined from the `charset` parameter of `Content-Type` header, and defaults to `utf-8` if not presented.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// let content = field.text().await.unwrap();
/// assert_eq!(content, "abcd");
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub async fn text(self) -> crate::Result<String> {
self.text_with_charset("utf-8").await
}
/// Get the full field data as text given a specific encoding.
///
/// This method decodes the field data with `BOM sniffing` and with malformed sequences replaced with the `REPLACEMENT CHARACTER`.
/// You can provide a default encoding for decoding the raw message, while the `charset` parameter of `Content-Type` header is still prioritized.
/// For more information about the possible encoding name, please go to [encoding_rs](https://docs.rs/encoding_rs/0.8.22/encoding_rs/) docs.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// let content = field.text_with_charset("utf-8").await.unwrap();
/// assert_eq!(content, "abcd");
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub async fn text_with_charset(self, default_encoding: &str) -> crate::Result<String> {
let encoding_name = self
.content_type()
.and_then(|mime| mime.get_param(mime::CHARSET))
.map(|charset| charset.as_str())
.unwrap_or(default_encoding);
let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8);
let bytes = self.bytes().await?;
let (text, _, _) = encoding.decode(&bytes);
match text {
Cow::Owned(s) => Ok(s),
Cow::Borrowed(s) => Ok(String::from(s)),
}
}
/// Get the index of this field in order they appeared in the stream.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(field) = multipart.next_field().await.unwrap() {
/// let idx = field.index();
/// println!("Field index: {}", idx);
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub fn index(&self) -> usize {
self.meta.idx
}
}
impl Stream for Field {
type Item = Result<Bytes, crate::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
if self.done {
return Poll::Ready(None);
}
let mut mutex_guard = match self.state.lock() {
Ok(lock) => lock,
Err(err) => {
return Poll::Ready(Some(Err(crate::Error::LockFailure(err.to_string().into()))));
}
};
let state: &mut MultipartState = mutex_guard.deref_mut();
let stream_buffer = &mut state.buffer;
if let Err(err) = stream_buffer.poll_stream(cx) {
return Poll::Ready(Some(Err(crate::Error::StreamReadFailed(err.into()))));
}
match stream_buffer.read_field_data(state.boundary.as_str(), state.curr_field_name.as_deref()) {
Ok(Some((done, bytes))) => {
state.curr_field_size_counter += bytes.len() as u64;
if state.curr_field_size_counter > state.curr_field_size_limit {
return Poll::Ready(Some(Err(crate::Error::FieldSizeExceeded {
limit: state.curr_field_size_limit,
field_name: state.curr_field_name.clone(),
})));
}
drop(mutex_guard);
if done {
self.done = true;
Poll::Ready(Some(Ok(bytes)))
} else {
Poll::Ready(Some(Ok(bytes)))
}
}
Ok(None) => Poll::Pending,
Err(err) => Poll::Ready(Some(Err(err))),
}
}
}
impl Drop for Field {
fn drop(&mut self) {
let mut mutex_guard = match self.state.lock() {
Ok(lock) => lock,
Err(err) => {
log::error!("{}", crate::Error::LockFailure(err.to_string().into()));
return;
}
};
let state: &mut MultipartState = mutex_guard.deref_mut();
if self.done {
state.stage = StreamingStage::ReadingBoundary;
} else {
state.stage = StreamingStage::CleaningPrevFieldData;
}
state.is_prev_field_consumed = true;
if let Some(waker) = state.next_field_waker.take() {
waker.clone().wake();
}
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use common_base::runtime::Runtime;
use common_catalog::plan::DataSourcePlan;
use common_catalog::plan::Projection;
use common_catalog::plan::PushDownInfo;
use common_catalog::table_context::TableContext;
use common_exception::ErrorCode;
use common_exception::Result;
use common_pipeline_core::Pipeline;
use storages_common_index::Index;
use storages_common_index::RangeIndex;
use crate::fuse_lazy_part::FuseLazyPartInfo;
use crate::io::BlockReader;
use crate::operations::fuse_source::build_fuse_source_pipeline;
use crate::FuseTable;
impl FuseTable {
pub fn create_block_reader(
&self,
projection: Projection,
query_internal_columns: bool,
ctx: Arc<dyn TableContext>,
) -> Result<Arc<BlockReader>> {
let table_schema = self.table_info.schema();
BlockReader::create(
self.operator.clone(),
table_schema,
projection,
ctx,
query_internal_columns,
)
}
// Build the block reader.
fn build_block_reader(
&self,
plan: &DataSourcePlan,
ctx: Arc<dyn TableContext>,
) -> Result<Arc<BlockReader>> {
self.create_block_reader(
PushDownInfo::projection_of_push_downs(&self.table_info.schema(), &plan.push_downs),
plan.query_internal_columns,
ctx,
)
}
fn adjust_io_request(&self, ctx: &Arc<dyn TableContext>) -> Result<usize> {
let max_threads = ctx.get_settings().get_max_threads()? as usize;
let max_io_requests = ctx.get_settings().get_max_storage_io_requests()? as usize;
if !self.operator.info().can_blocking() {
Ok(std::cmp::max(max_threads, max_io_requests))
} else {
// For blocking fs, we don't want this to be too large
Ok(std::cmp::min(max_threads, max_io_requests).clamp(1, 48))
}
}
#[inline]
pub fn do_read_data(
&self,
ctx: Arc<dyn TableContext>,
plan: &DataSourcePlan,
pipeline: &mut Pipeline,
) -> Result<()> {
let mut lazy_init_segments = Vec::with_capacity(plan.parts.len());
for part in &plan.parts.partitions {
if let Some(lazy_part_info) = part.as_any().downcast_ref::<FuseLazyPartInfo>() {
lazy_init_segments.push(lazy_part_info.segment_location.clone());
}
}
if !lazy_init_segments.is_empty() {
let table = self.clone();
let table_info = self.table_info.clone();
let push_downs = plan.push_downs.clone();
let query_ctx = ctx.clone();
let dal = self.operator.clone();
let plan = plan.clone();
// TODO: need refactor
pipeline.set_on_init(move || {
let table = table.clone();
let table_info = table_info.clone();
let ctx = query_ctx.clone();
let dal = dal.clone();
let push_downs = push_downs.clone();
let lazy_init_segments = lazy_init_segments.clone();
let partitions = Runtime::with_worker_threads(2, None)?.block_on(async move {
// if query from distribute query node, need to init segment id at first
let segment_id_map = if plan.query_internal_columns {
let snapshot = table.read_table_snapshot().await?;
if let Some(snapshot) = snapshot {
let segment_count = snapshot.segments.len();
let mut segment_id_map = HashMap::new();
for (i, segmennt_loc) in snapshot.segments.iter().enumerate() {
segment_id_map
.insert(segmennt_loc.0.to_string(), segment_count - i - 1);
}
Some(segment_id_map)
} else {
None
}
} else {
None
};
let (_statistics, partitions) = table
.prune_snapshot_blocks(
ctx,
dal,
push_downs,
table_info,
lazy_init_segments,
0,
segment_id_map,
)
.await?;
Result::<_, ErrorCode>::Ok(partitions)
})?;
query_ctx.set_partitions(partitions)?;
Ok(())
});
}
let block_reader = self.build_block_reader(plan, ctx.clone())?;
let max_io_requests = self.adjust_io_request(&ctx)?;
let topk = plan.push_downs.as_ref().and_then(|x| {
x.top_k(
plan.schema().as_ref(),
self.cluster_key_str(),
RangeIndex::supported_type,
)
});
build_fuse_source_pipeline(
ctx,
pipeline,
self.storage_format,
block_reader,
plan,
topk,
max_io_requests,
)
}
}
|
#![allow(incomplete_features)]
#![feature(const_generics)]
pub mod executor;
pub mod join;
pub mod storage;
pub use crossbeam_channel;
pub use fxhash;
pub use hibitset;
pub use parking_lot;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Entity(u32);
impl Entity {
pub fn new(id: u32) -> Self {
Self(id)
}
pub fn index(&self) -> u32 {
self.0
}
}
|
//! Common functions, definitions and extensions for code generation, used by this crate.
pub(crate) mod default;
pub(crate) mod deprecation;
mod description;
pub(crate) mod diagnostic;
pub(crate) mod field;
pub(crate) mod gen;
pub(crate) mod parse;
pub(crate) mod rename;
pub(crate) mod scalar;
mod span_container;
pub(crate) use self::{description::Description, span_container::SpanContainer};
/// Checks whether the specified [`syn::Path`] equals to one-segment string
/// `value`.
pub(crate) fn path_eq_single(path: &syn::Path, value: &str) -> bool {
path.segments.len() == 1 && path.segments[0].ident == value
}
/// Filters the provided [`syn::Attribute`] to contain only ones with the
/// specified `name`.
pub(crate) fn filter_attrs<'a>(
name: &'a str,
attrs: &'a [syn::Attribute],
) -> impl Iterator<Item = &'a syn::Attribute> + 'a {
attrs
.iter()
.filter(move |attr| path_eq_single(&attr.path, name))
}
|
// Interior vector utility functions.
import option::none;
import option::some;
import uint::next_power_of_two;
import ptr::addr_of;
type operator2[T, U, V] = fn(&T, &U) -> V ;
native "rust-intrinsic" mod rusti {
fn ivec_len[T](v: &T[]) -> uint;
}
native "rust" mod rustrt {
fn ivec_reserve_shared[T](v: &mutable T[mutable? ], n: uint);
fn ivec_on_heap[T](v: &T[]) -> uint;
fn ivec_to_ptr[T](v: &T[]) -> *T;
fn ivec_copy_from_buf_shared[T](v: &mutable T[mutable? ], ptr: *T,
count: uint);
}
fn from_vec[@T](v: &vec[T]) -> T[] {
let iv: T[] = ~[];
for e in v {
iv += ~[e];
}
ret iv;
}
fn to_vec[@T](iv: &T[]) -> vec[T] {
let v: vec[T] = [];
for e in iv {
v += [e];
}
ret v;
}
/// Reserves space for `n` elements in the given vector.
fn reserve[@T](v: &mutable T[mutable? ], n: uint) {
rustrt::ivec_reserve_shared(v, n);
}
fn on_heap[T](v: &T[]) -> bool { ret rustrt::ivec_on_heap(v) != 0u; }
fn to_ptr[T](v: &T[]) -> *T { ret rustrt::ivec_to_ptr(v); }
fn len[T](v: &T[mutable? ]) -> uint { ret rusti::ivec_len(v); }
type init_op[T] = fn(uint) -> T ;
fn init_fn[@T](op: &init_op[T], n_elts: uint) -> T[] {
let v = ~[];
reserve(v, n_elts);
let i: uint = 0u;
while i < n_elts { v += ~[op(i)]; i += 1u; }
ret v;
}
// TODO: Remove me once we have slots.
fn init_fn_mut[@T](op: &init_op[T], n_elts: uint) -> T[mutable ] {
let v = ~[mutable ];
reserve(v, n_elts);
let i: uint = 0u;
while i < n_elts { v += ~[mutable op(i)]; i += 1u; }
ret v;
}
fn init_elt[@T](t: &T, n_elts: uint) -> T[] {
let v = ~[];
reserve(v, n_elts);
let i: uint = 0u;
while i < n_elts { v += ~[t]; i += 1u; }
ret v;
}
// TODO: Remove me once we have slots.
fn init_elt_mut[@T](t: &T, n_elts: uint) -> T[mutable ] {
let v = ~[mutable ];
reserve(v, n_elts);
let i: uint = 0u;
while i < n_elts { v += ~[mutable t]; i += 1u; }
ret v;
}
fn to_mut[@T](v: &T[]) -> T[mutable ] {
let vres = ~[mutable ];
for t: T in v { vres += ~[mutable t]; }
ret vres;
}
fn from_mut[@T](v: &T[mutable ]) -> T[] {
let vres = ~[];
for t: T in v { vres += ~[t]; }
ret vres;
}
// Predicates
pred is_empty[T](v: &T[mutable? ]) -> bool {
// FIXME: This would be easier if we could just call len
for t: T in v { ret false; }
ret true;
}
pred is_not_empty[T](v: &T[mutable? ]) -> bool { ret !is_empty(v); }
// Accessors
/// Returns the first element of a vector
fn head[@T](v: &T[mutable?]) : is_not_empty(v) -> T { ret v.(0); }
/// Returns all but the first element of a vector
fn tail[@T](v: &T[mutable? ]) : is_not_empty(v) -> T[mutable?] {
ret slice(v, 1u, len(v));
}
/// Returns the last element of `v`.
fn last[@T](v: &T[mutable? ]) -> option::t[T] {
if len(v) == 0u { ret none; }
ret some(v.(len(v) - 1u));
}
/// Returns a copy of the elements from [`start`..`end`) from `v`.
fn slice[@T](v: &T[mutable? ], start: uint, end: uint) -> T[] {
assert (start <= end);
assert (end <= len(v));
let result = ~[];
reserve(result, end - start);
let i = start;
while i < end { result += ~[v.(i)]; i += 1u; }
ret result;
}
// TODO: Remove me once we have slots.
fn slice_mut[@T](v: &T[mutable? ], start: uint, end: uint) -> T[mutable ] {
assert (start <= end);
assert (end <= len(v));
let result = ~[mutable ];
reserve(result, end - start);
let i = start;
while i < end { result += ~[mutable v.(i)]; i += 1u; }
ret result;
}
// Mutators
// TODO: Write this, unsafely, in a way that's not O(n).
fn pop[@T](v: &mutable T[mutable? ]) -> T {
let ln = len(v);
assert (ln > 0u);
ln -= 1u;
let e = v.(ln);
v = slice(v, 0u, ln);
ret e;
}
// TODO: More.
// Appending
/// Expands the given vector in-place by appending `n` copies of `initval`.
fn grow[@T](v: &mutable T[], n: uint, initval: &T) {
reserve(v, next_power_of_two(len(v) + n));
let i: uint = 0u;
while i < n { v += ~[initval]; i += 1u; }
}
// TODO: Remove me once we have slots.
fn grow_mut[@T](v: &mutable T[mutable ], n: uint, initval: &T) {
reserve(v, next_power_of_two(len(v) + n));
let i: uint = 0u;
while i < n { v += ~[mutable initval]; i += 1u; }
}
/// Calls `f` `n` times and appends the results of these calls to the given
/// vector.
fn grow_fn[@T](v: &mutable T[], n: uint, init_fn: fn(uint) -> T ) {
reserve(v, next_power_of_two(len(v) + n));
let i: uint = 0u;
while i < n { v += ~[init_fn(i)]; i += 1u; }
}
/// Sets the element at position `index` to `val`. If `index` is past the end
/// of the vector, expands the vector by replicating `initval` to fill the
/// intervening space.
fn grow_set[@T](v: &mutable T[mutable ], index: uint, initval: &T, val: &T) {
if index >= len(v) { grow_mut(v, index - len(v) + 1u, initval); }
v.(index) = val;
}
// Functional utilities
fn map[@T, @U](f: fn(&T) -> U , v: &T[mutable? ]) -> U[] {
let result = ~[];
reserve(result, len(v));
for elem: T in v {
let elem2 = elem; // satisfies alias checker
result += ~[f(elem2)];
}
ret result;
}
fn filter_map[@T, @U](f: fn(&T) -> option::t[U] , v: &T[mutable? ]) -> U[] {
let result = ~[];
for elem: T in v {
let elem2 = elem; // satisfies alias checker
alt f(elem2) {
none. {/* no-op */ }
some(result_elem) { result += ~[result_elem]; }
}
}
ret result;
}
fn foldl[@T, @U](p: fn(&U, &T) -> U , z: &U, v: &T[mutable? ]) -> U {
let sz = len(v);
if sz == 0u { ret z; }
let first = v.(0);
let rest = slice(v, 1u, sz);
ret p(foldl[T, U](p, z, rest), first);
}
fn any[T](f: fn(&T) -> bool , v: &T[]) -> bool {
for elem: T in v { if f(elem) { ret true; } }
ret false;
}
fn all[T](f: fn(&T) -> bool , v: &T[]) -> bool {
for elem: T in v { if !f(elem) { ret false; } }
ret true;
}
fn member[T](x: &T, v: &T[]) -> bool {
for elt: T in v { if x == elt { ret true; } }
ret false;
}
fn count[T](x: &T, v: &T[mutable? ]) -> uint {
let cnt = 0u;
for elt: T in v { if x == elt { cnt += 1u; } }
ret cnt;
}
fn find[@T](f: fn(&T) -> bool , v: &T[]) -> option::t[T] {
for elt: T in v { if f(elt) { ret some[T](elt); } }
ret none[T];
}
fn unzip[@T, @U](v: &{_0: T, _1: U}[]) -> {_0: T[], _1: U[]} {
let sz = len(v);
if sz == 0u {
ret {_0: ~[], _1: ~[]};
} else {
let rest = slice(v, 1u, sz);
let tl = unzip(rest);
let a = ~[v.(0)._0];
let b = ~[v.(0)._1];
ret {_0: a + tl._0, _1: b + tl._1};
}
}
// FIXME make the lengths being equal a constraint
fn zip[@T, @U](v: &T[], u: &U[]) -> {_0: T, _1: U}[] {
let sz = len(v);
assert (sz == len(u));
if sz == 0u {
ret ~[];
} else {
let rest = zip(slice(v, 1u, sz), slice(u, 1u, sz));
ret ~[{_0: v.(0), _1: u.(0)}] + rest;
}
}
mod unsafe {
type ivec_repr =
{mutable fill: uint,
mutable alloc: uint,
heap_part: *mutable ivec_heap_part};
type ivec_heap_part = {mutable fill: uint};
fn copy_from_buf[T](v: &mutable T[], ptr: *T, count: uint) {
ret rustrt::ivec_copy_from_buf_shared(v, ptr, count);
}
fn from_buf[T](ptr: *T, bytes: uint) -> T[] {
let v = ~[];
copy_from_buf(v, ptr, bytes);
ret v;
}
fn set_len[T](v: &mutable T[], new_len: uint) {
let new_fill = new_len * sys::size_of[T]();
let stack_part: *mutable ivec_repr =
::unsafe::reinterpret_cast(addr_of(v));
if (*stack_part).fill == 0u {
(*(*stack_part).heap_part).fill = new_fill; // On heap.
} else {
(*stack_part).fill = new_fill; // On stack.
}
}
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
|
//! This module houses the structures that are specific to the management of a CrystalOrb game
//! client.
//!
//! The [`Client`] structure is what you create, store, and update, analogous to the
//! [`Server`](crate::server::Server) structure. However, there isn't much functionality you can
//! directly access from a [`Client`] object. This is because most functionality depends on what
//! [`stage`] the [`Client`] is at, with different functionality provided at different stages. To
//! access other important and useful functionality to view and control your client, you can call
//! [`Client::stage`] and [`Client::stage_mut`] which will return some [`stage`] structure
//! containing the extra functionality.
//!
//! For the majority of the time, you would probably want to use [`stage::Ready`] in order
//! to perform the following useful operations:
//!
//! - [Issuing commands](stage::Ready::issue_command) that come from the player.
// ! ```
// ! use crystalorb::{Config, client::{Client, stage::StageMut}};
// ! use crystalorb_demo::{DemoWorld, DemoCommand, PlayerSide, PlayerCommand};
// ! use crystalorb_mock_network::MockNetwork;
// !
// ! // Using a mock network as an example...
// ! let (_, (mut network, _)) =
// ! MockNetwork::new_mock_network::<DemoWorld>();
// !
// ! let mut client = Client::<DemoWorld>::new(Config::default());
// !
// ! // ...later on in your update loop, in response to a player input...
// !
// ! if let StageMut::Ready(mut ready_client) = client.stage_mut() {
// ! let command = DemoCommand::new(PlayerSide::Left, PlayerCommand::Jump, true);
// ! ready_client.issue_command(command, &mut network);
// ! }
// ! ```
//! - [Getting the current display state](stage::Ready::display_state) to render on the screen.
// ! ```
// ! use crystalorb::{
// ! Config,
// ! client::{Client, stage::Stage},
// ! world::DisplayState,
// ! };
// ! use crystalorb_demo::{DemoWorld, DemoDisplayState};
// !
// ! fn render(display_state: &DemoDisplayState) {
// ! // [Your game rendering code]
// ! println!("{:?}", display_state);
// ! }
// !
// ! let client = Client::<DemoWorld>::new(Config::default());
// !
// ! // ...later on in your update loop...
// !
// ! if let Stage::Ready(ready_client) = client.stage() {
// ! render(ready_client.display_state().display_state());
// ! }
// ! ```
use super::{
// clocksync::ClockSyncer,
command::CommandBuffer,
fixed_timestepper::{FixedTimestepper, Stepper, TerminationCondition, TimeKeeper},
// network_resource::{Connection, NetworkResource},
old_new::{OldNew, OldNewResult},
timestamp::{Timestamp, Timestamped},
world::{DisplayState, /*InitializationType,*/ Simulation, Tweened, World},
Config,
};
use std::{
collections::VecDeque,
fmt::{Display, Formatter},
sync::{Arc, RwLock},
};
// pub mod stage;
// use stage::{Stage, StageMut, StageOwned};
/// This is the top-level structure of CrystalOrb for your game client, analogous to the
/// [`Server`](crate::server::Server) for game servers. You create, store, and update this client
/// instance to run your game on the client side.
pub struct Client<WorldType: World> {
config: Arc<RwLock<Config>>,
// stage: StageOwned<WorldType>,
pub client: ActiveClient<WorldType>, // TODO: integrate this in Client?
}
impl<WorldType: World> Client<WorldType> {
/// Constructs a new [`Client`].
///
/// # Examples
///
/// Using the default configuration parameters:
///
// ```
// use crystalorb::{Config, client::Client};
// use crystalorb_demo::DemoWorld;
//
// let client = Client::<DemoWorld>::new(Config::default());
// ```
///
/// Overriding some configuration parameter:
///
// ```
// use crystalorb::{Config, client::Client};
// use crystalorb_demo::DemoWorld;
//
// let client = Client::<DemoWorld>::new(Config {
// lag_compensation_latency: 0.5,
// ..Config::default()
// });
// ```
pub fn new(seconds_since_startup: f64, config: Arc<RwLock<Config>>) -> Self {
Self {
config: config.clone(),
// stage: StageOwned::SyncingClock(ClockSyncer::new(config)),
client: ActiveClient::new(seconds_since_startup, config /*, clocksyncer*/),
}
}
/// Perform the next update for the current rendering frame. You would typically call this in
/// your game engine's update loop of some kind.
///
// # Examples
//
// Here is how one might call [`Client::update`] outside of any game engine:
//
// ```
// use orb::{Config, client::Client};
// use crystalorb_demo::DemoWorld;
// use crystalorb_mock_network::MockNetwork;
// use std::time::Instant;
//
// // Using a mock network as an example...
// let (_, (mut network, _)) =
// MockNetwork::new_mock_network::<DemoWorld>();
//
// let mut client = Client::<DemoWorld>::new(Config::default());
// let startup_time = Instant::now();
// let mut previous_time = Instant::now();
//
// loop {
// let current_time = Instant::now();
// let delta_seconds = current_time.duration_since(previous_time).as_secs_f64();
// let seconds_since_startup = current_time.duration_since(startup_time).as_secs_f64();
//
// client.update(delta_seconds, seconds_since_startup, &mut network);
//
// // ...Other update code omitted...
// # break;
// }
// ```
pub fn update(
&mut self,
delta_seconds: f64,
seconds_since_startup: f64,
// net: &mut NetworkResourceType,
) {
let positive_delta_seconds = delta_seconds.max(0.0);
#[allow(clippy::float_cmp)]
if delta_seconds != positive_delta_seconds {
log::warn!(
"Attempted to update client with a negative delta_seconds {}. Clamping it to zero.",
delta_seconds
);
}
self.client.update(
delta_seconds,
seconds_since_startup,
/*&self.config, net*/
);
}
// /// Get the current stage of the [`Client`], which provides access to extra functionality
// /// depending on what stage it is currently in. See [`Client::stage_mut`], which provides
// /// functionality to mutate the client in some way.
// ///
// /// # Example
// ///
// /// To check on the client's progress at connecting with the server, you can check the number
// /// of clocksync samples during the client's [`SyncingClock`](Stage::SyncingClock)
// /// stage:
// ///
// /// ```
// /// use crystalorb::{Config, client::{Client, stage::Stage}};
// /// use crystalorb_demo::DemoWorld;
// ///
// /// let client = Client::<DemoWorld>::new(Config::default());
// ///
// /// // ...Later on...
// ///
// /// if let Stage::SyncingClock(syncing_clock_client) = client.stage() {
// /// println!(
// /// "Connection progress: {}%",
// /// syncing_clock_client.sample_count() as f64
// /// / syncing_clock_client.samples_needed() as f64 * 100.0
// /// );
// /// }
// /// ```
// pub fn stage(&self) -> Stage<WorldType> {
// Stage::from(&self.stage)
// }
// /// Get the current stage f the [`Client`], which provides access to extra functionality
// /// depending on what stage it is currently in. For shareable immutable version, see
// /// [`Client::stage`].
// ///
// /// # Example
// ///
// /// To issue a command, you'll need to access the client in its [`Ready`](Stage::Ready)
// /// stage:
// ///
// /// ```
// /// use crystalorb::{Config, client::{Client, stage::StageMut}};
// /// use crystalorb_demo::{DemoWorld, DemoCommand, PlayerSide, PlayerCommand};
// /// use crystalorb_mock_network::MockNetwork;
// ///
// /// // Using a mock network as an example...
// /// let (_, (mut network, _)) =
// /// MockNetwork::new_mock_network::<DemoWorld>();
// ///
// /// let mut client = Client::<DemoWorld>::new(Config::default());
// ///
// /// // ...Later on...
// ///
// /// if let StageMut::Ready(mut ready_client) = client.stage_mut() {
// /// let command = DemoCommand::new(PlayerSide::Left, PlayerCommand::Jump, true);
// /// ready_client.issue_command(command, &mut network);
// /// }
// /// ```
// pub fn stage_mut(&mut self) -> StageMut<WorldType> {
// StageMut::from(&mut self.stage)
// }
// ---------------- former Stage methods --------------------------------
/// Get the current display state that can be used to render the client's screen.
pub fn display_state(&self) -> Option<&Tweened<WorldType::DisplayStateType>> {
self.client.timekeeping_simulations.display_state.as_ref()
}
}
/// The internal CrystalOrb structure used to actively run the simulations, which is not
/// constructed until the [`ClockSyncer`] is ready.
pub struct ActiveClient<WorldType: World> {
// clocksyncer: ClockSyncer,
timekeeping_simulations: TimeKeeper<
ClientWorldSimulations<WorldType>, /*, { TerminationCondition::FirstOvershoot }*/
>,
incoming_commands: VecDeque<Timestamped<WorldType::CommandType>>,
incoming_snapshots: VecDeque<Timestamped<WorldType::SnapshotType>>,
outgoing_commands: VecDeque<Timestamped<WorldType::CommandType>>,
}
impl<WorldType: World> ActiveClient<WorldType> {
fn new(
seconds_since_startup: f64,
config: Arc<RwLock<Config>>, /*, clocksyncer: ClockSyncer*/
) -> Self {
// let server_time = clocksyncer
// .server_seconds_since_startup(seconds_since_startup)
// .expect("Active client can only be constructed with a synchronized clock");
let initial_timestamp = Timestamp::from_seconds(
/*server_time*/ seconds_since_startup,
config.read().unwrap().timestep_seconds,
);
log::info!(
"Initial timestamp: {:?}", /*, client_id: {}"*/
initial_timestamp,
// clocksyncer
// .client_id()
// .expect("Active client can only be constructed once connected"),
);
Self {
// clocksyncer,
timekeeping_simulations: TimeKeeper::new(
ClientWorldSimulations::new(config.clone(), initial_timestamp),
config,
TerminationCondition::FirstOvershoot,
),
incoming_commands: VecDeque::new(),
incoming_snapshots: VecDeque::new(),
outgoing_commands: VecDeque::new(),
}
}
fn last_completed_timestamp(&self) -> Timestamp {
self.timekeeping_simulations.last_completed_timestamp()
}
fn simulating_timestamp(&self) -> Timestamp {
self.last_completed_timestamp() + 1
}
/// Perform the next update for the current rendering frame.
pub fn update(
&mut self,
delta_seconds: f64,
seconds_since_startup: f64,
// net: &mut NetworkResourceType,
) {
// self.clocksyncer
// .update(delta_seconds, seconds_since_startup, net);
for command in self.incoming_commands.drain(..) {
self.timekeeping_simulations.receive_command(&command);
}
for snapshot in self.incoming_snapshots.drain(..) {
self.timekeeping_simulations.receive_snapshot(snapshot);
}
// log::trace!(
// "client server clock offset {}",
// self.clocksyncer
// .server_seconds_offset()
// .expect("Clock should be synced")
// );
let lag_compensation_latency = self
.timekeeping_simulations
.config
.read()
.unwrap()
.lag_compensation_latency;
self.timekeeping_simulations.update(
delta_seconds,
seconds_since_startup
// self.clocksyncer
// .server_seconds_since_startup(seconds_since_startup)
// .expect("Clock should be synced")
+ lag_compensation_latency,
);
}
/// Whether all the uninitialized state has been flushed out, and that the first display state
/// is available to be shown to the client's screen.
pub fn is_ready(&self) -> bool {
self.timekeeping_simulations.display_state.is_some()
}
/// CrystalOrb is written assuming that
/// `ClockSyncMessage` and `SnapshotType` are unreliable and unordered, while `CommandType` is
/// reliable but unordered.
pub fn take_outgoing_commands(&mut self) -> VecDeque<Timestamped<WorldType::CommandType>> {
self.outgoing_commands.split_off(0)
}
pub fn enqueue_incoming_command(&mut self, command: Timestamped<WorldType::CommandType>) {
self.incoming_commands.push_back(command);
log::trace!(
"Waiting incoming_commands: {}",
self.incoming_commands.len()
);
}
pub fn enqueue_incoming_snapshot(&mut self, snapshot: Timestamped<WorldType::SnapshotType>) {
self.incoming_snapshots.push_back(snapshot);
log::trace!(
"Waiting incoming_snapshots: {}",
self.incoming_snapshots.len()
);
}
}
/// The client needs to perform different behaviours at different times. For example, the client
/// cannot reconcile with the server before receing a snapshot from the server. The client cannot
/// blend the snapshot into the current world state until the snapshot state has been fastforwarded
/// to the correct timestamp (since server snapshots are always behind the client's state).
#[derive(Debug)]
pub enum ReconciliationStatus {
/// This is the status when the previous snapshot has been fully blended in, and the client is
/// now waiting for the next snapshot to be applied.
AwaitingSnapshot,
/// This is the status when a snapshot is taken from the snapshot queue and the client is now
/// in the process of bringing that snapshot state on par with the client's existing timestamp.
Fastforwarding(FastforwardingHealth),
/// This is the status when the snapshot timestamp now matches the client's timestamp, and the
/// client is now in the process of blending the snapshot into the client's display state.
/// The `f64` value describes the current interpolation parameter used for blending the old and
/// new display states together, ranging from `0.0` (meaning use the old state) to `1.0`
/// (meaning use the new state).
Blending(f64),
}
/// Fastforwarding the server's snapshot to the current timestamp can take multiple update cycles.
/// During this time, different external situations can cause the fastfowarding process to abort in
/// an unexpected way. This enum describes these possible situations.
#[derive(Debug)]
pub enum FastforwardingHealth {
/// Exactly as the name implies. Fastforwarding continues as normal.
Healthy,
/// If a new server snapshot arrives before the current server snapshot has finished
/// fastfowarding, and for some reason this server snapshot has a timestamp newer than the
/// current fastforwarded snapshot timestamp, then we mark the current fastforwarded snapshot
/// as obsolete as it is even further behind than the latest snapshot. This newer snapshot then
/// replaces the current new-world state, and the fast-forwarding continues.
///
/// Essentially, this is like taking a shortcut, and is important whenever the client performs
/// a timeskip. The new world timestamp could suddenly become very far behind, and we don't
/// want the client to become stuck trying to fastforward this very "old" server snapshot.
Obsolete,
/// When the client perform timeskips, weird things can happen to existing timestamps and the
/// current new world timestamp that we are trying to fastforward may end up *ahead* of the
/// current timestamp.
Overshot,
}
impl Display for ReconciliationStatus {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ReconciliationStatus::AwaitingSnapshot => write!(f, "Awaiting Snapshot"),
ReconciliationStatus::Fastforwarding(health) => {
write!(f, "Fastforwarding {}", health)
}
ReconciliationStatus::Blending(t) => write!(f, "Blending @ {}%", (t * 100.0) as i32),
}
}
}
impl Display for FastforwardingHealth {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
FastforwardingHealth::Healthy => write!(f, ""),
FastforwardingHealth::Obsolete => write!(f, "Obsolete"),
FastforwardingHealth::Overshot => write!(f, "Overshot"),
}
}
}
#[derive(Debug)]
struct ClientWorldSimulations<WorldType: World> {
/// The next server snapshot that needs applying after the current latest snapshot has been
/// fully interpolated into.
queued_snapshot: Option<Timestamped<WorldType::SnapshotType>>,
/// The timestamp of the last queued snapshot from the server, so we can discard stale
/// snapshots from the server when the arrive out of order. This persists even after the queued
/// snapshot has been cleared after it has been applied to the world.
last_queued_snapshot_timestamp: Option<Timestamp>,
/// The timestamp of the last received snapshot from the server, regardless of whether it
/// was discarded or accepted (since we only keep the latest snapshot). This is primarily
/// for diagnostic purposes.
last_received_snapshot_timestamp: Option<Timestamp>,
/// The command buffer that is used to initialize the new world simulation's command
/// buffers whenever a queued snapshot is applied to it. Contains older commands that the
/// individual world simulation's internal command buffers would have already dropped, but
/// would otherwise need to replay onto the server snapshot to get it back to the current
/// timestamp.
base_command_buffer: CommandBuffer<WorldType::CommandType>,
/// The physics world simulation with and without the latest server snapshot applied.
/// `world_simulation.get().new` has the latest server snapshot applied.
/// `world_simulation.get().old` does not have the latest server snapshot applied.
/// Old and new gets swapped every time a new queued server snapshot is applied.
world_simulations:
OldNew<Simulation<WorldType /*, { InitializationType::NeedsInitialization }*/>>,
/// The interpolation paramater to blend the `old_world` and `new_world` together into a
/// single world state. The parameter is in the range `[0,1]` where 0 represents using only
/// the `old_world`, and where 1 represents using only the `new_world`.
blend_old_new_interpolation_t: f64,
/// The latest interpolated state between `old_world` and `new_world` just before and just
/// after the current requested render timestamp.
/// `states.get_old()` is the state just before the requested timestamp.
/// `states.get_new()` is the state just after the requested timestamp.
/// Old and new gets swapped every step.
/// They are None until the first world simulation state that is based on a server snapshot is
/// ready to be "published".
states: OldNew<Option<Timestamped<WorldType::DisplayStateType>>>,
/// The interpolation between `previous_state` and `current_state` for the requested render
/// timestamp. This remains None until the client is initialised with the server's snapshots.
display_state: Option<Tweened<WorldType::DisplayStateType>>,
config: Arc<RwLock<Config>>,
}
impl<WorldType: World> ClientWorldSimulations<WorldType> {
pub fn new(config: Arc<RwLock<Config>>, initial_timestamp: Timestamp) -> Self {
let mut client_world_simulations = Self {
queued_snapshot: None,
last_queued_snapshot_timestamp: None,
last_received_snapshot_timestamp: None,
base_command_buffer: CommandBuffer::new(),
world_simulations: OldNew::new(),
blend_old_new_interpolation_t: 1.0,
states: OldNew::new(),
display_state: None,
config,
};
let OldNewResult { old, new } = client_world_simulations.world_simulations.get_mut();
old.reset_last_completed_timestamp(initial_timestamp);
new.reset_last_completed_timestamp(initial_timestamp);
client_world_simulations
}
pub fn infer_current_reconciliation_status(&self) -> ReconciliationStatus {
let OldNewResult {
old: old_world_simulation,
new: new_world_simulation,
} = self.world_simulations.get();
if new_world_simulation.last_completed_timestamp()
== old_world_simulation.last_completed_timestamp()
{
assert_eq!(
new_world_simulation.last_completed_timestamp(),
old_world_simulation.last_completed_timestamp()
);
if self.blend_old_new_interpolation_t < 1.0 {
ReconciliationStatus::Blending(self.blend_old_new_interpolation_t)
} else {
assert!(self.blend_old_new_interpolation_t >= 1.0);
ReconciliationStatus::AwaitingSnapshot
}
} else {
assert!(
self.blend_old_new_interpolation_t <= 0.0,
"Interpolation t advances only if timestamps are equal, and once they are equal, they remain equal even in timeskips."
);
let is_snapshot_newer = self.queued_snapshot.as_ref().map_or(false, |snapshot| {
snapshot.timestamp() > new_world_simulation.last_completed_timestamp()
});
let fastforward_status = if new_world_simulation.last_completed_timestamp()
> old_world_simulation.last_completed_timestamp()
{
FastforwardingHealth::Overshot
} else if is_snapshot_newer {
FastforwardingHealth::Obsolete
} else {
assert!(
new_world_simulation.last_completed_timestamp()
< old_world_simulation.last_completed_timestamp()
);
FastforwardingHealth::Healthy
};
ReconciliationStatus::Fastforwarding(fastforward_status)
}
}
fn receive_command(&mut self, command: &Timestamped<WorldType::CommandType>) {
log::debug!("Received command {:?}", command);
let OldNewResult { old, new } = self.world_simulations.get_mut();
self.base_command_buffer.insert(command);
old.schedule_command(command);
new.schedule_command(command);
}
fn receive_snapshot(&mut self, snapshot: Timestamped<WorldType::SnapshotType>) {
log::trace!(
"Received snapshot: {:?} frames behind",
self.last_completed_timestamp() - snapshot.timestamp()
);
self.last_received_snapshot_timestamp = Some(snapshot.timestamp());
if snapshot.timestamp() > self.last_completed_timestamp() {
log::warn!("Received snapshot from the future! Ignoring snapshot.");
return;
}
match &self.last_queued_snapshot_timestamp {
None => self.queued_snapshot = Some(snapshot),
Some(last_timestamp) => {
// Ignore stale snapshots.
if snapshot.timestamp() > *last_timestamp {
self.queued_snapshot = Some(snapshot);
} else {
log::warn!("Received stale snapshot - ignoring.");
}
}
}
if let Some(queued_snapshot) = &self.queued_snapshot {
self.last_queued_snapshot_timestamp = Some(queued_snapshot.timestamp());
}
}
}
impl<WorldType: World> Stepper for ClientWorldSimulations<WorldType> {
fn step(&mut self) {
fn load_snapshot<WorldType: World>(
this: &mut ClientWorldSimulations<WorldType>,
snapshot: &Timestamped<WorldType::SnapshotType>,
) {
log::trace!("Loading new snapshot from server");
let OldNewResult {
old: old_world_simulation,
new: new_world_simulation,
} = this.world_simulations.get_mut();
// We can now safely discard commands from the buffer that are older than this
// server snapshot.
//
// Off-by-one check:
//
// snapshot has completed the frame at t=snapshot.timestamp(), and therefore
// has already applied commands that are scheduled for t=snapshot.timestamp().
this.base_command_buffer.drain_up_to(snapshot.timestamp());
new_world_simulation
.apply_completed_snapshot(snapshot, this.base_command_buffer.clone());
if new_world_simulation.last_completed_timestamp()
> old_world_simulation.last_completed_timestamp()
{
// The server should always be behind the client, even excluding the
// network latency. The client may momentarily fall behind due to, e.g.,
// browser tab sleeping, but once the browser tab wakes up, the client
// should automatically compensate, and if necessary, time skip to the
// correct timestamp to be ahead of the server. If even then the server
// continues to be ahead, then it might suggest that the client and the
// server's clocks are running at different rates, and some additional time
// syncing mechanism is needed.
log::warn!("Server's snapshot is newer than client!");
}
// We reset the old/new interpolation factor and begin slowly blending in from
// the old world to the new world once the new world has caught up (aka
// "fast-forwarded") to the old world's timestamp.
this.blend_old_new_interpolation_t = 0.0;
}
fn simulate_next_frame<WorldType: World>(this: &mut ClientWorldSimulations<WorldType>) {
log::trace!("Stepping old world by one frame");
let OldNewResult {
old: old_world_simulation,
new: new_world_simulation,
} = this.world_simulations.get_mut();
old_world_simulation.step();
log::trace!(
"Fastforwarding new world from timestamp {:?} to current timestamp {:?}",
new_world_simulation.last_completed_timestamp(),
old_world_simulation.last_completed_timestamp()
);
new_world_simulation.try_completing_simulations_up_to(
old_world_simulation.last_completed_timestamp(),
this.config.read().unwrap().fastforward_max_per_step,
);
}
fn publish_old_state<WorldType: World>(this: &mut ClientWorldSimulations<WorldType>) {
this.states.swap();
this.states
.set_new(this.world_simulations.get().old.display_state());
}
fn publish_blended_state<WorldType: World>(this: &mut ClientWorldSimulations<WorldType>) {
let OldNewResult {
old: old_world_simulation,
new: new_world_simulation,
} = this.world_simulations.get_mut();
assert_eq!(
old_world_simulation.last_completed_timestamp(),
new_world_simulation.last_completed_timestamp()
);
log::trace!("Blending the old and new world states");
let state_to_publish = match (
old_world_simulation.display_state(),
new_world_simulation.display_state(),
) {
(Some(old), Some(new)) => Some(
Timestamped::<WorldType::DisplayStateType>::from_interpolation(
&old,
&new,
this.blend_old_new_interpolation_t,
),
),
(None, Some(new)) => Some(new),
(Some(_), None) => {
unreachable!("New world is always initialized before old world does")
}
(None, None) => None,
};
this.states.swap();
this.states.set_new(state_to_publish);
}
log::trace!("Step...");
match self.infer_current_reconciliation_status() {
ReconciliationStatus::Blending(_) => {
self.blend_old_new_interpolation_t +=
self.config.read().unwrap().blend_progress_per_frame();
self.blend_old_new_interpolation_t =
self.blend_old_new_interpolation_t.clamp(0.0, 1.0);
simulate_next_frame(self);
publish_blended_state(self);
assert!(
matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Blending(_) | ReconciliationStatus::AwaitingSnapshot,
),
"Unexpected status change into: {:?}",
self.infer_current_reconciliation_status()
);
}
ReconciliationStatus::AwaitingSnapshot => {
if let Some(snapshot) = self.queued_snapshot.take() {
self.world_simulations.swap();
load_snapshot(self, &snapshot);
simulate_next_frame(self);
publish_old_state(self);
assert!(
matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Fastforwarding(
FastforwardingHealth::Healthy | FastforwardingHealth::Overshot
)
) || matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Blending(t) if t == 0.0
),
"Unexpected status change into: {:?}",
self.infer_current_reconciliation_status()
);
} else {
simulate_next_frame(self);
publish_blended_state(self);
assert!(
matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::AwaitingSnapshot
),
"Unexpected status change into: {:?}",
self.infer_current_reconciliation_status()
);
}
}
ReconciliationStatus::Fastforwarding(FastforwardingHealth::Obsolete) => {
let snapshot = self
.queued_snapshot
.take()
.expect("New world can only be obsolete if there exists a newer snapshot");
log::warn!("Abandoning previous snapshot for newer shapshot! Couldn't fastforward the previous snapshot in time.");
load_snapshot(self, &snapshot);
simulate_next_frame(self);
publish_old_state(self);
assert!(
matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Fastforwarding(FastforwardingHealth::Healthy)
),
"Unexpected status change into: {:?}",
self.infer_current_reconciliation_status()
);
}
ReconciliationStatus::Fastforwarding(FastforwardingHealth::Healthy) => {
simulate_next_frame(self);
publish_old_state(self);
assert!(
matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Fastforwarding(FastforwardingHealth::Healthy)
) || matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Blending(t) if t == 0.0
),
"Unexpected status change into: {:?}",
self.infer_current_reconciliation_status()
);
}
ReconciliationStatus::Fastforwarding(FastforwardingHealth::Overshot) => {
log::warn!("New world fastforwarded beyond old world - This should only happen when the client had timeskipped.");
let OldNewResult {
old: old_world_simulation,
new: new_world_simulation,
} = self.world_simulations.get_mut();
new_world_simulation.reset_last_completed_timestamp(
old_world_simulation.last_completed_timestamp(),
);
simulate_next_frame(self);
publish_blended_state(self);
assert!(
matches!(
self.infer_current_reconciliation_status(),
ReconciliationStatus::Blending(t) if t == 0.0
),
"Unexpected status change into: {:?}",
self.infer_current_reconciliation_status()
);
}
}
}
}
impl<WorldType: World> FixedTimestepper for ClientWorldSimulations<WorldType> {
fn last_completed_timestamp(&self) -> Timestamp {
self.world_simulations.get().old.last_completed_timestamp()
}
fn reset_last_completed_timestamp(&mut self, corrected_timestamp: Timestamp) {
let OldNewResult {
old: old_world_simulation,
new: new_world_simulation,
} = self.world_simulations.get_mut();
let old_timestamp = old_world_simulation.last_completed_timestamp();
if new_world_simulation.last_completed_timestamp()
== old_world_simulation.last_completed_timestamp()
{
new_world_simulation.reset_last_completed_timestamp(corrected_timestamp);
}
old_world_simulation.reset_last_completed_timestamp(corrected_timestamp);
// Note: If timeskip was so large that timestamp has wrapped around to the past,
// then we need to clear all the commands in the base command buffer so that any
// pending commands to get replayed unexpectedly in the future at the wrong time.
if corrected_timestamp < old_timestamp {
self.base_command_buffer.drain_all();
}
}
fn post_update(&mut self, timestep_overshoot_seconds: f64) {
// We display an interpolation between the undershot and overshot states.
log::trace!("Interpolating undershot/overshot states (aka tweening)");
let OldNewResult {
old: optional_undershot_state,
new: optional_overshot_state,
} = self.states.get();
let config = self.config.read().unwrap();
let tween_t = config
.tweening_method
.shape_interpolation_t(1.0 - timestep_overshoot_seconds / config.timestep_seconds);
log::trace!("tween_t {}", tween_t);
if let Some(undershot_state) = optional_undershot_state {
if let Some(overshot_state) = optional_overshot_state {
self.display_state = Some(Tweened::from_interpolation(
undershot_state,
overshot_state,
tween_t,
));
}
}
log::trace!("Update the base command buffer's timestamp and accept-window");
self.base_command_buffer
.update_timestamp(self.last_completed_timestamp());
log::trace!("Reset last completed timestamp if outside comparable range");
if let Some(last_timestamp) = self.last_queued_snapshot_timestamp.as_ref().copied() {
let comparable_range =
Timestamp::comparable_range_with_midpoint(self.last_completed_timestamp());
if !comparable_range.contains(&last_timestamp)
|| last_timestamp > self.last_completed_timestamp()
{
log::warn!("Last queued snapshot timestamp too old to compare. Resetting timestamp book-keeping");
// This is done to prevent new snapshots from being discarded due
// to a very old snapshot that was last applied. This can happen
// after a very long pause (e.g. browser tab sleeping).
// We don't jump to `comparable_range.start` since it will be invalid immediately
// in the next iteration.
self.last_queued_snapshot_timestamp = Some(
self.last_completed_timestamp()
- (self.config.read().unwrap().lag_compensation_frame_count() * 2),
);
}
}
}
}
|
enum Hint {
Glyph(char),
LineStart,
LineEnd,
PageStart
}
struct LayoutState {
// measure the width when breaking here
real: FlexMeasure,
//
imag: FlexMeasure,
hint: Hint,
score: f32
}
trait Item {
fn apply(&self, state: LayoutState) -> LayoutState;
}
struct Node {
state: LayoutState,
// score of this possible break
score: f32,
// index into input items
index: usize
}
enum Element {
Item(Item),
BranchEntry(usize),
BranchExit(usize)
}
struct LayoutSolver {
nodes: Vec<Node>,
}
struct LayoutInfo {
width: Length
}
impl LayoutSolver {
fn run() {
// initial
let mut state = LayoutState {
real: 0.
imag: 0.,
hint: PageStart
}
let mut start = 0;
loop {
// grab current node
let ref item = self.nodes[node.index];
}
}
// find paths starting with the given state
fn explore(mut node_index: usize) {
let mut node = self.nodes[node_index];
loop {
// appy the item to the state
state = item.apply(state);
// Increment the index into the state vector
node_index += 1;
// The item generates possible break points.
// It is important that this function always
// returns the same value for a given entry.
// Otherwise different runs might get inconsistent indices
// into the state vector, causing undefined results.
if let Some(score) = item.score() {
node = Node {
state: state,
index: node.index + 1,
score: node.score + score
};
match self.nodes.get(node_index) {
None => node_index.push(node);
Some(other) if other.score < node.score => self.nodes[node_index];
}
}
}
}
}
struct NonBreakingSpace {
measure: FlexMeasure
}
impl Item for NonBreakingSpace {
fn apply(&self, state: LayoutState) -> LayoutState {
state.imag += self.measure;
state
}
}
struct BreakingSpace {
measure: FlexMeasure
}
impl Item for NonBreakingSpace {
fn apply(&self, state: LayoutState) -> LayoutState {
state.imag += self.measure;
state
}
fn score(&self, info: LayoutInfo) {
Some( info.width)
}
}
struct Word<O> {
w: O::Word
}
impl Item for Word {
fn apply(&self, state: LayoutState) -> LayoutState {
LayoutState {
real: state.real + kerning(state.hint, self.w) + state.imag,
imag: 0.,
hint: self.w
}
}
}
struct Newline {}
impl Item for Newline {
fn apply(&self, _: LayoutState) -> LayoutState {
LayoutState {
real: 0.,
imag: 0.,
hint: Hint::LineStart
}
}
}
struct HFill {}
impl Item for HFill {
fn apply(&self, _: LayoutState) -> LayoutState {
LayoutState {
real: 0.,
imag: 0.,
hint: Hint::LineStart
}
}
}
struct Hyphen {}
impl Item for Hyphen {
fn apply(&self, state: LayoutState) -> LayoutState {
LayoutState {
real: state.real,
imag: state.imag + kerning(state.hint, Glyph('-'))
hint: Glyph('-')
}
}
}
|
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::Bytes;
use http::header::AsHeaderName;
use http::uri::Authority;
use http::HeaderMap;
use http_body::Body as HttpBody;
use hyper::Body;
use pin_project::pin_project;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};
use tonic::Code;
use tonic::{body::BoxBody, Status};
use tower::{Layer, Service};
use crate::sink::ErrorLogger;
use crate::{proto, sink::NopErrorLogger, NoReflection, Predicate, Sink};
/// Intercepts all gRPC frames, builds gRPC log entries and sends them to a [`Sink`].
#[derive(Debug, Default, Clone)]
pub struct BinaryLoggerLayer<K, P = NoReflection, L = NopErrorLogger>
where
K: Sink + Send + Sync,
L: ErrorLogger<K::Error>,
{
sink: Arc<K>,
predicate: P,
error_logger: L,
}
impl<K> BinaryLoggerLayer<K, NoReflection, NopErrorLogger>
where
K: Sink + Send + Sync,
{
/// Creates a new binary logger layer with the default predicate that
/// logs everything except gRPC reflection requests
pub fn new(sink: K) -> Self {
Self {
sink: Arc::new(sink),
predicate: Default::default(),
error_logger: NopErrorLogger,
}
}
}
impl<K, P, L> BinaryLoggerLayer<K, P, L>
where
K: Sink + Send + Sync,
P: Predicate,
L: ErrorLogger<K::Error>,
{
/// Builds a new binary logger layer with the provided predicate.
pub fn with_predicate<P2: Predicate>(self, predicate: P2) -> BinaryLoggerLayer<K, P2, L> {
BinaryLoggerLayer {
sink: self.sink,
predicate,
error_logger: self.error_logger,
}
}
/// Builds a new binary logger layer with the provided error logger.
pub fn with_error_logger<L2: ErrorLogger<K::Error>>(
self,
error_logger: L2,
) -> BinaryLoggerLayer<K, P, L2> {
BinaryLoggerLayer {
sink: self.sink,
predicate: self.predicate,
error_logger,
}
}
}
impl<S, K, P, L> Layer<S> for BinaryLoggerLayer<K, P, L>
where
P: Predicate + Send,
K: Sink + Send + Sync + 'static,
L: ErrorLogger<K::Error> + 'static,
{
type Service = BinaryLoggerMiddleware<S, K, P, L>;
fn layer(&self, service: S) -> Self::Service {
BinaryLoggerMiddleware::new(
service,
Arc::clone(&self.sink),
self.predicate.clone(),
self.error_logger.clone(),
)
}
}
#[derive(Debug, Clone)]
pub struct BinaryLoggerMiddleware<S, K, P, L>
where
K: Sink + Send + Sync,
L: ErrorLogger<K::Error>,
{
sink: Arc<K>,
inner: S,
predicate: P,
error_logger: L,
next_call_id: Arc<AtomicU64>,
}
impl<S, K, P, L> BinaryLoggerMiddleware<S, K, P, L>
where
K: Sink + Send + Sync,
P: Predicate + Send,
L: ErrorLogger<K::Error>,
{
fn new(inner: S, sink: Arc<K>, predicate: P, error_logger: L) -> Self {
Self {
sink,
inner,
predicate,
error_logger,
next_call_id: Arc::new(AtomicU64::new(1)),
}
}
fn next_call_id(&self) -> u64 {
self.next_call_id.fetch_add(1, Ordering::SeqCst)
}
}
impl<S, K, P, L> Service<hyper::Request<Body>> for BinaryLoggerMiddleware<S, K, P, L>
where
S: Service<hyper::Request<Body>, Response = hyper::Response<BoxBody>> + Clone + Send + 'static,
S::Future: Send + 'static,
K: Sink + Send + Sync + 'static,
P: Predicate + Send,
L: ErrorLogger<K::Error> + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = futures::future::BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: hyper::Request<Body>) -> Self::Future {
// This is necessary because tonic internally uses `tower::buffer::Buffer`.
// See https://github.com/tower-rs/tower/issues/547#issuecomment-767629149
// for details on why this is necessary
let clone = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, clone);
if !self.predicate.should_log(&request) {
Box::pin(async move { inner.call(request).await })
} else {
let call = CallLogger::new(
self.next_call_id(),
Arc::clone(&self.sink),
self.error_logger.clone(),
);
Box::pin(async move {
let uri = request.uri();
call.log(LogEntry::ClientHeaders {
method: uri.path(),
authority: uri.authority(),
headers: request.headers(),
});
// wrap our logger around the request stream.
let request = Self::logged_request(request, call.clone());
// Perform the actual request.
// When a handler returns an error, we get an `Ok(Response(...))` here.
// TODO(mkm): figure out what's the right way to log an error when we get `Err` here
let response = inner.call(request).await?;
// wrap our logger around the response stream.
Ok(Self::logged_response(response, call))
})
}
}
}
impl<S, K, P, L> BinaryLoggerMiddleware<S, K, P, L>
where
K: Sink + Send + Sync + 'static,
L: ErrorLogger<K::Error> + 'static,
{
fn logged_request(req: hyper::Request<Body>, call: CallLogger<K, L>) -> hyper::Request<Body> {
let (req_parts, mut req_body) = req.into_parts();
// We *must* return a Request<Body> because that's what `inner` requires.
// `Body` is not a trait though, so we cannot wrap it and passively log as
// tonic consumes bytes from the client connection. Instead we have to construct
// a `Body` with one of its public constructors. We can create a body that
// produces its data as obtained asynchronously from a channel.
// We spawn a task that reads from the request body and forwards bytes to the
// inner request. While we're streaming data we determine gRPC message boundaries
// and log messages.
let (mut sender, client_body) = hyper::Body::channel();
tokio::spawn(async move {
while let Some(buf) = req_body.data().await {
match buf {
Ok(buf) => {
// `data` returns an actual gRPC frames, even if it has been sent
// over multiple tcp segments and over multiple HTTP/2 DATA frames.
// TODO(mkm): figure out why the client produces a zero length chunk here.
// Ignoring it seems to be the right thing to do.
if !buf.is_empty() {
call.log(LogEntry::ClientMessage(&buf));
}
if sender.send_data(buf).await.is_err() {
// TODO(mkm): figure out how to log this kind of error, if any.
// The Go gRPC framework seems to either log a frame if successful
// or just not log it.
sender.abort();
return;
}
}
Err(_err) => {
// TODO(mkm): figure out how to log this kind of error, if any.
// The Go gRPC framework seems to either log a frame if successful
// or just not log it.
sender.abort();
return;
}
}
}
// gRPC doesn't use client trailers, but let's forward them nevertheless for completeness.
match req_body.trailers().await {
Ok(Some(trailers)) => {
if sender.send_trailers(trailers).await.is_err() {
// TODO(mkm): figure out how to log this kind of error, if any.
// The Go gRPC framework seems to either log a frame if successful
// or just not log it.
sender.abort();
}
}
Err(_err) => {
// TODO(mkm): figure out how to log this kind of error, if any.
// The Go gRPC framework seems to either log a frame if successful
// or just not log it.
sender.abort();
}
_ => {}
};
});
hyper::Request::from_parts(req_parts, client_body)
}
fn logged_response(
response: hyper::Response<BoxBody>,
call: CallLogger<K, L>,
) -> hyper::Response<BoxBody> {
let (parts, inner) = response.into_parts();
let body = BoxBody::new(BinaryLoggingBody {
inner,
headers: parts.headers.clone(),
call: call.clone(),
_phantom_error_logger: PhantomData,
});
call.log(LogEntry::ServerHeaders(&parts.headers));
if body.is_end_stream() {
// When an grpc call doesn't produce any results (either because the result type
// is empty or because it returns an error immediately), the BinaryLoggingBody
// won't be able to log anything. We have to log the event here.
call.log(LogEntry::ServerTrailers(&parts.headers));
}
hyper::Response::from_parts(parts, body)
}
}
#[pin_project]
struct BinaryLoggingBody<K, L>
where
K: Sink + Send + Sync,
L: ErrorLogger<K::Error>,
{
#[pin]
inner: BoxBody,
headers: HeaderMap,
call: CallLogger<K, L>,
_phantom_error_logger: PhantomData<L>,
}
impl<K, L> HttpBody for BinaryLoggingBody<K, L>
where
K: Sink + Send + Sync,
L: ErrorLogger<K::Error>,
{
type Data = bytes::Bytes;
type Error = Status;
fn poll_data(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
let call = self.call.clone();
let data = self.project().inner.poll_data(cx);
if let Poll::Ready(Some(Ok(ref body))) = data {
call.log(LogEntry::ServerMessage(body));
}
data
}
fn poll_trailers(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> {
let call = self.call.clone();
let trailers = self.project().inner.poll_trailers(cx);
if let Poll::Ready(Ok(Some(ref headers))) = trailers {
call.log(LogEntry::ServerTrailers(headers));
}
trailers
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
}
enum LogEntry<'a> {
ClientHeaders {
method: &'a str,
authority: Option<&'a Authority>,
headers: &'a HeaderMap,
},
ClientMessage(&'a Bytes),
ServerHeaders(&'a HeaderMap),
ServerMessage(&'a Bytes),
ServerTrailers(&'a HeaderMap),
}
#[derive(Clone)]
struct CallLogger<K, L>
where
K: Sink + Send + Sync,
L: ErrorLogger<K::Error>,
{
call_id: u64,
sequence: Arc<AtomicU64>,
sink: Arc<K>,
error_logger: L,
}
impl<K, L> CallLogger<K, L>
where
K: Sink + Send + Sync,
L: ErrorLogger<K::Error>,
{
fn new(call_id: u64, sink: Arc<K>, error_logger: L) -> Self {
Self {
call_id,
sequence: Arc::new(AtomicU64::new(1)),
sink,
error_logger,
}
}
fn log(&self, entry: LogEntry<'_>) {
let sequence_id_within_call = self.sequence.fetch_add(1, Ordering::SeqCst);
let common_entry = proto::GrpcLogEntry {
timestamp: Some(SystemTime::now().into()),
call_id: self.call_id,
sequence_id_within_call,
logger: proto::grpc_log_entry::Logger::Server as i32,
..Default::default()
};
let log_entry = match entry {
LogEntry::ClientHeaders {
method,
authority,
headers,
} => {
let timeout = headers.grpc_timeout().map(|t| t.try_into().unwrap());
proto::GrpcLogEntry {
r#type: proto::grpc_log_entry::EventType::ClientHeader as i32,
payload: Some(proto::grpc_log_entry::Payload::ClientHeader(
proto::ClientHeader {
method_name: method.to_string(),
metadata: Some(Self::metadata(headers)),
authority: authority
.map(|a| a.as_str())
.unwrap_or_default()
.to_string(),
timeout,
},
)),
..common_entry
}
}
LogEntry::ClientMessage(body) => proto::GrpcLogEntry {
r#type: proto::grpc_log_entry::EventType::ClientMessage as i32,
payload: Some(Self::message(body)),
..common_entry
},
LogEntry::ServerHeaders(headers) => proto::GrpcLogEntry {
r#type: proto::grpc_log_entry::EventType::ServerHeader as i32,
payload: Some(proto::grpc_log_entry::Payload::ServerHeader(
proto::ServerHeader {
metadata: Some(Self::metadata(headers)),
},
)),
..common_entry
},
LogEntry::ServerMessage(body) => proto::GrpcLogEntry {
r#type: proto::grpc_log_entry::EventType::ServerMessage as i32,
payload: Some(Self::message(body)),
..common_entry
},
LogEntry::ServerTrailers(headers) => proto::GrpcLogEntry {
r#type: proto::grpc_log_entry::EventType::ServerTrailer as i32,
payload: Some(proto::grpc_log_entry::Payload::Trailer(proto::Trailer {
status_code: headers.grpc_status() as u32,
status_message: headers.grpc_message().to_string(),
metadata: Some(Self::metadata(headers)),
status_details: headers.grpc_status_details(),
})),
..common_entry
},
};
self.sink.write(log_entry, self.error_logger.clone());
}
fn message(bytes: &Bytes) -> proto::grpc_log_entry::Payload {
let compressed = bytes[0] == 1;
if compressed {
unimplemented!("grpc compressed messages");
}
const COMPRESSED_FLAG_FIELD_LEN: usize = 1;
const MESSAGE_LENGTH_FIELD_LEN: usize = 4;
let data = bytes
.clone() // cheap
.into_iter()
.skip(COMPRESSED_FLAG_FIELD_LEN + MESSAGE_LENGTH_FIELD_LEN)
.collect::<Vec<_>>();
proto::grpc_log_entry::Payload::Message(proto::Message {
length: data.len() as u32,
data,
})
}
fn metadata(headers: &HeaderMap) -> proto::Metadata {
proto::Metadata {
entry: headers
.iter()
.filter(|&(key, _)| !is_reserved_header(key))
.map(|(key, value)| proto::MetadataEntry {
key: key.to_string(),
value: value.as_bytes().to_vec(),
})
.collect(),
}
}
}
/// As defined in [binarylog.proto](https://github.com/grpc/grpc-proto/blob/master/grpc/binlog/v1/binarylog.proto)
fn is_reserved_header<K>(key: K) -> bool
where
K: AsHeaderName,
{
let key = key.as_str();
match key {
"grpc-trace-bin" => false, // this is the only "grpc-" prefixed header that is not ignored.
"te" | "content-type" | "content-length" | "content-encoding" | "user-agent" => true,
_ if key.starts_with("grpc-") => true,
_ => false,
}
}
trait GrpcHeaderExt {
fn grpc_message(&self) -> &str;
fn grpc_status(&self) -> Code;
fn grpc_status_details(&self) -> Vec<u8>;
fn grpc_timeout(&self) -> Option<Duration>;
fn get_grpc_header<K>(&self, key: K) -> Option<&str>
where
K: AsHeaderName;
}
impl GrpcHeaderExt for HeaderMap {
fn grpc_message(&self) -> &str {
self.get_grpc_header("grpc-message").unwrap_or_default()
}
fn grpc_status(&self) -> Code {
self.get_grpc_header("grpc-status")
.map(|s| s.as_bytes())
.map(Code::from_bytes)
.unwrap_or(Code::Unknown)
}
fn grpc_status_details(&self) -> Vec<u8> {
self.get_grpc_header("grpc-status-details-bin")
.and_then(|v| BASE64_STANDARD.decode(v).ok())
.unwrap_or_default()
}
/// Extract a gRPC timeout from the `grpc-timeout` header.
/// Returns None if the header is not present or not valid.
fn grpc_timeout(&self) -> Option<Duration> {
self.get_grpc_header("grpc-timeout")
.and_then(parse_grpc_timeout)
}
fn get_grpc_header<K>(&self, key: K) -> Option<&str>
where
K: AsHeaderName,
{
self.get(key).and_then(|s| s.to_str().ok())
}
}
/// Parse a gRPC "Timeout" format (see [gRPC over HTTP2]).
/// Returns None if it cannot parse the format.
///
/// [gRPC over HTTP2]: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
fn parse_grpc_timeout(header_value: &str) -> Option<Duration> {
if header_value.is_empty() {
return None;
}
let (digits, unit) = header_value.split_at(header_value.len() - 1);
let timeout: u64 = digits.parse().ok()?;
match unit {
"H" => Some(Duration::from_secs(timeout * 60 * 60)),
"M" => Some(Duration::from_secs(timeout * 60)),
"S" => Some(Duration::from_secs(timeout)),
"m" => Some(Duration::from_millis(timeout)),
"u" => Some(Duration::from_micros(timeout)),
"n" => Some(Duration::from_nanos(timeout)),
_ => None,
}
}
|
//! Functions returning the stdio file descriptors.
//!
//! # Safety
//!
//! These access the file descriptors by absolute index value, and nothing
//! prevents them from being closed and reused. They should only be used in
//! `main` or other situations where one is in control of the process'
//! stdio streams.
#![allow(unsafe_code)]
use crate::backend;
use crate::fd::OwnedFd;
use backend::c;
use backend::fd::{BorrowedFd, FromRawFd, RawFd};
#[cfg(not(any(windows, target_os = "wasi")))]
use {crate::io, backend::fd::AsFd, core::mem::forget};
/// `STDIN_FILENO`—Standard input, borrowed.
///
/// In `std`-using configurations, this is a safe function, because the
/// standard library already assumes that the stdin file descriptor is always
/// valid. In `no_std` configurations, it is `unsafe`.
///
/// # Warning
///
/// This function allows reading directly from stdin without coordinating
/// with the buffering performed by [`std::io::Stdin`], so it could cause
/// corrupted input.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdin.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdin.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdin&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdin.4
/// [OpenBSD]: https://man.openbsd.org/stdin.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdin§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdin
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdin
#[cfg(feature = "std")]
#[doc(alias = "STDIN_FILENO")]
#[inline]
pub const fn stdin() -> BorrowedFd<'static> {
// SAFETY: When "std" is enabled, the standard library assumes that the
// stdio file descriptors are all valid.
unsafe { BorrowedFd::borrow_raw(c::STDIN_FILENO as RawFd) }
}
/// `STDIN_FILENO`—Standard input, borrowed.
///
/// In `std`-using configurations, this is a safe function, because the
/// standard library already assumes that the stdin file descriptor is always
/// valid. In `no_std` configurations, it is `unsafe`.
///
/// # Safety
///
/// In `no_std` configurations, the stdin file descriptor can be closed,
/// potentially on other threads, in which case the file descriptor index
/// value could be dynamically reused for other purposes, potentially on
/// different threads.
///
/// # Warning
///
/// This function allows reading directly from stdin without coordinating
/// with the buffering performed by [`std::io::Stdin`], so it could cause
/// corrupted input.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdin.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdin.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdin&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdin.4
/// [OpenBSD]: https://man.openbsd.org/stdin.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdin§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdin
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdin
#[cfg(not(feature = "std"))]
#[doc(alias = "STDIN_FILENO")]
#[inline]
pub const unsafe fn stdin() -> BorrowedFd<'static> {
BorrowedFd::borrow_raw(c::STDIN_FILENO as RawFd)
}
/// `STDIN_FILENO`—Standard input, owned.
///
/// This is similar to [`stdin`], however it returns an `OwnedFd` which closes
/// standard input when it is dropped.
///
/// # Safety
///
/// Safe `std`-using Rust code is permitted to assume that the stdin file
/// descriptor is always valid. This function returns an `OwnedFd` which will
/// close the stdin file descriptor when dropped.
///
/// # Warning
///
/// This has the same hazards as [`stdin`].
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdin.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdin.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdin&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdin.4
/// [OpenBSD]: https://man.openbsd.org/stdin.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdin§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdin
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdin
#[doc(alias = "STDIN_FILENO")]
#[inline]
pub unsafe fn take_stdin() -> OwnedFd {
backend::fd::OwnedFd::from_raw_fd(c::STDIN_FILENO as RawFd)
}
/// `STDOUT_FILENO`—Standard output, borrowed.
///
/// In `std`-using configurations, this is a safe function, because the
/// standard library already assumes that the stdout file descriptor is always
/// valid. In `no_std` configurations, it is `unsafe`.
///
/// # Warning
///
/// This function allows reading directly from stdout without coordinating
/// with the buffering performed by [`std::io::Stdout`], so it could cause
/// corrupted input.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdout.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdout.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdout&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdout.4
/// [OpenBSD]: https://man.openbsd.org/stdout.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdout§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdout
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdout
#[cfg(feature = "std")]
#[doc(alias = "STDOUT_FILENO")]
#[inline]
pub const fn stdout() -> BorrowedFd<'static> {
// SAFETY: When "std" is enabled, the standard library assumes that the
// stdio file descriptors are all valid.
unsafe { BorrowedFd::borrow_raw(c::STDOUT_FILENO as RawFd) }
}
/// `STDOUT_FILENO`—Standard output, borrowed.
///
/// In `std`-using configurations, this is a safe function, because the
/// standard library already assumes that the stdout file descriptor is always
/// valid. In `no_std` configurations, it is `unsafe`.
///
/// # Safety
///
/// In `no_std` configurations, the stdout file descriptor can be closed,
/// potentially on other threads, in which case the file descriptor index
/// value could be dynamically reused for other purposes, potentially on
/// different threads.
///
/// # Warning
///
/// This function allows reading directly from stdout without coordinating
/// with the buffering performed by [`std::io::Stdout`], so it could cause
/// corrupted input.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdout.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdout.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdout&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdout.4
/// [OpenBSD]: https://man.openbsd.org/stdout.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdout§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdout
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdout
#[cfg(not(feature = "std"))]
#[doc(alias = "STDOUT_FILENO")]
#[inline]
pub const unsafe fn stdout() -> BorrowedFd<'static> {
BorrowedFd::borrow_raw(c::STDOUT_FILENO as RawFd)
}
/// `STDOUT_FILENO`—Standard output, owned.
///
/// This is similar to [`stdout`], however it returns an `OwnedFd` which closes
/// standard output when it is dropped.
///
/// # Safety
///
/// Safe `std`-using Rust code is permitted to assume that the stdout file
/// descriptor is always valid. This function returns an `OwnedFd` which will
/// close the stdout file descriptor when dropped.
///
/// # Warning
///
/// This has the same hazards as [`stdout`].
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdout.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdout.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdout&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdout.4
/// [OpenBSD]: https://man.openbsd.org/stdout.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdout§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdout
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdout
#[doc(alias = "STDOUT_FILENO")]
#[inline]
pub unsafe fn take_stdout() -> OwnedFd {
backend::fd::OwnedFd::from_raw_fd(c::STDOUT_FILENO as RawFd)
}
/// `STDERR_FILENO`—Standard error, borrowed.
///
/// In `std`-using configurations, this is a safe function, because the
/// standard library already assumes that the stderr file descriptor is always
/// valid. In `no_std` configurations, it is `unsafe`.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stderr.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stderr.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stderr&sektion=4
/// [NetBSD]: https://man.netbsd.org/stderr.4
/// [OpenBSD]: https://man.openbsd.org/stderr.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stderr§ion=4
/// [illumos]: https://illumos.org/man/4FS/stderr
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stderr
#[cfg(feature = "std")]
#[doc(alias = "STDERR_FILENO")]
#[inline]
pub const fn stderr() -> BorrowedFd<'static> {
// SAFETY: When "std" is enabled, the standard library assumes that the
// stdio file descriptors are all valid.
unsafe { BorrowedFd::borrow_raw(c::STDERR_FILENO as RawFd) }
}
/// `STDERR_FILENO`—Standard error, borrowed.
///
/// In `std`-using configurations, this is a safe function, because the
/// standard library already assumes that the stderr file descriptor is always
/// valid. In `no_std` configurations, it is `unsafe`.
///
/// # Safety
///
/// In `no_std` configurations, the stderr file descriptor can be closed,
/// potentially on other threads, in which case the file descriptor index
/// value could be dynamically reused for other purposes, potentially on
/// different threads.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stderr.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stderr.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stderr&sektion=4
/// [NetBSD]: https://man.netbsd.org/stderr.4
/// [OpenBSD]: https://man.openbsd.org/stderr.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stderr§ion=4
/// [illumos]: https://illumos.org/man/4FS/stderr
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stderr
#[cfg(not(feature = "std"))]
#[doc(alias = "STDERR_FILENO")]
#[inline]
pub const unsafe fn stderr() -> BorrowedFd<'static> {
BorrowedFd::borrow_raw(c::STDERR_FILENO as RawFd)
}
/// `STDERR_FILENO`—Standard error, owned.
///
/// This is similar to [`stderr`], however it returns an `OwnedFd` which closes
/// standard output when it is dropped.
///
/// # Safety
///
/// Safe std-using Rust code is permitted to assume that the stderr file
/// descriptor is always valid. This function returns an `OwnedFd` which will
/// close the stderr file descriptor when dropped.
///
/// # Other hazards
///
/// This has the same hazards as [`stderr`].
///
/// And, when the `OwnedFd` is dropped, subsequent newly created file
/// descriptors may unknowingly reuse the stderr file descriptor number, which
/// may break common assumptions, so it should typically only be dropped at the
/// end of a program when no more file descriptors will be created.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stderr.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stderr.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stderr&sektion=4
/// [NetBSD]: https://man.netbsd.org/stderr.4
/// [OpenBSD]: https://man.openbsd.org/stderr.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stderr§ion=4
/// [illumos]: https://illumos.org/man/4FS/stderr
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stderr
#[doc(alias = "STDERR_FILENO")]
#[inline]
pub unsafe fn take_stderr() -> OwnedFd {
backend::fd::OwnedFd::from_raw_fd(c::STDERR_FILENO as RawFd)
}
/// `STDIN_FILENO`—Standard input, raw.
///
/// This is similar to [`stdin`], however it returns a `RawFd`.
///
/// # Other hazards
///
/// This has the same hazards as [`stdin`].
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdin.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdin.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdin&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdin.4
/// [OpenBSD]: https://man.openbsd.org/stdin.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdin§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdin
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdin
#[doc(alias = "STDIN_FILENO")]
#[inline]
pub const fn raw_stdin() -> RawFd {
c::STDIN_FILENO as RawFd
}
/// `STDOUT_FILENO`—Standard output, raw.
///
/// This is similar to [`stdout`], however it returns a `RawFd`.
///
/// # Other hazards
///
/// This has the same hazards as [`stdout`].
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stdout.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stdout.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stdout&sektion=4
/// [NetBSD]: https://man.netbsd.org/stdout.4
/// [OpenBSD]: https://man.openbsd.org/stdout.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stdout§ion=4
/// [illumos]: https://illumos.org/man/4FS/stdout
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stdout
#[doc(alias = "STDOUT_FILENO")]
#[inline]
pub const fn raw_stdout() -> RawFd {
c::STDOUT_FILENO as RawFd
}
/// `STDERR_FILENO`—Standard error, raw.
///
/// This is similar to [`stderr`], however it returns a `RawFd`.
///
/// # Other hazards
///
/// This has the same hazards as [`stderr`].
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/stderr.html
/// [Linux]: https://man7.org/linux/man-pages/man3/stderr.3.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=stderr&sektion=4
/// [NetBSD]: https://man.netbsd.org/stderr.4
/// [OpenBSD]: https://man.openbsd.org/stderr.4
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=stderr§ion=4
/// [illumos]: https://illumos.org/man/4FS/stderr
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#index-stderr
#[doc(alias = "STDERR_FILENO")]
#[inline]
pub const fn raw_stderr() -> RawFd {
c::STDERR_FILENO as RawFd
}
/// Utility function to safely `dup2` over stdin (fd 0).
#[cfg(not(any(windows, target_os = "wasi")))]
#[allow(clippy::mem_forget)]
#[inline]
pub fn dup2_stdin<Fd: AsFd>(fd: Fd) -> io::Result<()> {
// SAFETY: We pass the returned `OwnedFd` to `forget` so that it isn't
// dropped.
let mut target = unsafe { take_stdin() };
backend::io::syscalls::dup2(fd.as_fd(), &mut target)?;
forget(target);
Ok(())
}
/// Utility function to safely `dup2` over stdout (fd 1).
#[cfg(not(any(windows, target_os = "wasi")))]
#[allow(clippy::mem_forget)]
#[inline]
pub fn dup2_stdout<Fd: AsFd>(fd: Fd) -> io::Result<()> {
// SAFETY: We pass the returned `OwnedFd` to `forget` so that it isn't
// dropped.
let mut target = unsafe { take_stdout() };
backend::io::syscalls::dup2(fd.as_fd(), &mut target)?;
forget(target);
Ok(())
}
/// Utility function to safely `dup2` over stderr (fd 2).
#[cfg(not(any(windows, target_os = "wasi")))]
#[allow(clippy::mem_forget)]
#[inline]
pub fn dup2_stderr<Fd: AsFd>(fd: Fd) -> io::Result<()> {
// SAFETY: We pass the returned `OwnedFd` to `forget` so that it isn't
// dropped.
let mut target = unsafe { take_stderr() };
backend::io::syscalls::dup2(fd.as_fd(), &mut target)?;
forget(target);
Ok(())
}
|
#[cfg(test)]
mod test;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::registry;
#[native_implemented::function(erlang:registered/0)]
pub fn result(process: &Process) -> exception::Result<Term> {
registry::names(process)
}
|
pub type Typeidx = u32;
pub type Funcidx = u32;
pub type Tableidx = u32;
pub type Memidx = u32;
pub type Globalidx = u32;
pub type Localidx = u32;
pub type Labelidx = u32;
#[derive(Debug)]
pub enum ValType {
I32(i32),
I64(i64),
F32(f32),
F64(f64),
}
|
use nalgebra::Vector2;
use sdl2::event::Event;
use sdl2::gfx::primitives::DrawRenderer;
use sdl2::keyboard::Keycode;
use sdl2::mouse::MouseButton;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use std::env::args;
use std::error::Error;
use std::time::Duration;
use std::time::SystemTime;
use tokio::net::{TcpStream, UdpSocket};
use tokio::prelude::*;
use tokio::sync::mpsc::channel;
use tokio::sync::mpsc::error::TryRecvError;
use tokio::time::interval;
use game;
struct World {
updates: [game::WorldUpdate; 2],
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Connect with the server.
let addr = match args().nth(1) {
Some(addr) => addr,
None => {
eprintln!("Usage: {} HOST:PORT", args().nth(0).unwrap());
return Ok(())
},
};
println!("Connecting to {}...", addr);
let mut tcp_stream = TcpStream::connect(&addr).await?;
println!("Waiting for init message...");
const MAX_PACKET_SIZE_PLUS_ONE: usize = 4096;
let mut buf: [u8; MAX_PACKET_SIZE_PLUS_ONE] = [0; MAX_PACKET_SIZE_PLUS_ONE];
let num_bytes = tcp_stream.read(&mut buf).await?;
// Parse player id and random bytes from init message.
let tcp_init_message: game::TcpClientMessage = bincode::deserialize(&buf[..num_bytes])?;
let init = match tcp_init_message {
game::TcpClientMessage::Init(init) => init,
_ => panic!("Received unexpected message from server!"),
};
// Declare players arena.
let mut world = World {
updates: [
game::WorldUpdate { tick: 0, players: vec![], bullets: vec![] },
init.update,
],
};
let player_id = init.id;
// Open the UDP socket and ping the init message back until we get a response.
let mut udp_socket = UdpSocket::bind("0.0.0.0:0").await?;
udp_socket.connect(addr).await?;
let mut ticker = interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = ticker.tick() => {
udp_socket.send(bincode::serialize(&game::UdpServerMessage::Init(game::ServerInit { random_bytes: init.random_bytes }))?.as_slice()).await?;
},
_ = udp_socket.recv(&mut buf) => break,
};
}
// We're in! Launch separate tasks to read TCP and UDP.
let (mut internal_tcp_tx, mut tcp_rx) = channel(4);
let (mut tcp_tx, mut internal_tcp_rx) = channel(4);
let (mut internal_udp_tx, mut udp_rx) = channel(4);
let (mut udp_reader, mut udp_writer) = udp_socket.split();
let (mut tcp_reader, mut tcp_writer) = tcp_stream.into_split();
tokio::spawn(async move {
let mut buf: [u8; MAX_PACKET_SIZE_PLUS_ONE] = [0; MAX_PACKET_SIZE_PLUS_ONE];
loop {
match tcp_reader.read(&mut buf).await {
Ok(0) => break,
Ok(MAX_PACKET_SIZE_PLUS_ONE) => break,
Ok(num_bytes) => {
// Send the message down the internal channel.
let tcp_message: game::TcpClientMessage = match bincode::deserialize(&buf[..num_bytes]) {
Ok(msg) => msg,
Err(err) => {
eprintln!("failed to deserialize TCP message: {}", err);
break
}
};
match internal_tcp_tx.send(tcp_message).await {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
break
},
};
},
Err(err) => {
eprintln!("{}", err);
break
},
};
}
});
tokio::spawn(async move {
let mut buf: [u8; MAX_PACKET_SIZE_PLUS_ONE] = [0; MAX_PACKET_SIZE_PLUS_ONE];
loop {
match udp_reader.recv(&mut buf).await {
Ok(0) => break,
Ok(MAX_PACKET_SIZE_PLUS_ONE) => {
eprintln!("packet too big for buffer!");
break;
},
Ok(num_bytes) => {
// Send the message down the internal channel.
let udp_message: game::UdpClientMessage = match bincode::deserialize(&buf[..num_bytes]) {
Ok(msg) => msg,
Err(err) => {
eprintln!("{}", err);
break
}
};
// TODO(jack) When these messages get too big, everything crashes.
// It doesn't matter what gets sent down the channel.
match internal_udp_tx.send(udp_message).await {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
break
},
};
},
Err(err) => {
eprintln!("{}", err);
break
},
};
}
});
tokio::spawn(async move {
loop {
match internal_tcp_rx.recv().await {
Some(msg) => {
match tcp_writer.write(match bincode::serialize(msg) {
Ok(msg) => msg,
Err(err) => {
eprintln!("{}", err);
break
},
}.as_slice()).await {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
break
}
};
},
None => break,
};
}
});
let tick_period = Duration::from_secs(1) / init.tick_rate as u32;
let mut tick = SystemTime::now().duration_since(init.tick_zero)?.as_nanos() / (tick_period.as_secs_f64() * 1e9) as u128;
// Send input over UDP at a separate input rate.
let (mut input_tx, mut internal_input_rx) = channel(32);
tokio::spawn(async move {
let mut inputs = Vec::new();
let mut tick_interval = interval(tick_period);
let mut input_interval = interval(Duration::from_secs(1) / 60); // TODO(jack) Haven't really figured this out yet.
loop {
tokio::select! {
_ = tick_interval.tick() => {
// Sample player input.
let last_input = (0..)
.map(|_| match internal_input_rx.try_recv() {
Ok(input) => Some(Ok(input)),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Closed) => Some(Err(TryRecvError::Closed)),
})
.take_while(|x: &Option<Result<game::PlayerInput, TryRecvError>>| x.is_some())
.map(|x| x.unwrap())
.last();
let mut input = match last_input {
None => continue,
Some(Ok(input)) => input,
Some(Err(_)) => break,
};
input.tick = tick as u16;
inputs.push(input);
tick += 1;
},
_ = input_interval.tick() => {
if inputs.len() == 0 {
continue
}
let msg = game::UdpServerMessage::PlayerInput(inputs.clone());
let bytes = bincode::serialize(&msg).unwrap();
inputs.clear();
match udp_writer.send(&bytes).await {
Ok(_) => (),
Err(err) => {
eprintln!("{}", err);
return
}
}
}
}
}
});
// Write a dummy message to the server.
tcp_tx.try_send(&game::TcpServerMessage::Test(4))?;
let sdl = sdl2::init()?;
let sdl_video = sdl.video()?;
let window = sdl_video
.window("game", 600, 480)
.resizable()
.build()?;
let mut canvas = window
.into_canvas()
.accelerated()
.present_vsync()
.build()?;
// Load a font.
let sdl_ttf = sdl2::ttf::init()?;
let texture_creator = canvas.texture_creator();
let font = sdl_ttf.load_font("/usr/share/fonts/gsfonts/URWGothic-BookOblique.otf", 128)?;
let mut event_pump = sdl.event_pump()?;
let mut input = game::PlayerInput {
tick: 0,
up: false, left: false, down: false, right: false,
mouse_left: false, mouse_right: false,
angle: 0.0,
};
let tick_period = tick_period.as_secs_f64();
let mut current_time = SystemTime::now();
let duration_since_tick_zero = current_time
.duration_since(init.tick_zero)?;
let mut tick_dt_counter = duration_since_tick_zero.as_secs_f64() % tick_period;
let mut tick = (duration_since_tick_zero.as_nanos() / (tick_period * 1e9) as u128) as u16;
let scale = 40.0;
'game: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} => break 'game,
Event::MouseButtonDown { mouse_btn: MouseButton::Left, .. } => input.mouse_left = true,
Event::MouseButtonDown { mouse_btn: MouseButton::Right, .. } => input.mouse_right = true,
Event::MouseButtonUp { mouse_btn: MouseButton::Left, .. } => input.mouse_left = false,
Event::MouseButtonUp { mouse_btn: MouseButton::Right, .. } => input.mouse_right = false,
Event::MouseMotion {x, y, ..} => {
// Do player lerp.
// It's necessary to know the player position for the mouse position.
// TODO(jack) We should only bother with this for the final mouse motion event in the pump.
let num_ticks = world.updates[1].tick - world.updates[0].tick;
let mix_unclamped = ((tick as i32 - world.updates[0].tick as i32 - 1) as f64 + tick_dt_counter / tick_period) / num_ticks as f64;
let position = world.updates[1].players.iter().find(|p| p.id == player_id).unwrap().position;
let positions = [
world.updates[0].players.iter()
.find(|p| p.id == player_id)
.map(|p| p.position)
.unwrap_or(position),
position,
];
let mix = if mix_unclamped < 0.0 { 0.0 } else if mix_unclamped > 1.0 { 1.0 } else { mix_unclamped };
let player_position = mix * positions[1] + (1.0 - mix) * positions[0];
let mouse = Vector2::new(x as f64 / scale, y as f64 / scale);
let diff = mouse - player_position;
input.angle = diff.y.atan2(diff.x);
},
_ => (),
};
let keycode_and_on = match event {
Event::KeyDown { keycode: Some(keycode), .. } => Some((keycode, true)),
Event::KeyUp { keycode: Some(keycode), .. } => Some((keycode, false)),
_ => None,
};
match keycode_and_on {
Some((Keycode::W, on)) => input.up = on,
Some((Keycode::A, on)) => input.left = on,
Some((Keycode::S, on)) => input.down = on,
Some((Keycode::D, on)) => input.right = on,
_ => (),
}
}
// Read TCP and UDP messages.
match tcp_rx.try_recv() {
Ok(msg) => match msg {
game::TcpClientMessage::PlayerJoined(id) => {
println!("player joined: {}", id);
},
game::TcpClientMessage::PlayerLeft(id) => {
println!("player left: {}", id);
},
_ => eprintln!("received unknown message from server: {:?}", msg),
},
Err(TryRecvError::Empty) => (),
Err(TryRecvError::Closed) => break,
}
loop {
match udp_rx.try_recv() {
Ok(msg) => match msg {
game::UdpClientMessage::WorldUpdate(update) => {
// Sort the update into the world updates.
let mut updates = Vec::with_capacity(world.updates.len() + 1);
updates.push(update);
updates.extend_from_slice(&world.updates);
updates.sort_unstable_by_key(|w| w.tick);
world.updates.clone_from_slice(&updates[1..]);
},
},
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Closed) => break 'game,
}
}
let now = SystemTime::now();
let dt = now.duration_since(current_time)?.as_secs_f64();
current_time = now;
tick_dt_counter += dt;
if tick_dt_counter >= tick_period {
tick_dt_counter %= tick_period;
tick += 1;
input.tick = tick as u16;
}
// Send input.
input_tx.send(input).await?;
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
let num_ticks = world.updates[1].tick - world.updates[0].tick;
let mix_unclamped = ((tick as i32 - world.updates[0].tick as i32 - num_ticks as i32) as f64 + tick_dt_counter / tick_period) / num_ticks as f64;
let mix = if mix_unclamped < 0.0 { 0.0 } else if mix_unclamped > 1.0 { 1.0 } else { mix_unclamped };
for player in &world.updates[1].players {
let color = if player.id == player_id {
Color::RGB(255, 255, 255)
} else {
Color::RGB(255, 0, 0)
};
let previous_player = match world.updates[0].players.iter().find(|p| p.id == player.id) {
Some(p) => p,
None => player,
};
let position = mix * player.position + (1.0 - mix) * previous_player.position;
let radius = mix * player.radius + (1.0 - mix) * previous_player.radius;
let position = position * scale;
let radius = radius * scale;
canvas.filled_circle(
position.x as i16,
position.y as i16,
radius as i16,
color,
)?;
}
for bullet in &world.updates[1].bullets {
let color = if bullet.player_id == player_id {
Color::RGB(255, 255, 255)
} else {
Color::RGB(255, 0, 0)
};
let previous_bullet = match world.updates[0].bullets.iter().find(|b| b.id == bullet.id) {
Some(b) => b,
None => bullet,
};
let position = mix * bullet.position + (1.0 - mix) * previous_bullet.position;
let radius = mix * bullet.radius + (1.0 - mix) * previous_bullet.radius;
let position = position * scale;
let radius = radius * scale;
canvas.filled_circle(
position.x as i16,
position.y as i16,
radius as i16,
color,
)?;
}
let surface = font
.render(&format!(
"{} {}",
world.updates[1].tick,
tick,
))
.blended(Color::RGB(255, 255, 255))?;
let texture = texture_creator.create_texture_from_surface(&surface)?;
canvas.copy(&texture, None, Rect::new(0, 0, surface.width(), surface.height()))?;
canvas.present();
}
Ok(())
}
|
use actix_web::{HttpRequest, HttpResponse, FutureResponse, AsyncResponder, HttpMessage, http};
use futures::Future;
use apps::app::AppState;
use database::{db, models};
#[derive(Deserialize, Serialize, Debug)]
pub struct NewUser {
email: String,
}
pub fn user_create_handler(req: &HttpRequest<AppState>) -> FutureResponse<HttpResponse> {
let db_chan = req.state().db.clone();
req.json()
.from_err()
.and_then(move |val: NewUser| {
db_chan.send(db::CreateUser {
email: val.email
})
.from_err()
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()),
})
}).responder()
}
pub fn user_detail_handler(req: &HttpRequest<AppState>) -> FutureResponse<HttpResponse> {
let id: i32 = req.match_info().query("id").unwrap();
let db_chan = req.state().db.clone();
db_chan.send(db::GetUser {
id
})
.from_err()
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::new(http::StatusCode::NOT_FOUND)),
}).responder()
}
pub fn user_update_handler(req: &HttpRequest<AppState>) -> FutureResponse<HttpResponse> {
let id: i32 = req.match_info().query("id").unwrap();
let db_chan = req.state().db.clone();
req.json()
.from_err()
.and_then(move |val: NewUser| {
db_chan
.send(db::UpdateUser {
user: models::User {
id,
email: val.email,
}
})
.from_err()
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()),
})
}).responder()
}
pub fn user_delete_handler(req: &HttpRequest<AppState>) -> FutureResponse<HttpResponse> {
let id: i32 = req.match_info().query("id").unwrap();
let db_chan = req.state().db.clone();
db_chan.send(db::DeleteUser {
id
})
.from_err()
.and_then(|res| match res {
Ok(_) => Ok(HttpResponse::build(http::StatusCode::OK).body("User deleted")),
Err(_) => Ok(HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR)),
}).responder()
}
pub fn user_list_handler(req: &HttpRequest<AppState>) -> FutureResponse<HttpResponse> {
let db_chan = req.state().db.clone();
db_chan.send(db::ListUsers)
.from_err()
.and_then(|res| match res {
Ok(users) => Ok(HttpResponse::Ok().json(users)),
Err(_) => Ok(HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR)),
}).responder()
}
|
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
use bully::{MembershipList, Port};
#[derive(Debug, Serialize, Deserialize)]
pub struct Gossip {
hostname: String,
port: Port,
pub membership_list: Arc<RwLock<MembershipList>>,
}
impl Gossip {
pub fn new(hostname: String, port: Port, initial_nodes: &[Port]) -> Self {
Self {
hostname,
port,
membership_list: Arc::new(RwLock::new(MembershipList::from((
initial_nodes,
Some(port),
)))),
}
}
pub fn get_random(&self) -> Vec<Port> {
self.membership_list.read().unwrap().get_random()
}
}
|
#[link(
name = "rush",
vers = "0.1.0",
uuid = "636e5f0c-2815-11e3-989c-6bd39c248c79"
)];
#[desc = "A shell written in Rust"];
#[license = "GPLv3"];
#[feature(globs)];
extern mod extra;
use std::os;
mod rush;
fn main()
{
let args: ~[~str] = os::args();
::rush::start(args);
}
|
// Copyright (c) 2019 Aigbe Research
// ts_36211.rs
// TS 36.211: Physical channels and modulation
//
// Physical layer processing:
// scrambling
// modulation
// layer mapping
// precoding
// mapping to resource elements
// OFDM signal generation
//
// Input to the physical layer: codewords
// Roadmap: GPU support for baseband processing
pub mod scrambling;
pub mod modulation;
pub mod layer_mapping;
pub mod precoding;
pub mod re_mapping;
pub mod ofdm;
// pub fn scramble(phy_layer: &mut PhysicalLayer){
// scrambling::run(phy_layer);
// }
// pub fn demodulate() {
// }
// pub fn modulate() {
// }
// pub fn map_layer() {
// // TODO
// }
// pub fn precode() {
// // TODO
// }
// pub fn re_map() {
// // TODO
// }
|
fn main(){
//创建空字符串
let str:String = String::new();
//从abc字面量字符串创建String类型
let str1:String = String::From("abc");
//从abc字面量字符串创建String类型,与上一句作用相同
let str2:String = "abc".to_string();
//以上字符串不可修改,均为只读,未加mut修饰符
}
|
use game_lib::{
bevy::{
ecs::{self as bevy_ecs, component::Component, schedule::ShouldRun, system::BoxedSystem},
prelude::*,
},
derive_more::{Display, Error},
};
use std::fmt::Debug;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
enum ModeState {
Started,
Changed,
Unchanged,
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct Mode<T: Component + Eq> {
current: T,
queued: Option<T>,
prev: Option<T>,
state: ModeState,
}
impl<T: Component + Debug + Eq> Mode<T> {
pub fn new(initial: T) -> Self {
Mode {
current: initial,
queued: None,
prev: None,
state: ModeState::Started,
}
}
pub fn get(&self) -> &T {
&self.current
}
pub fn get_prev(&self) -> Option<&T> {
self.prev.as_ref()
}
pub fn get_queued(&self) -> Option<&T> {
self.queued.as_ref()
}
pub fn enqueue(&mut self, value: T) -> Result<(), ModeEnqueueError<T>> {
if self.queued.is_some() {
Err(ModeEnqueueError::ChangeAlreadyQueued { value })
} else if self.current == value {
Err(ModeEnqueueError::ModeAlreadySet { value })
} else {
self.queued = Some(value);
Ok(())
}
}
pub fn update(&mut self) {
let mut changed = self.state == ModeState::Started;
if let Some(queued) = self.queued.take() {
let prev = std::mem::replace(&mut self.current, queued);
self.prev = Some(prev);
changed = true;
} else {
self.prev = None;
}
self.state = if changed {
ModeState::Changed
} else {
ModeState::Unchanged
};
}
pub fn if_active(value: T) -> BoxedSystem<(), ShouldRun> {
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DelayState {
Delayed,
Ready,
}
#[derive(Debug)]
struct LocalState<T> {
target: T,
delay: DelayState,
}
Box::new(
(|mode: ResMut<Mode<T>>, mut state: Local<Option<LocalState<T>>>| -> ShouldRun {
let state = state.as_mut().unwrap();
if mode.get() == &state.target {
match state.delay {
DelayState::Ready if mode.state == ModeState::Changed => {
state.delay = DelayState::Delayed;
ShouldRun::NoAndCheckAgain
}
DelayState::Delayed | DelayState::Ready => {
state.delay = DelayState::Ready;
ShouldRun::Yes
}
}
} else {
ShouldRun::No
}
})
.system()
.config(|(_, state)| {
*state = Some(Some(LocalState {
target: value,
delay: DelayState::Ready,
}))
}),
)
}
pub fn if_inactive(value: T) -> BoxedSystem<(), ShouldRun> {
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DelayState {
Delayed,
Ready,
}
#[derive(Debug)]
struct LocalState<T> {
target: T,
delay: DelayState,
}
Box::new(
(|mode: ResMut<Mode<T>>, mut state: Local<Option<LocalState<T>>>| -> ShouldRun {
let state = state.as_mut().unwrap();
if mode.get() != &state.target {
match state.delay {
DelayState::Ready if mode.state == ModeState::Changed => {
state.delay = DelayState::Delayed;
ShouldRun::NoAndCheckAgain
}
DelayState::Delayed | DelayState::Ready => {
state.delay = DelayState::Ready;
ShouldRun::Yes
}
}
} else {
ShouldRun::No
}
})
.system()
.config(|(_, state)| {
*state = Some(Some(LocalState {
target: value,
delay: DelayState::Ready,
}))
}),
)
}
pub fn if_entered(value: T) -> BoxedSystem<(), ShouldRun> {
Box::new(
(|mode: ResMut<Mode<T>>, target: Local<Option<T>>| -> ShouldRun {
target
.as_ref()
.filter(|&target| mode.state == ModeState::Changed && mode.get() == target)
.map(|_| ShouldRun::Yes)
.unwrap_or(ShouldRun::No)
})
.system()
.config(|(_, target)| *target = Some(Some(value))),
)
}
pub fn if_exited(value: T) -> BoxedSystem<(), ShouldRun> {
Box::new(
(|mode: ResMut<Mode<T>>, target: Local<Option<T>>| -> ShouldRun {
target
.as_ref()
.filter(|&target| mode.state == ModeState::Changed && mode.get() != target)
.and_then(|target| mode.get_prev().filter(|&prev| prev == target))
.map(|_| ShouldRun::Yes)
.unwrap_or(ShouldRun::No)
})
.system()
.config(|(_, target)| *target = Some(Some(value))),
)
}
}
#[derive(Debug, Display, Error)]
pub enum ModeEnqueueError<T>
where
T: Component + Eq,
{
#[display(fmt = "a change was already queued")]
ChangeAlreadyQueued { value: T },
#[display(fmt = "the requested mode is already the current mode")]
ModeAlreadySet { value: T },
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, SystemLabel, AmbiguitySetLabel)]
pub enum ModeSystem {
UpdateModes,
}
|
#![windows_subsystem = "windows"]
use chrono::{Datelike, NaiveDate, NaiveTime, Weekday};
use notify_rust::Notification;
use serde::Deserialize;
#[derive(Debug)]
enum WeekType {
A,
B,
C,
}
#[derive(Debug)]
struct Bell {
bell: String,
time: NaiveTime,
}
#[derive(Debug)]
struct Bells {
status: String,
bells_altered: bool,
bells_altered_reason: String,
bells: Vec<Bell>,
date: NaiveDate,
day: Weekday,
term: u8,
week: u8,
week_type: WeekType,
}
impl From<BellsResponse> for Bells {
fn from(response: BellsResponse) -> Self {
let bells_list: Vec<_> = response
.bells
.into_iter()
.map(|response_bell| Bell {
bell: match &response_bell.bell[..] {
"1" => String::from("Period 1"),
"2" => String::from("Period 2"),
"3" => String::from("Period 3"),
"4" => String::from("Period 4"),
"5" => String::from("Period 5"),
_ => response_bell.bell,
},
time: NaiveTime::parse_from_str(&response_bell.time[..], "%H:%M").unwrap(),
})
.collect();
Bells {
status: response.status,
bells_altered: response.bells_altered,
bells_altered_reason: response.bells_altered_reason,
bells: bells_list,
date: NaiveDate::parse_from_str(&response.date[..], "%Y-%m-%d").unwrap(),
day: match &response.day[..] {
"Monday" => Weekday::Mon,
"Tuesday" => Weekday::Tue,
"Wednesday" => Weekday::Wed,
"Thursday" => Weekday::Thu,
"Friday" => Weekday::Fri,
_ => panic!("The response weekday doesn't match any of the weekday patterns!"),
},
term: response.term.parse().unwrap(),
week: response.week.parse().unwrap(),
week_type: match &response.week_type[..] {
"A" => WeekType::A,
"B" => WeekType::B,
"C" => WeekType::C,
_ => panic!("The week type doesn't match any of the week type patterns!"),
},
}
}
}
#[derive(Deserialize)]
struct ResponseBell {
bell: String,
time: String,
}
#[derive(Deserialize)]
struct BellsResponse {
status: String,
#[serde(rename = "bellsAltered")]
bells_altered: bool,
#[serde(rename = "bellsAlteredReason")]
bells_altered_reason: String,
bells: Vec<ResponseBell>,
date: String,
day: String,
term: String,
week: String,
#[serde(rename = "weekType")]
week_type: String,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
Notification::new()
.summary("RunToClass | Active")
.body("RunToClass is active and will notify you of school belltimes.")
.show()?;
loop {
let response = fetch_bells();
let bells: Bells;
match response {
Ok(response) => bells = Bells::from(response),
Err(_) => {
Notification::new()
.summary("RunToClass | Offline Mode")
.body("RunToClass cannot connect to the SBHS Student Portal API and will use offline mode. Keep in mind that you will not be notified of changed bell times this way.")
.show()?;
bells = get_offline_bells();
}
}
println!("{:#?}", bells);
if bells.bells_altered {
Notification::new()
.summary("RunToClass | Bells Changed")
.body(
&(String::from("The bell times have been changed for today. Reason: ")
+ &bells.bells_altered_reason[..])[..],
)
.show()?;
}
for bell in bells.bells {
if chrono::Local::now().naive_local().time() > bell.time {
continue;
}
loop {
let now_time = chrono::Utc::now().naive_local().time();
if !(now_time <= bell.time) {
continue;
}
Notification::new()
.summary(&bell.bell[..])
.body("This notification was sent by RunToClass.")
.show()?;
break;
}
}
loop {
if chrono::Local::today().naive_local() <= bells.date {
continue;
}
break;
}
}
}
fn fetch_bells() -> Result<BellsResponse, reqwest::Error> {
let response: BellsResponse =
reqwest::blocking::get("https://student.sbhs.net.au/api/timetable/bells.json")?.json()?;
Ok(response)
}
fn get_offline_bells() -> Bells {
let today = chrono::Local::today().naive_local();
let bells = match today.weekday() {
Weekday::Mon | Weekday::Tue => vec![
Bell {
bell: String::from("Warning Bell"),
time: NaiveTime::from_hms(9, 0, 0),
},
Bell {
bell: String::from("Period 1"),
time: NaiveTime::from_hms(9, 5, 0),
},
Bell {
bell: String::from("Transition"),
time: NaiveTime::from_hms(10, 5, 0),
},
Bell {
bell: String::from("Period 2"),
time: NaiveTime::from_hms(10, 10, 0),
},
Bell {
bell: String::from("Lunch 1"),
time: NaiveTime::from_hms(11, 10, 0),
},
Bell {
bell: String::from("Lunch 2"),
time: NaiveTime::from_hms(11, 30, 0),
},
Bell {
bell: String::from("Period 3"),
time: NaiveTime::from_hms(11, 50, 0),
},
Bell {
bell: String::from("Transition"),
time: NaiveTime::from_hms(12, 50, 0),
},
Bell {
bell: String::from("Period 4"),
time: NaiveTime::from_hms(12, 55, 0),
},
Bell {
bell: String::from("Recess"),
time: NaiveTime::from_hms(13, 55, 0),
},
Bell {
bell: String::from("Period 5"),
time: NaiveTime::from_hms(14, 15, 0),
},
Bell {
bell: String::from("End of Day"),
time: NaiveTime::from_hms(15, 15, 0),
},
],
Weekday::Wed | Weekday::Thu => vec![
Bell {
bell: String::from("Warning Bell"),
time: NaiveTime::from_hms(9, 0, 0),
},
Bell {
bell: String::from("Period 1"),
time: NaiveTime::from_hms(9, 5, 0),
},
Bell {
bell: String::from("Transition"),
time: NaiveTime::from_hms(10, 5, 0),
},
Bell {
bell: String::from("Period 2"),
time: NaiveTime::from_hms(10, 10, 0),
},
Bell {
bell: String::from("Recess"),
time: NaiveTime::from_hms(11, 10, 0),
},
Bell {
bell: String::from("Period 3"),
time: NaiveTime::from_hms(11, 30, 0),
},
Bell {
bell: String::from("Lunch 1"),
time: NaiveTime::from_hms(12, 30, 0),
},
Bell {
bell: String::from("Lunch 2"),
time: NaiveTime::from_hms(12, 50, 0),
},
Bell {
bell: String::from("Period 4"),
time: NaiveTime::from_hms(13, 10, 0),
},
Bell {
bell: String::from("Transition"),
time: NaiveTime::from_hms(14, 10, 0),
},
Bell {
bell: String::from("Period 5"),
time: NaiveTime::from_hms(14, 15, 0),
},
Bell {
bell: String::from("End of Day"),
time: NaiveTime::from_hms(15, 15, 0),
},
],
Weekday::Fri => vec![
Bell {
bell: String::from("Scripture"),
time: NaiveTime::from_hms(8, 50, 0),
},
Bell {
bell: String::from("Warning Bell"),
time: NaiveTime::from_hms(9, 25, 0),
},
Bell {
bell: String::from("Period 1"),
time: NaiveTime::from_hms(9, 30, 0),
},
Bell {
bell: String::from("Transition"),
time: NaiveTime::from_hms(10, 25, 0),
},
Bell {
bell: String::from("Period 2"),
time: NaiveTime::from_hms(10, 30, 0),
},
Bell {
bell: String::from("Recess"),
time: NaiveTime::from_hms(11, 25, 0),
},
Bell {
bell: String::from("Period 3"),
time: NaiveTime::from_hms(11, 45, 0),
},
Bell {
bell: String::from("Lunch 1"),
time: NaiveTime::from_hms(12, 40, 0),
},
Bell {
bell: String::from("Lunch 2"),
time: NaiveTime::from_hms(13, 0, 0),
},
Bell {
bell: String::from("Period 4"),
time: NaiveTime::from_hms(13, 20, 0),
},
Bell {
bell: String::from("Transition"),
time: NaiveTime::from_hms(14, 15, 0),
},
Bell {
bell: String::from("Period 5"),
time: NaiveTime::from_hms(14, 20, 0),
},
Bell {
bell: String::from("End of Day"),
time: NaiveTime::from_hms(15, 15, 0),
},
],
_ => vec![],
};
Bells {
status: String::from("OK"),
bells_altered: false,
bells_altered_reason: String::from(""),
bells,
date: today,
day: today.weekday(),
term: 1,
week: 1,
week_type: WeekType::A,
}
}
|
use super::Result;
///! Helpers functions to output `cargo:` lines suitable for build.rs output.
use std::env;
use std::path::Path;
/// Find out if we are cross-compiling.
pub fn is_cross_compiling() -> Result<bool> {
Ok(env::var("TARGET")? != env::var("HOST")?)
}
/// Adds a `cargo:rustc-link-lib=` line.
pub fn include_path<P: AsRef<Path>>(lib_dir_path: P) -> Result<()> {
println!("cargo:rustc-link-lib={}", lib_dir_path.as_ref().display());
Ok(())
}
/// Adds a `cargo:rustc-link-search=` and `cargo:rustc-link-lib=static=` line.
pub fn link_static<P: AsRef<Path>>(lib_name: &str, lib_dir_path: P) -> Result<()> {
println!(
"cargo:rustc-link-search={}",
lib_dir_path.as_ref().display()
);
println!("cargo:rustc-link-lib=static={}", lib_name);
Ok(())
}
/// Adds a `cargo:rustc-link-search=` and `cargo:rustc-link-lib=dylib=` line.
pub fn link_dylib<P: AsRef<Path>>(lib_name: &str, lib_dir_path: P) -> Result<()> {
println!(
"cargo:rustc-link-search={}",
lib_dir_path.as_ref().display()
);
println!("cargo:rustc-link-lib=dylib={}", lib_name);
Ok(())
}
/// Adds a `cargo:rustc-link-search` and `cargo:rustc-link-lib=` line.
pub fn link_lib<P: AsRef<Path>>(lib_name: &str, lib_dir_path: P) -> Result<()> {
println!(
"cargo:rustc-link-search={}",
lib_dir_path.as_ref().display()
);
println!("cargo:rustc-link-lib={}", lib_name);
Ok(())
}
/// Adds a `cargo:rustc-link-lib=dylib=` line.
pub fn link_system_dylib(lib_name: &str) -> Result<()> {
println!("cargo:rustc-link-lib=dylib={}", lib_name);
Ok(())
}
/// Adds a `cargo:rustc-link-lib=` line.
pub fn link_system_lib(lib_name: &str) -> Result<()> {
println!("cargo:rustc-link-lib={}", lib_name);
Ok(())
}
/// Adds a `cargo:rerun-if-changed=` line.
pub fn rerun_if_changed<P: AsRef<Path>>(filepath: P) {
println!("cargo:rerun-if-changed={}", filepath.as_ref().display());
}
|
use proconio::{input, marker::Usize1};
fn dfs(i: usize, p: usize, g: &Vec<Vec<usize>>, size: &mut Vec<usize>) {
size[i] = 1;
for &j in &g[i] {
if j == p {
continue;
}
dfs(j, i, g, size);
size[i] += size[j];
}
}
fn solve(i: usize, p: usize, g: &Vec<Vec<usize>>, size: &Vec<usize>, acc: usize, ans: &mut Vec<usize>) {
// 頂点 i を根にして解く
let mut children = vec![acc];
for &j in &g[i] {
if j == p {
continue;
}
children.push(size[j]);
}
let mut dp1 = 0;
let mut dp2 = 0;
let mut dp3 = 0;
for &c in &children {
dp3 += dp2 * c;
dp2 += dp1 * c;
dp1 += c;
}
// eprintln!("i = {}, acc = {}, dp3 = {}, dp2 = {}, dp1 = {}", i, acc, dp3, dp2, dp1);
ans[i] = dp3;
// 再帰的に解く
for &j in &g[i] {
if j == p {
continue;
}
solve(j, i, g, size, acc + size[i] - size[j], ans);
}
}
fn main() {
input! {
n: usize,
edges: [(Usize1, Usize1); n - 1],
};
let mut g = vec![vec![]; n];
for (a, b) in edges {
g[a].push(b);
g[b].push(a);
}
let mut size = vec![0; n];
dfs(0, std::usize::MAX, &g, &mut size);
// eprintln!("size = {:?}", size);
let mut ans = vec![0; n];
solve(0, std::usize::MAX, &g, &size, 0, &mut ans);
let mut total = 0;
for ans in ans {
total += ans;
}
println!("{}", total);
}
|
use anyhow::Result;
use std::sync::Arc;
#[derive(Debug)]
pub struct RenderTexture {
pub texture: Arc<wgpu::Texture>,
pub size: wgpu::Extent3d,
pub view: wgpu::TextureView,
}
impl RenderTexture {
pub fn new(width: u32, height: u32, device: &wgpu::Device) -> Result<Self> {
let size = wgpu::Extent3d {
width,
height,
depth: 1,
};
let desc = wgpu::TextureDescriptor {
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8UnormSrgb, // the format is required by render pipeline??
usage: wgpu::TextureUsage::COPY_SRC | wgpu::TextureUsage::OUTPUT_ATTACHMENT,
label: Some("Render Texture"),
size,
};
let texture = device.create_texture(&desc);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
Ok(Self {
texture: Arc::new(texture),
size,
view,
})
}
}
|
/*
* RustCat - A port of NetCat to Rust.
* Written by Noah Snelson, in the year of Our Lord 2019.
*/
#[macro_use]
extern crate clap;
use std::fs::{File, remove_file};
mod connect;
mod listen;
use rustcat::lib::CliArgs;
fn main() {
let matches = clap_app!(rustcat =>
(version: "0.1.0")
(author: "Noah Snelson <noah.snelson@protonmail.com>")
(about: "Rewrite of the netcat tool in Rust.")
(@arg listen: -l --listen conflicts_with[host]
"Listen for incoming connection on port.")
(@arg host: +takes_value conflicts_with[listen]
"IP or hostname to connect to.")
(@arg listenport: -p --port +takes_value requires[listen]
"Port to listen on.")
(@arg connectport: +takes_value conflicts_with[listen]
"Port to connect to.")
(@arg command: -e --execute +takes_value requires[listen]
"Pipe incoming queries to specified program.")
(@arg output: -o --output +takes_value
"Hexdump incoming and outgoing traffic to file.")
).get_matches();
if matches.is_present("output") {
let filename = matches.value_of("output").unwrap();
match File::open(filename) {
Ok(_) => remove_file(filename),
Err(_) => Ok(()),
}.unwrap();
}
if matches.is_present("listen"){
let args = CliArgs{
port: String::from(matches.value_of("listenport").unwrap()),
host: String::new(),
command: matches.value_of("command").map(String::from),
output: matches.value_of("output").map(String::from),
};
listen::listen_loop(args).unwrap();
}
else{
let args = CliArgs{
port: String::from(matches.value_of("connectport").unwrap()),
host: String::from(matches.value_of("host").unwrap()),
command: matches.value_of("command").map(String::from),
output: matches.value_of("output").map(String::from),
};
connect::write_loop(args).unwrap();
}
}
|
use egg::*;
define_language! {
enum Prop {
Bool(bool),
"pr" = Pr([Id; 2]),
"vec" = PVec([Id; 4]),
"&" = And(Id),
"~" = Not(Id),
"pi1" = Pi1(Id),
"pi2" = Pi2(Id),
// "|" = Or([Id; 2]),
// "->" = Implies([Id; 2]),
"x" = X,
}
}
type EGraph = egg::EGraph<Prop, ()>;
type Rewrite = egg::Rewrite<Prop, ()>;
struct CostFn;
impl CostFunction<Prop> for CostFn {
type Cost = f64;
// you're passed in an enode whose children are costs instead of eclass ids
fn cost<C>(&mut self, enode: &Prop, mut costs: C) -> Self::Cost
where
C: FnMut(Id) -> Self::Cost,
{
let op_cost = match enode {
Prop::X => 0.001,
_ => 1.0,
};
enode.fold(op_cost, |sum, id| sum + costs(id))
}
}
macro_rules! rule {
($name:ident, $left:literal, $right:literal) => {
#[allow(dead_code)]
fn $name() -> Rewrite {
rewrite!(stringify!($name); $left => $right)
}
};
($name:ident, $name2:ident, $left:literal, $right:literal) => {
rule!($name, $left, $right);
rule!($name2, $right, $left);
};
}
macro_rules! rev_rule {
($name:ident, $left:literal, $right:literal) => {
#[allow(dead_code)]
fn $name() -> Rewrite {
rewrite!(stringify!($name); $right => $left)
}
};
}
// rule! {def_imply, def_imply_flip, "(-> ?a ?b)", "(| (~ ?a) ?b)" }
// rule! {double_neg, double_neg_flip, "(~ (~ ?a))", "?a" }
// rule! {assoc_or, "(| ?a (| ?b ?c))", "(| (| ?a ?b) ?c)" }
// rule! {dist_and_or, "(& ?a (| ?b ?c))", "(| (& ?a ?b) (& ?a ?c))"}
// rule! {dist_or_and, "(| ?a (& ?b ?c))", "(& (| ?a ?b) (| ?a ?c))"}
// rule! {comm_or, "(| ?a ?b)", "(| ?b ?a)" }
// rule! {comm_and, "(& ?a ?b)", "(& ?b ?a)" }
// rule! {lem, "(| ?a (~ ?a))", "true" }
// rule! {or_true, "(| ?a true)", "true" }
// rule! {and_true, "(& ?a true)", "?a" }
// rule! {contrapositive, "(-> ?a ?b)", "(-> (~ ?b) (~ ?a))" }
// rule! {lem_imply, "(& (-> ?a ?b) (-> (~ ?a) ?c))", "(| ?b ?c)"}
// thanks I hate it
rev_rule! {not_ffff, "(~ (vec false false false false))", "(vec true true true true)"}
rev_rule! {not_ffft, "(~ (vec false false false true))", "(vec true true true false)"}
rev_rule! {not_fftf, "(~ (vec false false true false))", "(vec true true false true)"}
rev_rule! {not_fftt, "(~ (vec false false true true))", "(vec true true false false)"}
rev_rule! {not_ftff, "(~ (vec false true false false))", "(vec true false true true)"}
rev_rule! {not_ftft, "(~ (vec false true false true))", "(vec true false true false)"}
rev_rule! {not_fttf, "(~ (vec false true true false))", "(vec true false false true)"}
rev_rule! {not_fttt, "(~ (vec false true true true))", "(vec true false false false)"}
rev_rule! {not_tfff, "(~ (vec true false false false))", "(vec false true true true)"}
rev_rule! {not_tfft, "(~ (vec true false false true))", "(vec false true true false)"}
rev_rule! {not_tftf, "(~ (vec true false true false))", "(vec false true false true)"}
rev_rule! {not_tftt, "(~ (vec true false true true))", "(vec false true false false)"}
rev_rule! {not_ttff, "(~ (vec true true false false))", "(vec false false true true)"}
rev_rule! {not_ttft, "(~ (vec true true false true))", "(vec false false true false)"}
rev_rule! {not_tttf, "(~ (vec true true true false))", "(vec false false false true)"}
rev_rule! {not_tttt, "(~ (vec true true true true))", "(vec false false false false)"}
rev_rule! {and_ffffffff, "(& (vec (pr false false) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ffffffft, "(& (vec (pr false false) (pr false false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fffffftf, "(& (vec (pr false false) (pr false false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fffffftt, "(& (vec (pr false false) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ffffftff, "(& (vec (pr false false) (pr false false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ffffftft, "(& (vec (pr false false) (pr false false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fffffttf, "(& (vec (pr false false) (pr false false) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fffffttt, "(& (vec (pr false false) (pr false false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fffftfff, "(& (vec (pr false false) (pr false false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fffftfft, "(& (vec (pr false false) (pr false false) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fffftftf, "(& (vec (pr false false) (pr false false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fffftftt, "(& (vec (pr false false) (pr false false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ffffttff, "(& (vec (pr false false) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_ffffttft, "(& (vec (pr false false) (pr false false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_fffftttf, "(& (vec (pr false false) (pr false false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_fffftttt, "(& (vec (pr false false) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_ffftffff, "(& (vec (pr false false) (pr false true) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ffftffft, "(& (vec (pr false false) (pr false true) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ffftfftf, "(& (vec (pr false false) (pr false true) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ffftfftt, "(& (vec (pr false false) (pr false true) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ffftftff, "(& (vec (pr false false) (pr false true) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ffftftft, "(& (vec (pr false false) (pr false true) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ffftfttf, "(& (vec (pr false false) (pr false true) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ffftfttt, "(& (vec (pr false false) (pr false true) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fffttfff, "(& (vec (pr false false) (pr false true) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fffttfft, "(& (vec (pr false false) (pr false true) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fffttftf, "(& (vec (pr false false) (pr false true) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fffttftt, "(& (vec (pr false false) (pr false true) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ffftttff, "(& (vec (pr false false) (pr false true) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_ffftttft, "(& (vec (pr false false) (pr false true) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_fffttttf, "(& (vec (pr false false) (pr false true) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_fffttttt, "(& (vec (pr false false) (pr false true) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_fftfffff, "(& (vec (pr false false) (pr true false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fftfffft, "(& (vec (pr false false) (pr true false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fftffftf, "(& (vec (pr false false) (pr true false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fftffftt, "(& (vec (pr false false) (pr true false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fftfftff, "(& (vec (pr false false) (pr true false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fftfftft, "(& (vec (pr false false) (pr true false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fftffttf, "(& (vec (pr false false) (pr true false) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fftffttt, "(& (vec (pr false false) (pr true false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fftftfff, "(& (vec (pr false false) (pr true false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fftftfft, "(& (vec (pr false false) (pr true false) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fftftftf, "(& (vec (pr false false) (pr true false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fftftftt, "(& (vec (pr false false) (pr true false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fftfttff, "(& (vec (pr false false) (pr true false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_fftfttft, "(& (vec (pr false false) (pr true false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_fftftttf, "(& (vec (pr false false) (pr true false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_fftftttt, "(& (vec (pr false false) (pr true false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_ffttffff, "(& (vec (pr false false) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_ffttffft, "(& (vec (pr false false) (pr true true) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_ffttfftf, "(& (vec (pr false false) (pr true true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_ffttfftt, "(& (vec (pr false false) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_ffttftff, "(& (vec (pr false false) (pr true true) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_ffttftft, "(& (vec (pr false false) (pr true true) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_ffttfttf, "(& (vec (pr false false) (pr true true) (pr false true) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_ffttfttt, "(& (vec (pr false false) (pr true true) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_fftttfff, "(& (vec (pr false false) (pr true true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_fftttfft, "(& (vec (pr false false) (pr true true) (pr true false) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_fftttftf, "(& (vec (pr false false) (pr true true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_fftttftt, "(& (vec (pr false false) (pr true true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_ffttttff, "(& (vec (pr false false) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {and_ffttttft, "(& (vec (pr false false) (pr true true) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {and_fftttttf, "(& (vec (pr false false) (pr true true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {and_fftttttt, "(& (vec (pr false false) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {and_ftffffff, "(& (vec (pr false true) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ftffffft, "(& (vec (pr false true) (pr false false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ftfffftf, "(& (vec (pr false true) (pr false false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ftfffftt, "(& (vec (pr false true) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ftffftff, "(& (vec (pr false true) (pr false false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ftffftft, "(& (vec (pr false true) (pr false false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ftfffttf, "(& (vec (pr false true) (pr false false) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ftfffttt, "(& (vec (pr false true) (pr false false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ftfftfff, "(& (vec (pr false true) (pr false false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ftfftfft, "(& (vec (pr false true) (pr false false) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ftfftftf, "(& (vec (pr false true) (pr false false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ftfftftt, "(& (vec (pr false true) (pr false false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ftffttff, "(& (vec (pr false true) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_ftffttft, "(& (vec (pr false true) (pr false false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_ftfftttf, "(& (vec (pr false true) (pr false false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_ftfftttt, "(& (vec (pr false true) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_ftftffff, "(& (vec (pr false true) (pr false true) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ftftffft, "(& (vec (pr false true) (pr false true) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ftftfftf, "(& (vec (pr false true) (pr false true) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ftftfftt, "(& (vec (pr false true) (pr false true) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ftftftff, "(& (vec (pr false true) (pr false true) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ftftftft, "(& (vec (pr false true) (pr false true) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ftftfttf, "(& (vec (pr false true) (pr false true) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ftftfttt, "(& (vec (pr false true) (pr false true) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ftfttfff, "(& (vec (pr false true) (pr false true) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_ftfttfft, "(& (vec (pr false true) (pr false true) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_ftfttftf, "(& (vec (pr false true) (pr false true) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_ftfttftt, "(& (vec (pr false true) (pr false true) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_ftftttff, "(& (vec (pr false true) (pr false true) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_ftftttft, "(& (vec (pr false true) (pr false true) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_ftfttttf, "(& (vec (pr false true) (pr false true) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_ftfttttt, "(& (vec (pr false true) (pr false true) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_fttfffff, "(& (vec (pr false true) (pr true false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fttfffft, "(& (vec (pr false true) (pr true false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fttffftf, "(& (vec (pr false true) (pr true false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fttffftt, "(& (vec (pr false true) (pr true false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fttfftff, "(& (vec (pr false true) (pr true false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fttfftft, "(& (vec (pr false true) (pr true false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fttffttf, "(& (vec (pr false true) (pr true false) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fttffttt, "(& (vec (pr false true) (pr true false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fttftfff, "(& (vec (pr false true) (pr true false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_fttftfft, "(& (vec (pr false true) (pr true false) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_fttftftf, "(& (vec (pr false true) (pr true false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_fttftftt, "(& (vec (pr false true) (pr true false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_fttfttff, "(& (vec (pr false true) (pr true false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_fttfttft, "(& (vec (pr false true) (pr true false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_fttftttf, "(& (vec (pr false true) (pr true false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_fttftttt, "(& (vec (pr false true) (pr true false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_ftttffff, "(& (vec (pr false true) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_ftttffft, "(& (vec (pr false true) (pr true true) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_ftttfftf, "(& (vec (pr false true) (pr true true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_ftttfftt, "(& (vec (pr false true) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_ftttftff, "(& (vec (pr false true) (pr true true) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_ftttftft, "(& (vec (pr false true) (pr true true) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_ftttfttf, "(& (vec (pr false true) (pr true true) (pr false true) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_ftttfttt, "(& (vec (pr false true) (pr true true) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_fttttfff, "(& (vec (pr false true) (pr true true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_fttttfft, "(& (vec (pr false true) (pr true true) (pr true false) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_fttttftf, "(& (vec (pr false true) (pr true true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_fttttftt, "(& (vec (pr false true) (pr true true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_ftttttff, "(& (vec (pr false true) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {and_ftttttft, "(& (vec (pr false true) (pr true true) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {and_fttttttf, "(& (vec (pr false true) (pr true true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {and_fttttttt, "(& (vec (pr false true) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {and_tfffffff, "(& (vec (pr true false) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tfffffft, "(& (vec (pr true false) (pr false false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tffffftf, "(& (vec (pr true false) (pr false false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tffffftt, "(& (vec (pr true false) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tfffftff, "(& (vec (pr true false) (pr false false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tfffftft, "(& (vec (pr true false) (pr false false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tffffttf, "(& (vec (pr true false) (pr false false) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tffffttt, "(& (vec (pr true false) (pr false false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tffftfff, "(& (vec (pr true false) (pr false false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tffftfft, "(& (vec (pr true false) (pr false false) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tffftftf, "(& (vec (pr true false) (pr false false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tffftftt, "(& (vec (pr true false) (pr false false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tfffttff, "(& (vec (pr true false) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_tfffttft, "(& (vec (pr true false) (pr false false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_tffftttf, "(& (vec (pr true false) (pr false false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_tffftttt, "(& (vec (pr true false) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_tfftffff, "(& (vec (pr true false) (pr false true) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tfftffft, "(& (vec (pr true false) (pr false true) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tfftfftf, "(& (vec (pr true false) (pr false true) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tfftfftt, "(& (vec (pr true false) (pr false true) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tfftftff, "(& (vec (pr true false) (pr false true) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tfftftft, "(& (vec (pr true false) (pr false true) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tfftfttf, "(& (vec (pr true false) (pr false true) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tfftfttt, "(& (vec (pr true false) (pr false true) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tffttfff, "(& (vec (pr true false) (pr false true) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tffttfft, "(& (vec (pr true false) (pr false true) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tffttftf, "(& (vec (pr true false) (pr false true) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tffttftt, "(& (vec (pr true false) (pr false true) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tfftttff, "(& (vec (pr true false) (pr false true) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_tfftttft, "(& (vec (pr true false) (pr false true) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_tffttttf, "(& (vec (pr true false) (pr false true) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_tffttttt, "(& (vec (pr true false) (pr false true) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_tftfffff, "(& (vec (pr true false) (pr true false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tftfffft, "(& (vec (pr true false) (pr true false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tftffftf, "(& (vec (pr true false) (pr true false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tftffftt, "(& (vec (pr true false) (pr true false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tftfftff, "(& (vec (pr true false) (pr true false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tftfftft, "(& (vec (pr true false) (pr true false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tftffttf, "(& (vec (pr true false) (pr true false) (pr false true) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tftffttt, "(& (vec (pr true false) (pr true false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tftftfff, "(& (vec (pr true false) (pr true false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {and_tftftfft, "(& (vec (pr true false) (pr true false) (pr true false) (pr false true)))", "(vec false false false false)"}
rev_rule! {and_tftftftf, "(& (vec (pr true false) (pr true false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {and_tftftftt, "(& (vec (pr true false) (pr true false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {and_tftfttff, "(& (vec (pr true false) (pr true false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {and_tftfttft, "(& (vec (pr true false) (pr true false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {and_tftftttf, "(& (vec (pr true false) (pr true false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {and_tftftttt, "(& (vec (pr true false) (pr true false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {and_tfttffff, "(& (vec (pr true false) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_tfttffft, "(& (vec (pr true false) (pr true true) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_tfttfftf, "(& (vec (pr true false) (pr true true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_tfttfftt, "(& (vec (pr true false) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_tfttftff, "(& (vec (pr true false) (pr true true) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_tfttftft, "(& (vec (pr true false) (pr true true) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_tfttfttf, "(& (vec (pr true false) (pr true true) (pr false true) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_tfttfttt, "(& (vec (pr true false) (pr true true) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_tftttfff, "(& (vec (pr true false) (pr true true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {and_tftttfft, "(& (vec (pr true false) (pr true true) (pr true false) (pr false true)))", "(vec false true false false)"}
rev_rule! {and_tftttftf, "(& (vec (pr true false) (pr true true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {and_tftttftt, "(& (vec (pr true false) (pr true true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {and_tfttttff, "(& (vec (pr true false) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {and_tfttttft, "(& (vec (pr true false) (pr true true) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {and_tftttttf, "(& (vec (pr true false) (pr true true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {and_tftttttt, "(& (vec (pr true false) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {and_ttffffff, "(& (vec (pr true true) (pr false false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_ttffffft, "(& (vec (pr true true) (pr false false) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_ttfffftf, "(& (vec (pr true true) (pr false false) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_ttfffftt, "(& (vec (pr true true) (pr false false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_ttffftff, "(& (vec (pr true true) (pr false false) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_ttffftft, "(& (vec (pr true true) (pr false false) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_ttfffttf, "(& (vec (pr true true) (pr false false) (pr false true) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_ttfffttt, "(& (vec (pr true true) (pr false false) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_ttfftfff, "(& (vec (pr true true) (pr false false) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_ttfftfft, "(& (vec (pr true true) (pr false false) (pr true false) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_ttfftftf, "(& (vec (pr true true) (pr false false) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_ttfftftt, "(& (vec (pr true true) (pr false false) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_ttffttff, "(& (vec (pr true true) (pr false false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {and_ttffttft, "(& (vec (pr true true) (pr false false) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {and_ttfftttf, "(& (vec (pr true true) (pr false false) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {and_ttfftttt, "(& (vec (pr true true) (pr false false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {and_ttftffff, "(& (vec (pr true true) (pr false true) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_ttftffft, "(& (vec (pr true true) (pr false true) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_ttftfftf, "(& (vec (pr true true) (pr false true) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_ttftfftt, "(& (vec (pr true true) (pr false true) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_ttftftff, "(& (vec (pr true true) (pr false true) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_ttftftft, "(& (vec (pr true true) (pr false true) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_ttftfttf, "(& (vec (pr true true) (pr false true) (pr false true) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_ttftfttt, "(& (vec (pr true true) (pr false true) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_ttfttfff, "(& (vec (pr true true) (pr false true) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_ttfttfft, "(& (vec (pr true true) (pr false true) (pr true false) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_ttfttftf, "(& (vec (pr true true) (pr false true) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_ttfttftt, "(& (vec (pr true true) (pr false true) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_ttftttff, "(& (vec (pr true true) (pr false true) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {and_ttftttft, "(& (vec (pr true true) (pr false true) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {and_ttfttttf, "(& (vec (pr true true) (pr false true) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {and_ttfttttt, "(& (vec (pr true true) (pr false true) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {and_tttfffff, "(& (vec (pr true true) (pr true false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_tttfffft, "(& (vec (pr true true) (pr true false) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_tttffftf, "(& (vec (pr true true) (pr true false) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_tttffftt, "(& (vec (pr true true) (pr true false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_tttfftff, "(& (vec (pr true true) (pr true false) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_tttfftft, "(& (vec (pr true true) (pr true false) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_tttffttf, "(& (vec (pr true true) (pr true false) (pr false true) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_tttffttt, "(& (vec (pr true true) (pr true false) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_tttftfff, "(& (vec (pr true true) (pr true false) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {and_tttftfft, "(& (vec (pr true true) (pr true false) (pr true false) (pr false true)))", "(vec true false false false)"}
rev_rule! {and_tttftftf, "(& (vec (pr true true) (pr true false) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {and_tttftftt, "(& (vec (pr true true) (pr true false) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {and_tttfttff, "(& (vec (pr true true) (pr true false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {and_tttfttft, "(& (vec (pr true true) (pr true false) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {and_tttftttf, "(& (vec (pr true true) (pr true false) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {and_tttftttt, "(& (vec (pr true true) (pr true false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {and_ttttffff, "(& (vec (pr true true) (pr true true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {and_ttttffft, "(& (vec (pr true true) (pr true true) (pr false false) (pr false true)))", "(vec true true false false)"}
rev_rule! {and_ttttfftf, "(& (vec (pr true true) (pr true true) (pr false false) (pr true false)))", "(vec true true false false)"}
rev_rule! {and_ttttfftt, "(& (vec (pr true true) (pr true true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {and_ttttftff, "(& (vec (pr true true) (pr true true) (pr false true) (pr false false)))", "(vec true true false false)"}
rev_rule! {and_ttttftft, "(& (vec (pr true true) (pr true true) (pr false true) (pr false true)))", "(vec true true false false)"}
rev_rule! {and_ttttfttf, "(& (vec (pr true true) (pr true true) (pr false true) (pr true false)))", "(vec true true false false)"}
rev_rule! {and_ttttfttt, "(& (vec (pr true true) (pr true true) (pr false true) (pr true true)))", "(vec true true false true)"}
rev_rule! {and_tttttfff, "(& (vec (pr true true) (pr true true) (pr true false) (pr false false)))", "(vec true true false false)"}
rev_rule! {and_tttttfft, "(& (vec (pr true true) (pr true true) (pr true false) (pr false true)))", "(vec true true false false)"}
rev_rule! {and_tttttftf, "(& (vec (pr true true) (pr true true) (pr true false) (pr true false)))", "(vec true true false false)"}
rev_rule! {and_tttttftt, "(& (vec (pr true true) (pr true true) (pr true false) (pr true true)))", "(vec true true false true)"}
rev_rule! {and_ttttttff, "(& (vec (pr true true) (pr true true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {and_ttttttft, "(& (vec (pr true true) (pr true true) (pr true true) (pr false true)))", "(vec true true true false)"}
rev_rule! {and_tttttttf, "(& (vec (pr true true) (pr true true) (pr true true) (pr true false)))", "(vec true true true false)"}
rev_rule! {and_tttttttt, "(& (vec (pr true true) (pr true true) (pr true true) (pr true true)))", "(vec true true true true)"}
// rev_rule! {pi1, "(pi1 (vec (pr ?x1 ?y1) (pr ?x2 ?y2) (pr ?x3 ?y3) (pr ?x4 ?y4)))", "(vec ?x1 ?x2 ?x3 ?x4)"}
// rev_rule! {pi2, "(pi2 (vec (pr ?x1 ?y1) (pr ?x2 ?y2) (pr ?x3 ?y3) (pr ?x4 ?y4)))", "(vec ?y1 ?y2 ?y3 ?y4)"}
rev_rule! {pi1_ffffffff, "(pi1 (vec (pr false false) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ffffffft, "(pi1 (vec (pr false false) (pr false false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_fffffftf, "(pi1 (vec (pr false false) (pr false false) (pr false false) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_fffffftt, "(pi1 (vec (pr false false) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_ffffftff, "(pi1 (vec (pr false false) (pr false false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ffffftft, "(pi1 (vec (pr false false) (pr false false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_fffffttf, "(pi1 (vec (pr false false) (pr false false) (pr false true) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_fffffttt, "(pi1 (vec (pr false false) (pr false false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_fffftfff, "(pi1 (vec (pr false false) (pr false false) (pr true false) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_fffftfft, "(pi1 (vec (pr false false) (pr false false) (pr true false) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_fffftftf, "(pi1 (vec (pr false false) (pr false false) (pr true false) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_fffftftt, "(pi1 (vec (pr false false) (pr false false) (pr true false) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_ffffttff, "(pi1 (vec (pr false false) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_ffffttft, "(pi1 (vec (pr false false) (pr false false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_fffftttf, "(pi1 (vec (pr false false) (pr false false) (pr true true) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_fffftttt, "(pi1 (vec (pr false false) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_ffftffff, "(pi1 (vec (pr false false) (pr false true) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ffftffft, "(pi1 (vec (pr false false) (pr false true) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_ffftfftf, "(pi1 (vec (pr false false) (pr false true) (pr false false) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_ffftfftt, "(pi1 (vec (pr false false) (pr false true) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_ffftftff, "(pi1 (vec (pr false false) (pr false true) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ffftftft, "(pi1 (vec (pr false false) (pr false true) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_ffftfttf, "(pi1 (vec (pr false false) (pr false true) (pr false true) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_ffftfttt, "(pi1 (vec (pr false false) (pr false true) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_fffttfff, "(pi1 (vec (pr false false) (pr false true) (pr true false) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_fffttfft, "(pi1 (vec (pr false false) (pr false true) (pr true false) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_fffttftf, "(pi1 (vec (pr false false) (pr false true) (pr true false) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_fffttftt, "(pi1 (vec (pr false false) (pr false true) (pr true false) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_ffftttff, "(pi1 (vec (pr false false) (pr false true) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_ffftttft, "(pi1 (vec (pr false false) (pr false true) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_fffttttf, "(pi1 (vec (pr false false) (pr false true) (pr true true) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_fffttttt, "(pi1 (vec (pr false false) (pr false true) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_fftfffff, "(pi1 (vec (pr false false) (pr true false) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_fftfffft, "(pi1 (vec (pr false false) (pr true false) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_fftffftf, "(pi1 (vec (pr false false) (pr true false) (pr false false) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_fftffftt, "(pi1 (vec (pr false false) (pr true false) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_fftfftff, "(pi1 (vec (pr false false) (pr true false) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_fftfftft, "(pi1 (vec (pr false false) (pr true false) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_fftffttf, "(pi1 (vec (pr false false) (pr true false) (pr false true) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_fftffttt, "(pi1 (vec (pr false false) (pr true false) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_fftftfff, "(pi1 (vec (pr false false) (pr true false) (pr true false) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_fftftfft, "(pi1 (vec (pr false false) (pr true false) (pr true false) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fftftftf, "(pi1 (vec (pr false false) (pr true false) (pr true false) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fftftftt, "(pi1 (vec (pr false false) (pr true false) (pr true false) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_fftfttff, "(pi1 (vec (pr false false) (pr true false) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_fftfttft, "(pi1 (vec (pr false false) (pr true false) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fftftttf, "(pi1 (vec (pr false false) (pr true false) (pr true true) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fftftttt, "(pi1 (vec (pr false false) (pr true false) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_ffttffff, "(pi1 (vec (pr false false) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_ffttffft, "(pi1 (vec (pr false false) (pr true true) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_ffttfftf, "(pi1 (vec (pr false false) (pr true true) (pr false false) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_ffttfftt, "(pi1 (vec (pr false false) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_ffttftff, "(pi1 (vec (pr false false) (pr true true) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_ffttftft, "(pi1 (vec (pr false false) (pr true true) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_ffttfttf, "(pi1 (vec (pr false false) (pr true true) (pr false true) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_ffttfttt, "(pi1 (vec (pr false false) (pr true true) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_fftttfff, "(pi1 (vec (pr false false) (pr true true) (pr true false) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_fftttfft, "(pi1 (vec (pr false false) (pr true true) (pr true false) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fftttftf, "(pi1 (vec (pr false false) (pr true true) (pr true false) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fftttftt, "(pi1 (vec (pr false false) (pr true true) (pr true false) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_ffttttff, "(pi1 (vec (pr false false) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_ffttttft, "(pi1 (vec (pr false false) (pr true true) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fftttttf, "(pi1 (vec (pr false false) (pr true true) (pr true true) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fftttttt, "(pi1 (vec (pr false false) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_ftffffff, "(pi1 (vec (pr false true) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ftffffft, "(pi1 (vec (pr false true) (pr false false) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_ftfffftf, "(pi1 (vec (pr false true) (pr false false) (pr false false) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_ftfffftt, "(pi1 (vec (pr false true) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_ftffftff, "(pi1 (vec (pr false true) (pr false false) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ftffftft, "(pi1 (vec (pr false true) (pr false false) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_ftfffttf, "(pi1 (vec (pr false true) (pr false false) (pr false true) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_ftfffttt, "(pi1 (vec (pr false true) (pr false false) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_ftfftfff, "(pi1 (vec (pr false true) (pr false false) (pr true false) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_ftfftfft, "(pi1 (vec (pr false true) (pr false false) (pr true false) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_ftfftftf, "(pi1 (vec (pr false true) (pr false false) (pr true false) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_ftfftftt, "(pi1 (vec (pr false true) (pr false false) (pr true false) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_ftffttff, "(pi1 (vec (pr false true) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_ftffttft, "(pi1 (vec (pr false true) (pr false false) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_ftfftttf, "(pi1 (vec (pr false true) (pr false false) (pr true true) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_ftfftttt, "(pi1 (vec (pr false true) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_ftftffff, "(pi1 (vec (pr false true) (pr false true) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ftftffft, "(pi1 (vec (pr false true) (pr false true) (pr false false) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_ftftfftf, "(pi1 (vec (pr false true) (pr false true) (pr false false) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_ftftfftt, "(pi1 (vec (pr false true) (pr false true) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_ftftftff, "(pi1 (vec (pr false true) (pr false true) (pr false true) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi1_ftftftft, "(pi1 (vec (pr false true) (pr false true) (pr false true) (pr false true)))", "(vec false false false false)"}
rev_rule! {pi1_ftftfttf, "(pi1 (vec (pr false true) (pr false true) (pr false true) (pr true false)))", "(vec false false false true)"}
rev_rule! {pi1_ftftfttt, "(pi1 (vec (pr false true) (pr false true) (pr false true) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi1_ftfttfff, "(pi1 (vec (pr false true) (pr false true) (pr true false) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_ftfttfft, "(pi1 (vec (pr false true) (pr false true) (pr true false) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_ftfttftf, "(pi1 (vec (pr false true) (pr false true) (pr true false) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_ftfttftt, "(pi1 (vec (pr false true) (pr false true) (pr true false) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_ftftttff, "(pi1 (vec (pr false true) (pr false true) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi1_ftftttft, "(pi1 (vec (pr false true) (pr false true) (pr true true) (pr false true)))", "(vec false false true false)"}
rev_rule! {pi1_ftfttttf, "(pi1 (vec (pr false true) (pr false true) (pr true true) (pr true false)))", "(vec false false true true)"}
rev_rule! {pi1_ftfttttt, "(pi1 (vec (pr false true) (pr false true) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi1_fttfffff, "(pi1 (vec (pr false true) (pr true false) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_fttfffft, "(pi1 (vec (pr false true) (pr true false) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_fttffftf, "(pi1 (vec (pr false true) (pr true false) (pr false false) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_fttffftt, "(pi1 (vec (pr false true) (pr true false) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_fttfftff, "(pi1 (vec (pr false true) (pr true false) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_fttfftft, "(pi1 (vec (pr false true) (pr true false) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_fttffttf, "(pi1 (vec (pr false true) (pr true false) (pr false true) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_fttffttt, "(pi1 (vec (pr false true) (pr true false) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_fttftfff, "(pi1 (vec (pr false true) (pr true false) (pr true false) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_fttftfft, "(pi1 (vec (pr false true) (pr true false) (pr true false) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fttftftf, "(pi1 (vec (pr false true) (pr true false) (pr true false) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fttftftt, "(pi1 (vec (pr false true) (pr true false) (pr true false) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_fttfttff, "(pi1 (vec (pr false true) (pr true false) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_fttfttft, "(pi1 (vec (pr false true) (pr true false) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fttftttf, "(pi1 (vec (pr false true) (pr true false) (pr true true) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fttftttt, "(pi1 (vec (pr false true) (pr true false) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_ftttffff, "(pi1 (vec (pr false true) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_ftttffft, "(pi1 (vec (pr false true) (pr true true) (pr false false) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_ftttfftf, "(pi1 (vec (pr false true) (pr true true) (pr false false) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_ftttfftt, "(pi1 (vec (pr false true) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_ftttftff, "(pi1 (vec (pr false true) (pr true true) (pr false true) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi1_ftttftft, "(pi1 (vec (pr false true) (pr true true) (pr false true) (pr false true)))", "(vec false true false false)"}
rev_rule! {pi1_ftttfttf, "(pi1 (vec (pr false true) (pr true true) (pr false true) (pr true false)))", "(vec false true false true)"}
rev_rule! {pi1_ftttfttt, "(pi1 (vec (pr false true) (pr true true) (pr false true) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi1_fttttfff, "(pi1 (vec (pr false true) (pr true true) (pr true false) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_fttttfft, "(pi1 (vec (pr false true) (pr true true) (pr true false) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fttttftf, "(pi1 (vec (pr false true) (pr true true) (pr true false) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fttttftt, "(pi1 (vec (pr false true) (pr true true) (pr true false) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_ftttttff, "(pi1 (vec (pr false true) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi1_ftttttft, "(pi1 (vec (pr false true) (pr true true) (pr true true) (pr false true)))", "(vec false true true false)"}
rev_rule! {pi1_fttttttf, "(pi1 (vec (pr false true) (pr true true) (pr true true) (pr true false)))", "(vec false true true true)"}
rev_rule! {pi1_fttttttt, "(pi1 (vec (pr false true) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi1_tfffffff, "(pi1 (vec (pr true false) (pr false false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_tfffffft, "(pi1 (vec (pr true false) (pr false false) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_tffffftf, "(pi1 (vec (pr true false) (pr false false) (pr false false) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_tffffftt, "(pi1 (vec (pr true false) (pr false false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_tfffftff, "(pi1 (vec (pr true false) (pr false false) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_tfffftft, "(pi1 (vec (pr true false) (pr false false) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_tffffttf, "(pi1 (vec (pr true false) (pr false false) (pr false true) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_tffffttt, "(pi1 (vec (pr true false) (pr false false) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_tffftfff, "(pi1 (vec (pr true false) (pr false false) (pr true false) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_tffftfft, "(pi1 (vec (pr true false) (pr false false) (pr true false) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_tffftftf, "(pi1 (vec (pr true false) (pr false false) (pr true false) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_tffftftt, "(pi1 (vec (pr true false) (pr false false) (pr true false) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_tfffttff, "(pi1 (vec (pr true false) (pr false false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_tfffttft, "(pi1 (vec (pr true false) (pr false false) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_tffftttf, "(pi1 (vec (pr true false) (pr false false) (pr true true) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_tffftttt, "(pi1 (vec (pr true false) (pr false false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_tfftffff, "(pi1 (vec (pr true false) (pr false true) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_tfftffft, "(pi1 (vec (pr true false) (pr false true) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_tfftfftf, "(pi1 (vec (pr true false) (pr false true) (pr false false) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_tfftfftt, "(pi1 (vec (pr true false) (pr false true) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_tfftftff, "(pi1 (vec (pr true false) (pr false true) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_tfftftft, "(pi1 (vec (pr true false) (pr false true) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_tfftfttf, "(pi1 (vec (pr true false) (pr false true) (pr false true) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_tfftfttt, "(pi1 (vec (pr true false) (pr false true) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_tffttfff, "(pi1 (vec (pr true false) (pr false true) (pr true false) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_tffttfft, "(pi1 (vec (pr true false) (pr false true) (pr true false) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_tffttftf, "(pi1 (vec (pr true false) (pr false true) (pr true false) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_tffttftt, "(pi1 (vec (pr true false) (pr false true) (pr true false) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_tfftttff, "(pi1 (vec (pr true false) (pr false true) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_tfftttft, "(pi1 (vec (pr true false) (pr false true) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_tffttttf, "(pi1 (vec (pr true false) (pr false true) (pr true true) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_tffttttt, "(pi1 (vec (pr true false) (pr false true) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_tftfffff, "(pi1 (vec (pr true false) (pr true false) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_tftfffft, "(pi1 (vec (pr true false) (pr true false) (pr false false) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_tftffftf, "(pi1 (vec (pr true false) (pr true false) (pr false false) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_tftffftt, "(pi1 (vec (pr true false) (pr true false) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tftfftff, "(pi1 (vec (pr true false) (pr true false) (pr false true) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_tftfftft, "(pi1 (vec (pr true false) (pr true false) (pr false true) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_tftffttf, "(pi1 (vec (pr true false) (pr true false) (pr false true) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_tftffttt, "(pi1 (vec (pr true false) (pr true false) (pr false true) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tftftfff, "(pi1 (vec (pr true false) (pr true false) (pr true false) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tftftfft, "(pi1 (vec (pr true false) (pr true false) (pr true false) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tftftftf, "(pi1 (vec (pr true false) (pr true false) (pr true false) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tftftftt, "(pi1 (vec (pr true false) (pr true false) (pr true false) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_tftfttff, "(pi1 (vec (pr true false) (pr true false) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tftfttft, "(pi1 (vec (pr true false) (pr true false) (pr true true) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tftftttf, "(pi1 (vec (pr true false) (pr true false) (pr true true) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tftftttt, "(pi1 (vec (pr true false) (pr true false) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_tfttffff, "(pi1 (vec (pr true false) (pr true true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_tfttffft, "(pi1 (vec (pr true false) (pr true true) (pr false false) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_tfttfftf, "(pi1 (vec (pr true false) (pr true true) (pr false false) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_tfttfftt, "(pi1 (vec (pr true false) (pr true true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tfttftff, "(pi1 (vec (pr true false) (pr true true) (pr false true) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_tfttftft, "(pi1 (vec (pr true false) (pr true true) (pr false true) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_tfttfttf, "(pi1 (vec (pr true false) (pr true true) (pr false true) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_tfttfttt, "(pi1 (vec (pr true false) (pr true true) (pr false true) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tftttfff, "(pi1 (vec (pr true false) (pr true true) (pr true false) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tftttfft, "(pi1 (vec (pr true false) (pr true true) (pr true false) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tftttftf, "(pi1 (vec (pr true false) (pr true true) (pr true false) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tftttftt, "(pi1 (vec (pr true false) (pr true true) (pr true false) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_tfttttff, "(pi1 (vec (pr true false) (pr true true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tfttttft, "(pi1 (vec (pr true false) (pr true true) (pr true true) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tftttttf, "(pi1 (vec (pr true false) (pr true true) (pr true true) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tftttttt, "(pi1 (vec (pr true false) (pr true true) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_ttffffff, "(pi1 (vec (pr true true) (pr false false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_ttffffft, "(pi1 (vec (pr true true) (pr false false) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_ttfffftf, "(pi1 (vec (pr true true) (pr false false) (pr false false) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_ttfffftt, "(pi1 (vec (pr true true) (pr false false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_ttffftff, "(pi1 (vec (pr true true) (pr false false) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_ttffftft, "(pi1 (vec (pr true true) (pr false false) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_ttfffttf, "(pi1 (vec (pr true true) (pr false false) (pr false true) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_ttfffttt, "(pi1 (vec (pr true true) (pr false false) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_ttfftfff, "(pi1 (vec (pr true true) (pr false false) (pr true false) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_ttfftfft, "(pi1 (vec (pr true true) (pr false false) (pr true false) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_ttfftftf, "(pi1 (vec (pr true true) (pr false false) (pr true false) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_ttfftftt, "(pi1 (vec (pr true true) (pr false false) (pr true false) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_ttffttff, "(pi1 (vec (pr true true) (pr false false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_ttffttft, "(pi1 (vec (pr true true) (pr false false) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_ttfftttf, "(pi1 (vec (pr true true) (pr false false) (pr true true) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_ttfftttt, "(pi1 (vec (pr true true) (pr false false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_ttftffff, "(pi1 (vec (pr true true) (pr false true) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_ttftffft, "(pi1 (vec (pr true true) (pr false true) (pr false false) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_ttftfftf, "(pi1 (vec (pr true true) (pr false true) (pr false false) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_ttftfftt, "(pi1 (vec (pr true true) (pr false true) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_ttftftff, "(pi1 (vec (pr true true) (pr false true) (pr false true) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi1_ttftftft, "(pi1 (vec (pr true true) (pr false true) (pr false true) (pr false true)))", "(vec true false false false)"}
rev_rule! {pi1_ttftfttf, "(pi1 (vec (pr true true) (pr false true) (pr false true) (pr true false)))", "(vec true false false true)"}
rev_rule! {pi1_ttftfttt, "(pi1 (vec (pr true true) (pr false true) (pr false true) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi1_ttfttfff, "(pi1 (vec (pr true true) (pr false true) (pr true false) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_ttfttfft, "(pi1 (vec (pr true true) (pr false true) (pr true false) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_ttfttftf, "(pi1 (vec (pr true true) (pr false true) (pr true false) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_ttfttftt, "(pi1 (vec (pr true true) (pr false true) (pr true false) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_ttftttff, "(pi1 (vec (pr true true) (pr false true) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi1_ttftttft, "(pi1 (vec (pr true true) (pr false true) (pr true true) (pr false true)))", "(vec true false true false)"}
rev_rule! {pi1_ttfttttf, "(pi1 (vec (pr true true) (pr false true) (pr true true) (pr true false)))", "(vec true false true true)"}
rev_rule! {pi1_ttfttttt, "(pi1 (vec (pr true true) (pr false true) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi1_tttfffff, "(pi1 (vec (pr true true) (pr true false) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_tttfffft, "(pi1 (vec (pr true true) (pr true false) (pr false false) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_tttffftf, "(pi1 (vec (pr true true) (pr true false) (pr false false) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_tttffftt, "(pi1 (vec (pr true true) (pr true false) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tttfftff, "(pi1 (vec (pr true true) (pr true false) (pr false true) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_tttfftft, "(pi1 (vec (pr true true) (pr true false) (pr false true) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_tttffttf, "(pi1 (vec (pr true true) (pr true false) (pr false true) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_tttffttt, "(pi1 (vec (pr true true) (pr true false) (pr false true) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tttftfff, "(pi1 (vec (pr true true) (pr true false) (pr true false) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tttftfft, "(pi1 (vec (pr true true) (pr true false) (pr true false) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tttftftf, "(pi1 (vec (pr true true) (pr true false) (pr true false) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tttftftt, "(pi1 (vec (pr true true) (pr true false) (pr true false) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_tttfttff, "(pi1 (vec (pr true true) (pr true false) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tttfttft, "(pi1 (vec (pr true true) (pr true false) (pr true true) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tttftttf, "(pi1 (vec (pr true true) (pr true false) (pr true true) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tttftttt, "(pi1 (vec (pr true true) (pr true false) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_ttttffff, "(pi1 (vec (pr true true) (pr true true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_ttttffft, "(pi1 (vec (pr true true) (pr true true) (pr false false) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_ttttfftf, "(pi1 (vec (pr true true) (pr true true) (pr false false) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_ttttfftt, "(pi1 (vec (pr true true) (pr true true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_ttttftff, "(pi1 (vec (pr true true) (pr true true) (pr false true) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi1_ttttftft, "(pi1 (vec (pr true true) (pr true true) (pr false true) (pr false true)))", "(vec true true false false)"}
rev_rule! {pi1_ttttfttf, "(pi1 (vec (pr true true) (pr true true) (pr false true) (pr true false)))", "(vec true true false true)"}
rev_rule! {pi1_ttttfttt, "(pi1 (vec (pr true true) (pr true true) (pr false true) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi1_tttttfff, "(pi1 (vec (pr true true) (pr true true) (pr true false) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_tttttfft, "(pi1 (vec (pr true true) (pr true true) (pr true false) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tttttftf, "(pi1 (vec (pr true true) (pr true true) (pr true false) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tttttftt, "(pi1 (vec (pr true true) (pr true true) (pr true false) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi1_ttttttff, "(pi1 (vec (pr true true) (pr true true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi1_ttttttft, "(pi1 (vec (pr true true) (pr true true) (pr true true) (pr false true)))", "(vec true true true false)"}
rev_rule! {pi1_tttttttf, "(pi1 (vec (pr true true) (pr true true) (pr true true) (pr true false)))", "(vec true true true true)"}
rev_rule! {pi1_tttttttt, "(pi1 (vec (pr true true) (pr true true) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_ffffffff, "(pi2 (vec (pr false false) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_ffffffft, "(pi2 (vec (pr false false) (pr false false) (pr false false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_fffffftf, "(pi2 (vec (pr false false) (pr false false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_fffffftt, "(pi2 (vec (pr false false) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_ffffftff, "(pi2 (vec (pr false false) (pr false false) (pr false true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_ffffftft, "(pi2 (vec (pr false false) (pr false false) (pr false true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_fffffttf, "(pi2 (vec (pr false false) (pr false false) (pr false true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_fffffttt, "(pi2 (vec (pr false false) (pr false false) (pr false true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_fffftfff, "(pi2 (vec (pr false false) (pr false false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_fffftfft, "(pi2 (vec (pr false false) (pr false false) (pr true false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_fffftftf, "(pi2 (vec (pr false false) (pr false false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_fffftftt, "(pi2 (vec (pr false false) (pr false false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_ffffttff, "(pi2 (vec (pr false false) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_ffffttft, "(pi2 (vec (pr false false) (pr false false) (pr true true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_fffftttf, "(pi2 (vec (pr false false) (pr false false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_fffftttt, "(pi2 (vec (pr false false) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_ffftffff, "(pi2 (vec (pr false false) (pr false true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_ffftffft, "(pi2 (vec (pr false false) (pr false true) (pr false false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_ffftfftf, "(pi2 (vec (pr false false) (pr false true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_ffftfftt, "(pi2 (vec (pr false false) (pr false true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_ffftftff, "(pi2 (vec (pr false false) (pr false true) (pr false true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_ffftftft, "(pi2 (vec (pr false false) (pr false true) (pr false true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_ffftfttf, "(pi2 (vec (pr false false) (pr false true) (pr false true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_ffftfttt, "(pi2 (vec (pr false false) (pr false true) (pr false true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_fffttfff, "(pi2 (vec (pr false false) (pr false true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_fffttfft, "(pi2 (vec (pr false false) (pr false true) (pr true false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_fffttftf, "(pi2 (vec (pr false false) (pr false true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_fffttftt, "(pi2 (vec (pr false false) (pr false true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_ffftttff, "(pi2 (vec (pr false false) (pr false true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_ffftttft, "(pi2 (vec (pr false false) (pr false true) (pr true true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_fffttttf, "(pi2 (vec (pr false false) (pr false true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_fffttttt, "(pi2 (vec (pr false false) (pr false true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_fftfffff, "(pi2 (vec (pr false false) (pr true false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_fftfffft, "(pi2 (vec (pr false false) (pr true false) (pr false false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_fftffftf, "(pi2 (vec (pr false false) (pr true false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_fftffftt, "(pi2 (vec (pr false false) (pr true false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_fftfftff, "(pi2 (vec (pr false false) (pr true false) (pr false true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_fftfftft, "(pi2 (vec (pr false false) (pr true false) (pr false true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_fftffttf, "(pi2 (vec (pr false false) (pr true false) (pr false true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_fftffttt, "(pi2 (vec (pr false false) (pr true false) (pr false true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_fftftfff, "(pi2 (vec (pr false false) (pr true false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_fftftfft, "(pi2 (vec (pr false false) (pr true false) (pr true false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_fftftftf, "(pi2 (vec (pr false false) (pr true false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_fftftftt, "(pi2 (vec (pr false false) (pr true false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_fftfttff, "(pi2 (vec (pr false false) (pr true false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_fftfttft, "(pi2 (vec (pr false false) (pr true false) (pr true true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_fftftttf, "(pi2 (vec (pr false false) (pr true false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_fftftttt, "(pi2 (vec (pr false false) (pr true false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_ffttffff, "(pi2 (vec (pr false false) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_ffttffft, "(pi2 (vec (pr false false) (pr true true) (pr false false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_ffttfftf, "(pi2 (vec (pr false false) (pr true true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_ffttfftt, "(pi2 (vec (pr false false) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_ffttftff, "(pi2 (vec (pr false false) (pr true true) (pr false true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_ffttftft, "(pi2 (vec (pr false false) (pr true true) (pr false true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_ffttfttf, "(pi2 (vec (pr false false) (pr true true) (pr false true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_ffttfttt, "(pi2 (vec (pr false false) (pr true true) (pr false true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_fftttfff, "(pi2 (vec (pr false false) (pr true true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_fftttfft, "(pi2 (vec (pr false false) (pr true true) (pr true false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_fftttftf, "(pi2 (vec (pr false false) (pr true true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_fftttftt, "(pi2 (vec (pr false false) (pr true true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_ffttttff, "(pi2 (vec (pr false false) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_ffttttft, "(pi2 (vec (pr false false) (pr true true) (pr true true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_fftttttf, "(pi2 (vec (pr false false) (pr true true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_fftttttt, "(pi2 (vec (pr false false) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_ftffffff, "(pi2 (vec (pr false true) (pr false false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_ftffffft, "(pi2 (vec (pr false true) (pr false false) (pr false false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_ftfffftf, "(pi2 (vec (pr false true) (pr false false) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_ftfffftt, "(pi2 (vec (pr false true) (pr false false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_ftffftff, "(pi2 (vec (pr false true) (pr false false) (pr false true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_ftffftft, "(pi2 (vec (pr false true) (pr false false) (pr false true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_ftfffttf, "(pi2 (vec (pr false true) (pr false false) (pr false true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_ftfffttt, "(pi2 (vec (pr false true) (pr false false) (pr false true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_ftfftfff, "(pi2 (vec (pr false true) (pr false false) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_ftfftfft, "(pi2 (vec (pr false true) (pr false false) (pr true false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_ftfftftf, "(pi2 (vec (pr false true) (pr false false) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_ftfftftt, "(pi2 (vec (pr false true) (pr false false) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_ftffttff, "(pi2 (vec (pr false true) (pr false false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_ftffttft, "(pi2 (vec (pr false true) (pr false false) (pr true true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_ftfftttf, "(pi2 (vec (pr false true) (pr false false) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_ftfftttt, "(pi2 (vec (pr false true) (pr false false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_ftftffff, "(pi2 (vec (pr false true) (pr false true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_ftftffft, "(pi2 (vec (pr false true) (pr false true) (pr false false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_ftftfftf, "(pi2 (vec (pr false true) (pr false true) (pr false false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_ftftfftt, "(pi2 (vec (pr false true) (pr false true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ftftftff, "(pi2 (vec (pr false true) (pr false true) (pr false true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ftftftft, "(pi2 (vec (pr false true) (pr false true) (pr false true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_ftftfttf, "(pi2 (vec (pr false true) (pr false true) (pr false true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_ftftfttt, "(pi2 (vec (pr false true) (pr false true) (pr false true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_ftfttfff, "(pi2 (vec (pr false true) (pr false true) (pr true false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_ftfttfft, "(pi2 (vec (pr false true) (pr false true) (pr true false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_ftfttftf, "(pi2 (vec (pr false true) (pr false true) (pr true false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_ftfttftt, "(pi2 (vec (pr false true) (pr false true) (pr true false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ftftttff, "(pi2 (vec (pr false true) (pr false true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ftftttft, "(pi2 (vec (pr false true) (pr false true) (pr true true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_ftfttttf, "(pi2 (vec (pr false true) (pr false true) (pr true true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_ftfttttt, "(pi2 (vec (pr false true) (pr false true) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_fttfffff, "(pi2 (vec (pr false true) (pr true false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_fttfffft, "(pi2 (vec (pr false true) (pr true false) (pr false false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_fttffftf, "(pi2 (vec (pr false true) (pr true false) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_fttffftt, "(pi2 (vec (pr false true) (pr true false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_fttfftff, "(pi2 (vec (pr false true) (pr true false) (pr false true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_fttfftft, "(pi2 (vec (pr false true) (pr true false) (pr false true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_fttffttf, "(pi2 (vec (pr false true) (pr true false) (pr false true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_fttffttt, "(pi2 (vec (pr false true) (pr true false) (pr false true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_fttftfff, "(pi2 (vec (pr false true) (pr true false) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_fttftfft, "(pi2 (vec (pr false true) (pr true false) (pr true false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_fttftftf, "(pi2 (vec (pr false true) (pr true false) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_fttftftt, "(pi2 (vec (pr false true) (pr true false) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_fttfttff, "(pi2 (vec (pr false true) (pr true false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_fttfttft, "(pi2 (vec (pr false true) (pr true false) (pr true true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_fttftttf, "(pi2 (vec (pr false true) (pr true false) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_fttftttt, "(pi2 (vec (pr false true) (pr true false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_ftttffff, "(pi2 (vec (pr false true) (pr true true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_ftttffft, "(pi2 (vec (pr false true) (pr true true) (pr false false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_ftttfftf, "(pi2 (vec (pr false true) (pr true true) (pr false false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_ftttfftt, "(pi2 (vec (pr false true) (pr true true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ftttftff, "(pi2 (vec (pr false true) (pr true true) (pr false true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ftttftft, "(pi2 (vec (pr false true) (pr true true) (pr false true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_ftttfttf, "(pi2 (vec (pr false true) (pr true true) (pr false true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_ftttfttt, "(pi2 (vec (pr false true) (pr true true) (pr false true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_fttttfff, "(pi2 (vec (pr false true) (pr true true) (pr true false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_fttttfft, "(pi2 (vec (pr false true) (pr true true) (pr true false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_fttttftf, "(pi2 (vec (pr false true) (pr true true) (pr true false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_fttttftt, "(pi2 (vec (pr false true) (pr true true) (pr true false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ftttttff, "(pi2 (vec (pr false true) (pr true true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ftttttft, "(pi2 (vec (pr false true) (pr true true) (pr true true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_fttttttf, "(pi2 (vec (pr false true) (pr true true) (pr true true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_fttttttt, "(pi2 (vec (pr false true) (pr true true) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_tfffffff, "(pi2 (vec (pr true false) (pr false false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_tfffffft, "(pi2 (vec (pr true false) (pr false false) (pr false false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_tffffftf, "(pi2 (vec (pr true false) (pr false false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_tffffftt, "(pi2 (vec (pr true false) (pr false false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_tfffftff, "(pi2 (vec (pr true false) (pr false false) (pr false true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_tfffftft, "(pi2 (vec (pr true false) (pr false false) (pr false true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_tffffttf, "(pi2 (vec (pr true false) (pr false false) (pr false true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_tffffttt, "(pi2 (vec (pr true false) (pr false false) (pr false true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_tffftfff, "(pi2 (vec (pr true false) (pr false false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_tffftfft, "(pi2 (vec (pr true false) (pr false false) (pr true false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_tffftftf, "(pi2 (vec (pr true false) (pr false false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_tffftftt, "(pi2 (vec (pr true false) (pr false false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_tfffttff, "(pi2 (vec (pr true false) (pr false false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_tfffttft, "(pi2 (vec (pr true false) (pr false false) (pr true true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_tffftttf, "(pi2 (vec (pr true false) (pr false false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_tffftttt, "(pi2 (vec (pr true false) (pr false false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_tfftffff, "(pi2 (vec (pr true false) (pr false true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_tfftffft, "(pi2 (vec (pr true false) (pr false true) (pr false false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_tfftfftf, "(pi2 (vec (pr true false) (pr false true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_tfftfftt, "(pi2 (vec (pr true false) (pr false true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_tfftftff, "(pi2 (vec (pr true false) (pr false true) (pr false true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_tfftftft, "(pi2 (vec (pr true false) (pr false true) (pr false true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_tfftfttf, "(pi2 (vec (pr true false) (pr false true) (pr false true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_tfftfttt, "(pi2 (vec (pr true false) (pr false true) (pr false true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_tffttfff, "(pi2 (vec (pr true false) (pr false true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_tffttfft, "(pi2 (vec (pr true false) (pr false true) (pr true false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_tffttftf, "(pi2 (vec (pr true false) (pr false true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_tffttftt, "(pi2 (vec (pr true false) (pr false true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_tfftttff, "(pi2 (vec (pr true false) (pr false true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_tfftttft, "(pi2 (vec (pr true false) (pr false true) (pr true true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_tffttttf, "(pi2 (vec (pr true false) (pr false true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_tffttttt, "(pi2 (vec (pr true false) (pr false true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_tftfffff, "(pi2 (vec (pr true false) (pr true false) (pr false false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_tftfffft, "(pi2 (vec (pr true false) (pr true false) (pr false false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_tftffftf, "(pi2 (vec (pr true false) (pr true false) (pr false false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_tftffftt, "(pi2 (vec (pr true false) (pr true false) (pr false false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_tftfftff, "(pi2 (vec (pr true false) (pr true false) (pr false true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_tftfftft, "(pi2 (vec (pr true false) (pr true false) (pr false true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_tftffttf, "(pi2 (vec (pr true false) (pr true false) (pr false true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_tftffttt, "(pi2 (vec (pr true false) (pr true false) (pr false true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_tftftfff, "(pi2 (vec (pr true false) (pr true false) (pr true false) (pr false false)))", "(vec false false false false)"}
rev_rule! {pi2_tftftfft, "(pi2 (vec (pr true false) (pr true false) (pr true false) (pr false true)))", "(vec false false false true)"}
rev_rule! {pi2_tftftftf, "(pi2 (vec (pr true false) (pr true false) (pr true false) (pr true false)))", "(vec false false false false)"}
rev_rule! {pi2_tftftftt, "(pi2 (vec (pr true false) (pr true false) (pr true false) (pr true true)))", "(vec false false false true)"}
rev_rule! {pi2_tftfttff, "(pi2 (vec (pr true false) (pr true false) (pr true true) (pr false false)))", "(vec false false true false)"}
rev_rule! {pi2_tftfttft, "(pi2 (vec (pr true false) (pr true false) (pr true true) (pr false true)))", "(vec false false true true)"}
rev_rule! {pi2_tftftttf, "(pi2 (vec (pr true false) (pr true false) (pr true true) (pr true false)))", "(vec false false true false)"}
rev_rule! {pi2_tftftttt, "(pi2 (vec (pr true false) (pr true false) (pr true true) (pr true true)))", "(vec false false true true)"}
rev_rule! {pi2_tfttffff, "(pi2 (vec (pr true false) (pr true true) (pr false false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_tfttffft, "(pi2 (vec (pr true false) (pr true true) (pr false false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_tfttfftf, "(pi2 (vec (pr true false) (pr true true) (pr false false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_tfttfftt, "(pi2 (vec (pr true false) (pr true true) (pr false false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_tfttftff, "(pi2 (vec (pr true false) (pr true true) (pr false true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_tfttftft, "(pi2 (vec (pr true false) (pr true true) (pr false true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_tfttfttf, "(pi2 (vec (pr true false) (pr true true) (pr false true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_tfttfttt, "(pi2 (vec (pr true false) (pr true true) (pr false true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_tftttfff, "(pi2 (vec (pr true false) (pr true true) (pr true false) (pr false false)))", "(vec false true false false)"}
rev_rule! {pi2_tftttfft, "(pi2 (vec (pr true false) (pr true true) (pr true false) (pr false true)))", "(vec false true false true)"}
rev_rule! {pi2_tftttftf, "(pi2 (vec (pr true false) (pr true true) (pr true false) (pr true false)))", "(vec false true false false)"}
rev_rule! {pi2_tftttftt, "(pi2 (vec (pr true false) (pr true true) (pr true false) (pr true true)))", "(vec false true false true)"}
rev_rule! {pi2_tfttttff, "(pi2 (vec (pr true false) (pr true true) (pr true true) (pr false false)))", "(vec false true true false)"}
rev_rule! {pi2_tfttttft, "(pi2 (vec (pr true false) (pr true true) (pr true true) (pr false true)))", "(vec false true true true)"}
rev_rule! {pi2_tftttttf, "(pi2 (vec (pr true false) (pr true true) (pr true true) (pr true false)))", "(vec false true true false)"}
rev_rule! {pi2_tftttttt, "(pi2 (vec (pr true false) (pr true true) (pr true true) (pr true true)))", "(vec false true true true)"}
rev_rule! {pi2_ttffffff, "(pi2 (vec (pr true true) (pr false false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_ttffffft, "(pi2 (vec (pr true true) (pr false false) (pr false false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_ttfffftf, "(pi2 (vec (pr true true) (pr false false) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_ttfffftt, "(pi2 (vec (pr true true) (pr false false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_ttffftff, "(pi2 (vec (pr true true) (pr false false) (pr false true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_ttffftft, "(pi2 (vec (pr true true) (pr false false) (pr false true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_ttfffttf, "(pi2 (vec (pr true true) (pr false false) (pr false true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_ttfffttt, "(pi2 (vec (pr true true) (pr false false) (pr false true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_ttfftfff, "(pi2 (vec (pr true true) (pr false false) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_ttfftfft, "(pi2 (vec (pr true true) (pr false false) (pr true false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_ttfftftf, "(pi2 (vec (pr true true) (pr false false) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_ttfftftt, "(pi2 (vec (pr true true) (pr false false) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_ttffttff, "(pi2 (vec (pr true true) (pr false false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_ttffttft, "(pi2 (vec (pr true true) (pr false false) (pr true true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_ttfftttf, "(pi2 (vec (pr true true) (pr false false) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_ttfftttt, "(pi2 (vec (pr true true) (pr false false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_ttftffff, "(pi2 (vec (pr true true) (pr false true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_ttftffft, "(pi2 (vec (pr true true) (pr false true) (pr false false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_ttftfftf, "(pi2 (vec (pr true true) (pr false true) (pr false false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_ttftfftt, "(pi2 (vec (pr true true) (pr false true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ttftftff, "(pi2 (vec (pr true true) (pr false true) (pr false true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ttftftft, "(pi2 (vec (pr true true) (pr false true) (pr false true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_ttftfttf, "(pi2 (vec (pr true true) (pr false true) (pr false true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_ttftfttt, "(pi2 (vec (pr true true) (pr false true) (pr false true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_ttfttfff, "(pi2 (vec (pr true true) (pr false true) (pr true false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_ttfttfft, "(pi2 (vec (pr true true) (pr false true) (pr true false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_ttfttftf, "(pi2 (vec (pr true true) (pr false true) (pr true false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_ttfttftt, "(pi2 (vec (pr true true) (pr false true) (pr true false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ttftttff, "(pi2 (vec (pr true true) (pr false true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ttftttft, "(pi2 (vec (pr true true) (pr false true) (pr true true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_ttfttttf, "(pi2 (vec (pr true true) (pr false true) (pr true true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_ttfttttt, "(pi2 (vec (pr true true) (pr false true) (pr true true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_tttfffff, "(pi2 (vec (pr true true) (pr true false) (pr false false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_tttfffft, "(pi2 (vec (pr true true) (pr true false) (pr false false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_tttffftf, "(pi2 (vec (pr true true) (pr true false) (pr false false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_tttffftt, "(pi2 (vec (pr true true) (pr true false) (pr false false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_tttfftff, "(pi2 (vec (pr true true) (pr true false) (pr false true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_tttfftft, "(pi2 (vec (pr true true) (pr true false) (pr false true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_tttffttf, "(pi2 (vec (pr true true) (pr true false) (pr false true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_tttffttt, "(pi2 (vec (pr true true) (pr true false) (pr false true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_tttftfff, "(pi2 (vec (pr true true) (pr true false) (pr true false) (pr false false)))", "(vec true false false false)"}
rev_rule! {pi2_tttftfft, "(pi2 (vec (pr true true) (pr true false) (pr true false) (pr false true)))", "(vec true false false true)"}
rev_rule! {pi2_tttftftf, "(pi2 (vec (pr true true) (pr true false) (pr true false) (pr true false)))", "(vec true false false false)"}
rev_rule! {pi2_tttftftt, "(pi2 (vec (pr true true) (pr true false) (pr true false) (pr true true)))", "(vec true false false true)"}
rev_rule! {pi2_tttfttff, "(pi2 (vec (pr true true) (pr true false) (pr true true) (pr false false)))", "(vec true false true false)"}
rev_rule! {pi2_tttfttft, "(pi2 (vec (pr true true) (pr true false) (pr true true) (pr false true)))", "(vec true false true true)"}
rev_rule! {pi2_tttftttf, "(pi2 (vec (pr true true) (pr true false) (pr true true) (pr true false)))", "(vec true false true false)"}
rev_rule! {pi2_tttftttt, "(pi2 (vec (pr true true) (pr true false) (pr true true) (pr true true)))", "(vec true false true true)"}
rev_rule! {pi2_ttttffff, "(pi2 (vec (pr true true) (pr true true) (pr false false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_ttttffft, "(pi2 (vec (pr true true) (pr true true) (pr false false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_ttttfftf, "(pi2 (vec (pr true true) (pr true true) (pr false false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_ttttfftt, "(pi2 (vec (pr true true) (pr true true) (pr false false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ttttftff, "(pi2 (vec (pr true true) (pr true true) (pr false true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ttttftft, "(pi2 (vec (pr true true) (pr true true) (pr false true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_ttttfttf, "(pi2 (vec (pr true true) (pr true true) (pr false true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_ttttfttt, "(pi2 (vec (pr true true) (pr true true) (pr false true) (pr true true)))", "(vec true true true true)"}
rev_rule! {pi2_tttttfff, "(pi2 (vec (pr true true) (pr true true) (pr true false) (pr false false)))", "(vec true true false false)"}
rev_rule! {pi2_tttttfft, "(pi2 (vec (pr true true) (pr true true) (pr true false) (pr false true)))", "(vec true true false true)"}
rev_rule! {pi2_tttttftf, "(pi2 (vec (pr true true) (pr true true) (pr true false) (pr true false)))", "(vec true true false false)"}
rev_rule! {pi2_tttttftt, "(pi2 (vec (pr true true) (pr true true) (pr true false) (pr true true)))", "(vec true true false true)"}
rev_rule! {pi2_ttttttff, "(pi2 (vec (pr true true) (pr true true) (pr true true) (pr false false)))", "(vec true true true false)"}
rev_rule! {pi2_ttttttft, "(pi2 (vec (pr true true) (pr true true) (pr true true) (pr false true)))", "(vec true true true true)"}
rev_rule! {pi2_tttttttf, "(pi2 (vec (pr true true) (pr true true) (pr true true) (pr true false)))", "(vec true true true false)"}
rev_rule! {pi2_tttttttt, "(pi2 (vec (pr true true) (pr true true) (pr true true) (pr true true)))", "(vec true true true true)"}
rule! {input, "(vec (pr false false) (pr false true) (pr true false) (pr true true))", "x"}
// (vec false true true false)
fn prove_something(name: &str, start: &str, rewrites: &[Rewrite], goals: &[&str]) {
let _ = env_logger::builder().is_test(true).try_init();
println!("Proving {}", name);
let start_expr: RecExpr<_> = start.parse().unwrap();
let goal_exprs: Vec<RecExpr<_>> = goals.iter().map(|g| g.parse().unwrap()).collect();
let runner = Runner::default()
.with_iter_limit(20)
.with_node_limit(5_000)
.with_expr(&start_expr)
.run(rewrites);
let (egraph, root) = (runner.egraph, runner.roots[0]);
egraph.dot().to_dot("target/getcell.dot").unwrap();
let mut extractor = Extractor::new(&egraph, CostFn);
let (best_cost, best) = extractor.find_best(root);
println!("best cost {}", best_cost);
println!("best {}", best);
for (i, (goal_expr, goal_str)) in goal_exprs.iter().zip(goals).enumerate() {
println!("Trying to prove goal {}: {}", i, goal_str);
let equivs = egraph.equivs(&start_expr, &goal_expr);
if equivs.is_empty() {
panic!("Couldn't prove goal {}: {}", i, goal_str);
}
}
}
#[test]
fn prove_simple() {
let _ = env_logger::builder().is_test(true).try_init();
let rules = &[
not_ffff(),
not_ffft(),
not_fftf(),
not_fftt(),
not_ftff(),
not_ftft(),
not_fttf(),
not_fttt(),
not_tfff(),
not_tfft(),
not_tftf(),
not_tftt(),
not_ttff(),
not_ttft(),
not_tttf(),
not_tttt(),
and_ffffffff(),
and_ffffffft(),
and_fffffftf(),
and_fffffftt(),
and_ffffftff(),
and_ffffftft(),
and_fffffttf(),
and_fffffttt(),
and_fffftfff(),
and_fffftfft(),
and_fffftftf(),
and_fffftftt(),
and_ffffttff(),
and_ffffttft(),
and_fffftttf(),
and_fffftttt(),
and_ffftffff(),
and_ffftffft(),
and_ffftfftf(),
and_ffftfftt(),
and_ffftftff(),
and_ffftftft(),
and_ffftfttf(),
and_ffftfttt(),
and_fffttfff(),
and_fffttfft(),
and_fffttftf(),
and_fffttftt(),
and_ffftttff(),
and_ffftttft(),
and_fffttttf(),
and_fffttttt(),
and_fftfffff(),
and_fftfffft(),
and_fftffftf(),
and_fftffftt(),
and_fftfftff(),
and_fftfftft(),
and_fftffttf(),
and_fftffttt(),
and_fftftfff(),
and_fftftfft(),
and_fftftftf(),
and_fftftftt(),
and_fftfttff(),
and_fftfttft(),
and_fftftttf(),
and_fftftttt(),
and_ffttffff(),
and_ffttffft(),
and_ffttfftf(),
and_ffttfftt(),
and_ffttftff(),
and_ffttftft(),
and_ffttfttf(),
and_ffttfttt(),
and_fftttfff(),
and_fftttfft(),
and_fftttftf(),
and_fftttftt(),
and_ffttttff(),
and_ffttttft(),
and_fftttttf(),
and_fftttttt(),
and_ftffffff(),
and_ftffffft(),
and_ftfffftf(),
and_ftfffftt(),
and_ftffftff(),
and_ftffftft(),
and_ftfffttf(),
and_ftfffttt(),
and_ftfftfff(),
and_ftfftfft(),
and_ftfftftf(),
and_ftfftftt(),
and_ftffttff(),
and_ftffttft(),
and_ftfftttf(),
and_ftfftttt(),
and_ftftffff(),
and_ftftffft(),
and_ftftfftf(),
and_ftftfftt(),
and_ftftftff(),
and_ftftftft(),
and_ftftfttf(),
and_ftftfttt(),
and_ftfttfff(),
and_ftfttfft(),
and_ftfttftf(),
and_ftfttftt(),
and_ftftttff(),
and_ftftttft(),
and_ftfttttf(),
and_ftfttttt(),
and_fttfffff(),
and_fttfffft(),
and_fttffftf(),
and_fttffftt(),
and_fttfftff(),
and_fttfftft(),
and_fttffttf(),
and_fttffttt(),
and_fttftfff(),
and_fttftfft(),
and_fttftftf(),
and_fttftftt(),
and_fttfttff(),
and_fttfttft(),
and_fttftttf(),
and_fttftttt(),
and_ftttffff(),
and_ftttffft(),
and_ftttfftf(),
and_ftttfftt(),
and_ftttftff(),
and_ftttftft(),
and_ftttfttf(),
and_ftttfttt(),
and_fttttfff(),
and_fttttfft(),
and_fttttftf(),
and_fttttftt(),
and_ftttttff(),
and_ftttttft(),
and_fttttttf(),
and_fttttttt(),
and_tfffffff(),
and_tfffffft(),
and_tffffftf(),
and_tffffftt(),
and_tfffftff(),
and_tfffftft(),
and_tffffttf(),
and_tffffttt(),
and_tffftfff(),
and_tffftfft(),
and_tffftftf(),
and_tffftftt(),
and_tfffttff(),
and_tfffttft(),
and_tffftttf(),
and_tffftttt(),
and_tfftffff(),
and_tfftffft(),
and_tfftfftf(),
and_tfftfftt(),
and_tfftftff(),
and_tfftftft(),
and_tfftfttf(),
and_tfftfttt(),
and_tffttfff(),
and_tffttfft(),
and_tffttftf(),
and_tffttftt(),
and_tfftttff(),
and_tfftttft(),
and_tffttttf(),
and_tffttttt(),
and_tftfffff(),
and_tftfffft(),
and_tftffftf(),
and_tftffftt(),
and_tftfftff(),
and_tftfftft(),
and_tftffttf(),
and_tftffttt(),
and_tftftfff(),
and_tftftfft(),
and_tftftftf(),
and_tftftftt(),
and_tftfttff(),
and_tftfttft(),
and_tftftttf(),
and_tftftttt(),
and_tfttffff(),
and_tfttffft(),
and_tfttfftf(),
and_tfttfftt(),
and_tfttftff(),
and_tfttftft(),
and_tfttfttf(),
and_tfttfttt(),
and_tftttfff(),
and_tftttfft(),
and_tftttftf(),
and_tftttftt(),
and_tfttttff(),
and_tfttttft(),
and_tftttttf(),
and_tftttttt(),
and_ttffffff(),
and_ttffffft(),
and_ttfffftf(),
and_ttfffftt(),
and_ttffftff(),
and_ttffftft(),
and_ttfffttf(),
and_ttfffttt(),
and_ttfftfff(),
and_ttfftfft(),
and_ttfftftf(),
and_ttfftftt(),
and_ttffttff(),
and_ttffttft(),
and_ttfftttf(),
and_ttfftttt(),
and_ttftffff(),
and_ttftffft(),
and_ttftfftf(),
and_ttftfftt(),
and_ttftftff(),
and_ttftftft(),
and_ttftfttf(),
and_ttftfttt(),
and_ttfttfff(),
and_ttfttfft(),
and_ttfttftf(),
and_ttfttftt(),
and_ttftttff(),
and_ttftttft(),
and_ttfttttf(),
and_ttfttttt(),
and_tttfffff(),
and_tttfffft(),
and_tttffftf(),
and_tttffftt(),
and_tttfftff(),
and_tttfftft(),
and_tttffttf(),
and_tttffttt(),
and_tttftfff(),
and_tttftfft(),
and_tttftftf(),
and_tttftftt(),
and_tttfttff(),
and_tttfttft(),
and_tttftttf(),
and_tttftttt(),
and_ttttffff(),
and_ttttffft(),
and_ttttfftf(),
and_ttttfftt(),
and_ttttftff(),
and_ttttftft(),
and_ttttfttf(),
and_ttttfttt(),
and_tttttfff(),
and_tttttfft(),
and_tttttftf(),
and_tttttftt(),
and_ttttttff(),
and_ttttttft(),
and_tttttttf(),
and_tttttttt(),
pi1_ffffffff(),
pi1_ffffffft(),
pi1_fffffftf(),
pi1_fffffftt(),
pi1_ffffftff(),
pi1_ffffftft(),
pi1_fffffttf(),
pi1_fffffttt(),
pi1_fffftfff(),
pi1_fffftfft(),
pi1_fffftftf(),
pi1_fffftftt(),
pi1_ffffttff(),
pi1_ffffttft(),
pi1_fffftttf(),
pi1_fffftttt(),
pi1_ffftffff(),
pi1_ffftffft(),
pi1_ffftfftf(),
pi1_ffftfftt(),
pi1_ffftftff(),
pi1_ffftftft(),
pi1_ffftfttf(),
pi1_ffftfttt(),
pi1_fffttfff(),
pi1_fffttfft(),
pi1_fffttftf(),
pi1_fffttftt(),
pi1_ffftttff(),
pi1_ffftttft(),
pi1_fffttttf(),
pi1_fffttttt(),
pi1_fftfffff(),
pi1_fftfffft(),
pi1_fftffftf(),
pi1_fftffftt(),
pi1_fftfftff(),
pi1_fftfftft(),
pi1_fftffttf(),
pi1_fftffttt(),
pi1_fftftfff(),
pi1_fftftfft(),
pi1_fftftftf(),
pi1_fftftftt(),
pi1_fftfttff(),
pi1_fftfttft(),
pi1_fftftttf(),
pi1_fftftttt(),
pi1_ffttffff(),
pi1_ffttffft(),
pi1_ffttfftf(),
pi1_ffttfftt(),
pi1_ffttftff(),
pi1_ffttftft(),
pi1_ffttfttf(),
pi1_ffttfttt(),
pi1_fftttfff(),
pi1_fftttfft(),
pi1_fftttftf(),
pi1_fftttftt(),
pi1_ffttttff(),
pi1_ffttttft(),
pi1_fftttttf(),
pi1_fftttttt(),
pi1_ftffffff(),
pi1_ftffffft(),
pi1_ftfffftf(),
pi1_ftfffftt(),
pi1_ftffftff(),
pi1_ftffftft(),
pi1_ftfffttf(),
pi1_ftfffttt(),
pi1_ftfftfff(),
pi1_ftfftfft(),
pi1_ftfftftf(),
pi1_ftfftftt(),
pi1_ftffttff(),
pi1_ftffttft(),
pi1_ftfftttf(),
pi1_ftfftttt(),
pi1_ftftffff(),
pi1_ftftffft(),
pi1_ftftfftf(),
pi1_ftftfftt(),
pi1_ftftftff(),
pi1_ftftftft(),
pi1_ftftfttf(),
pi1_ftftfttt(),
pi1_ftfttfff(),
pi1_ftfttfft(),
pi1_ftfttftf(),
pi1_ftfttftt(),
pi1_ftftttff(),
pi1_ftftttft(),
pi1_ftfttttf(),
pi1_ftfttttt(),
pi1_fttfffff(),
pi1_fttfffft(),
pi1_fttffftf(),
pi1_fttffftt(),
pi1_fttfftff(),
pi1_fttfftft(),
pi1_fttffttf(),
pi1_fttffttt(),
pi1_fttftfff(),
pi1_fttftfft(),
pi1_fttftftf(),
pi1_fttftftt(),
pi1_fttfttff(),
pi1_fttfttft(),
pi1_fttftttf(),
pi1_fttftttt(),
pi1_ftttffff(),
pi1_ftttffft(),
pi1_ftttfftf(),
pi1_ftttfftt(),
pi1_ftttftff(),
pi1_ftttftft(),
pi1_ftttfttf(),
pi1_ftttfttt(),
pi1_fttttfff(),
pi1_fttttfft(),
pi1_fttttftf(),
pi1_fttttftt(),
pi1_ftttttff(),
pi1_ftttttft(),
pi1_fttttttf(),
pi1_fttttttt(),
pi1_tfffffff(),
pi1_tfffffft(),
pi1_tffffftf(),
pi1_tffffftt(),
pi1_tfffftff(),
pi1_tfffftft(),
pi1_tffffttf(),
pi1_tffffttt(),
pi1_tffftfff(),
pi1_tffftfft(),
pi1_tffftftf(),
pi1_tffftftt(),
pi1_tfffttff(),
pi1_tfffttft(),
pi1_tffftttf(),
pi1_tffftttt(),
pi1_tfftffff(),
pi1_tfftffft(),
pi1_tfftfftf(),
pi1_tfftfftt(),
pi1_tfftftff(),
pi1_tfftftft(),
pi1_tfftfttf(),
pi1_tfftfttt(),
pi1_tffttfff(),
pi1_tffttfft(),
pi1_tffttftf(),
pi1_tffttftt(),
pi1_tfftttff(),
pi1_tfftttft(),
pi1_tffttttf(),
pi1_tffttttt(),
pi1_tftfffff(),
pi1_tftfffft(),
pi1_tftffftf(),
pi1_tftffftt(),
pi1_tftfftff(),
pi1_tftfftft(),
pi1_tftffttf(),
pi1_tftffttt(),
pi1_tftftfff(),
pi1_tftftfft(),
pi1_tftftftf(),
pi1_tftftftt(),
pi1_tftfttff(),
pi1_tftfttft(),
pi1_tftftttf(),
pi1_tftftttt(),
pi1_tfttffff(),
pi1_tfttffft(),
pi1_tfttfftf(),
pi1_tfttfftt(),
pi1_tfttftff(),
pi1_tfttftft(),
pi1_tfttfttf(),
pi1_tfttfttt(),
pi1_tftttfff(),
pi1_tftttfft(),
pi1_tftttftf(),
pi1_tftttftt(),
pi1_tfttttff(),
pi1_tfttttft(),
pi1_tftttttf(),
pi1_tftttttt(),
pi1_ttffffff(),
pi1_ttffffft(),
pi1_ttfffftf(),
pi1_ttfffftt(),
pi1_ttffftff(),
pi1_ttffftft(),
pi1_ttfffttf(),
pi1_ttfffttt(),
pi1_ttfftfff(),
pi1_ttfftfft(),
pi1_ttfftftf(),
pi1_ttfftftt(),
pi1_ttffttff(),
pi1_ttffttft(),
pi1_ttfftttf(),
pi1_ttfftttt(),
pi1_ttftffff(),
pi1_ttftffft(),
pi1_ttftfftf(),
pi1_ttftfftt(),
pi1_ttftftff(),
pi1_ttftftft(),
pi1_ttftfttf(),
pi1_ttftfttt(),
pi1_ttfttfff(),
pi1_ttfttfft(),
pi1_ttfttftf(),
pi1_ttfttftt(),
pi1_ttftttff(),
pi1_ttftttft(),
pi1_ttfttttf(),
pi1_ttfttttt(),
pi1_tttfffff(),
pi1_tttfffft(),
pi1_tttffftf(),
pi1_tttffftt(),
pi1_tttfftff(),
pi1_tttfftft(),
pi1_tttffttf(),
pi1_tttffttt(),
pi1_tttftfff(),
pi1_tttftfft(),
pi1_tttftftf(),
pi1_tttftftt(),
pi1_tttfttff(),
pi1_tttfttft(),
pi1_tttftttf(),
pi1_tttftttt(),
pi1_ttttffff(),
pi1_ttttffft(),
pi1_ttttfftf(),
pi1_ttttfftt(),
pi1_ttttftff(),
pi1_ttttftft(),
pi1_ttttfttf(),
pi1_ttttfttt(),
pi1_tttttfff(),
pi1_tttttfft(),
pi1_tttttftf(),
pi1_tttttftt(),
pi1_ttttttff(),
pi1_ttttttft(),
pi1_tttttttf(),
pi1_tttttttt(),
pi2_ffffffff(),
pi2_ffffffft(),
pi2_fffffftf(),
pi2_fffffftt(),
pi2_ffffftff(),
pi2_ffffftft(),
pi2_fffffttf(),
pi2_fffffttt(),
pi2_fffftfff(),
pi2_fffftfft(),
pi2_fffftftf(),
pi2_fffftftt(),
pi2_ffffttff(),
pi2_ffffttft(),
pi2_fffftttf(),
pi2_fffftttt(),
pi2_ffftffff(),
pi2_ffftffft(),
pi2_ffftfftf(),
pi2_ffftfftt(),
pi2_ffftftff(),
pi2_ffftftft(),
pi2_ffftfttf(),
pi2_ffftfttt(),
pi2_fffttfff(),
pi2_fffttfft(),
pi2_fffttftf(),
pi2_fffttftt(),
pi2_ffftttff(),
pi2_ffftttft(),
pi2_fffttttf(),
pi2_fffttttt(),
pi2_fftfffff(),
pi2_fftfffft(),
pi2_fftffftf(),
pi2_fftffftt(),
pi2_fftfftff(),
pi2_fftfftft(),
pi2_fftffttf(),
pi2_fftffttt(),
pi2_fftftfff(),
pi2_fftftfft(),
pi2_fftftftf(),
pi2_fftftftt(),
pi2_fftfttff(),
pi2_fftfttft(),
pi2_fftftttf(),
pi2_fftftttt(),
pi2_ffttffff(),
pi2_ffttffft(),
pi2_ffttfftf(),
pi2_ffttfftt(),
pi2_ffttftff(),
pi2_ffttftft(),
pi2_ffttfttf(),
pi2_ffttfttt(),
pi2_fftttfff(),
pi2_fftttfft(),
pi2_fftttftf(),
pi2_fftttftt(),
pi2_ffttttff(),
pi2_ffttttft(),
pi2_fftttttf(),
pi2_fftttttt(),
pi2_ftffffff(),
pi2_ftffffft(),
pi2_ftfffftf(),
pi2_ftfffftt(),
pi2_ftffftff(),
pi2_ftffftft(),
pi2_ftfffttf(),
pi2_ftfffttt(),
pi2_ftfftfff(),
pi2_ftfftfft(),
pi2_ftfftftf(),
pi2_ftfftftt(),
pi2_ftffttff(),
pi2_ftffttft(),
pi2_ftfftttf(),
pi2_ftfftttt(),
pi2_ftftffff(),
pi2_ftftffft(),
pi2_ftftfftf(),
pi2_ftftfftt(),
pi2_ftftftff(),
pi2_ftftftft(),
pi2_ftftfttf(),
pi2_ftftfttt(),
pi2_ftfttfff(),
pi2_ftfttfft(),
pi2_ftfttftf(),
pi2_ftfttftt(),
pi2_ftftttff(),
pi2_ftftttft(),
pi2_ftfttttf(),
pi2_ftfttttt(),
pi2_fttfffff(),
pi2_fttfffft(),
pi2_fttffftf(),
pi2_fttffftt(),
pi2_fttfftff(),
pi2_fttfftft(),
pi2_fttffttf(),
pi2_fttffttt(),
pi2_fttftfff(),
pi2_fttftfft(),
pi2_fttftftf(),
pi2_fttftftt(),
pi2_fttfttff(),
pi2_fttfttft(),
pi2_fttftttf(),
pi2_fttftttt(),
pi2_ftttffff(),
pi2_ftttffft(),
pi2_ftttfftf(),
pi2_ftttfftt(),
pi2_ftttftff(),
pi2_ftttftft(),
pi2_ftttfttf(),
pi2_ftttfttt(),
pi2_fttttfff(),
pi2_fttttfft(),
pi2_fttttftf(),
pi2_fttttftt(),
pi2_ftttttff(),
pi2_ftttttft(),
pi2_fttttttf(),
pi2_fttttttt(),
pi2_tfffffff(),
pi2_tfffffft(),
pi2_tffffftf(),
pi2_tffffftt(),
pi2_tfffftff(),
pi2_tfffftft(),
pi2_tffffttf(),
pi2_tffffttt(),
pi2_tffftfff(),
pi2_tffftfft(),
pi2_tffftftf(),
pi2_tffftftt(),
pi2_tfffttff(),
pi2_tfffttft(),
pi2_tffftttf(),
pi2_tffftttt(),
pi2_tfftffff(),
pi2_tfftffft(),
pi2_tfftfftf(),
pi2_tfftfftt(),
pi2_tfftftff(),
pi2_tfftftft(),
pi2_tfftfttf(),
pi2_tfftfttt(),
pi2_tffttfff(),
pi2_tffttfft(),
pi2_tffttftf(),
pi2_tffttftt(),
pi2_tfftttff(),
pi2_tfftttft(),
pi2_tffttttf(),
pi2_tffttttt(),
pi2_tftfffff(),
pi2_tftfffft(),
pi2_tftffftf(),
pi2_tftffftt(),
pi2_tftfftff(),
pi2_tftfftft(),
pi2_tftffttf(),
pi2_tftffttt(),
pi2_tftftfff(),
pi2_tftftfft(),
pi2_tftftftf(),
pi2_tftftftt(),
pi2_tftfttff(),
pi2_tftfttft(),
pi2_tftftttf(),
pi2_tftftttt(),
pi2_tfttffff(),
pi2_tfttffft(),
pi2_tfttfftf(),
pi2_tfttfftt(),
pi2_tfttftff(),
pi2_tfttftft(),
pi2_tfttfttf(),
pi2_tfttfttt(),
pi2_tftttfff(),
pi2_tftttfft(),
pi2_tftttftf(),
pi2_tftttftt(),
pi2_tfttttff(),
pi2_tfttttft(),
pi2_tftttttf(),
pi2_tftttttt(),
pi2_ttffffff(),
pi2_ttffffft(),
pi2_ttfffftf(),
pi2_ttfffftt(),
pi2_ttffftff(),
pi2_ttffftft(),
pi2_ttfffttf(),
pi2_ttfffttt(),
pi2_ttfftfff(),
pi2_ttfftfft(),
pi2_ttfftftf(),
pi2_ttfftftt(),
pi2_ttffttff(),
pi2_ttffttft(),
pi2_ttfftttf(),
pi2_ttfftttt(),
pi2_ttftffff(),
pi2_ttftffft(),
pi2_ttftfftf(),
pi2_ttftfftt(),
pi2_ttftftff(),
pi2_ttftftft(),
pi2_ttftfttf(),
pi2_ttftfttt(),
pi2_ttfttfff(),
pi2_ttfttfft(),
pi2_ttfttftf(),
pi2_ttfttftt(),
pi2_ttftttff(),
pi2_ttftttft(),
pi2_ttfttttf(),
pi2_ttfttttt(),
pi2_tttfffff(),
pi2_tttfffft(),
pi2_tttffftf(),
pi2_tttffftt(),
pi2_tttfftff(),
pi2_tttfftft(),
pi2_tttffttf(),
pi2_tttffttt(),
pi2_tttftfff(),
pi2_tttftfft(),
pi2_tttftftf(),
pi2_tttftftt(),
pi2_tttfttff(),
pi2_tttfttft(),
pi2_tttftttf(),
pi2_tttftttt(),
pi2_ttttffff(),
pi2_ttttffft(),
pi2_ttttfftf(),
pi2_ttttfftt(),
pi2_ttttftff(),
pi2_ttttftft(),
pi2_ttttfttf(),
pi2_ttttfttt(),
pi2_tttttfff(),
pi2_tttttfft(),
pi2_tttttftf(),
pi2_tttttftt(),
pi2_ttttttff(),
pi2_ttttttft(),
pi2_tttttttf(),
pi2_tttttttt(),
// pi1(),
// pi2(),
input(),
];
prove_something("simple", "(vec false true false true)", rules, &[]);
}
// #[test]
// fn prove_contrapositive() {
// let _ = env_logger::builder().is_test(true).try_init();
// let rules = &[def_imply(), def_imply_flip(), double_neg_flip(), comm_or()];
// prove_something(
// "contrapositive",
// "(-> x y)",
// rules,
// &[
// "(-> x y)",
// "(| (~ x) y)",
// "(| (~ x) (~ (~ y)))",
// "(| (~ (~ y)) (~ x))",
// "(-> (~ y) (~ x))",
// ],
// );
// }
// #[test]
// fn prove_chain() {
// let _ = env_logger::builder().is_test(true).try_init();
// let rules = &[
// // rules needed for contrapositive
// def_imply(),
// def_imply_flip(),
// double_neg_flip(),
// comm_or(),
// // and some others
// comm_and(),
// lem_imply(),
// ];
// prove_something(
// "chain",
// "(& (-> x y) (-> y z))",
// rules,
// &[
// "(& (-> x y) (-> y z))",
// "(& (-> (~ y) (~ x)) (-> y z))",
// "(& (-> y z) (-> (~ y) (~ x)))",
// "(| z (~ x))",
// "(| (~ x) z)",
// "(-> x z)",
// ],
// );
// }
// #[test]
// fn const_fold() {
// let start = "(| (& false true) (& true false))";
// let start_expr = start.parse().unwrap();
// let end = "false";
// let end_expr = end.parse().unwrap();
// let mut eg = EGraph::default();
// eg.add_expr(&start_expr);
// eg.rebuild();
// assert!(!eg.equivs(&start_expr, &end_expr).is_empty());
// }
|
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use super::address::AddressError;
use libp2p::PeerId;
use std::borrow::Cow;
use std::str::FromStr;
type Result<T> = core::result::Result<T, AddressError>;
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum Protocol {
// Service on the network
Service(String),
// Directly accessible peer
Peer(PeerId),
// Peer that's accessible only via relay mechanics
Client(PeerId),
Signature(Vec<u8>),
}
impl Protocol {
#[allow(clippy::should_implement_trait)]
// Builds Protocol from next 2 elements of the given iterator
pub fn from_iter<'a, I>(mut iter: I) -> Result<Self>
where
I: Iterator<Item = &'a str>,
{
use self::Protocol::*;
match iter.next().ok_or(AddressError::Empty)? {
"service" => {
let id = iter.next().ok_or(AddressError::Empty)?;
Ok(Service(id.into()))
}
"peer" => {
let id = Self::parse_peer_id(iter)?;
Ok(Peer(id))
}
"client" => {
let id = Self::parse_peer_id(iter)?;
Ok(Client(id))
}
"signature" => {
let sig = iter.next().ok_or(AddressError::Empty)?;
let sig = Self::parse_base_58(sig)?;
Ok(Signature(sig))
}
_ => Err(AddressError::UnknownProtocol),
}
}
// Returns tuple of (kind, value).
// Basically destructs Protocol into a tuple (without consuming it)
pub fn components(&self) -> (&'static str, Cow<'_, String>) {
use self::Protocol::*;
match self {
Service(id) => ("service", Cow::Borrowed(id)),
Peer(id) => ("peer", Cow::Owned(Self::peer_id_to_base58(id))),
Client(id) => ("client", Cow::Owned(Self::peer_id_to_base58(id))),
Signature(sig) => ("signature", Cow::Owned(Self::vec_to_base58(sig))),
}
}
// Utility function to parse peer id from iterator. Takes two elements from the iterator.
fn parse_peer_id<'a, I>(mut iter: I) -> Result<PeerId>
where
I: Iterator<Item = &'a str>,
{
let str = iter.next().ok_or(AddressError::Empty)?;
let peer_id: PeerId = str.parse().map_err(|_| AddressError::InvalidPeerId)?;
Ok(peer_id)
}
fn parse_base_58(from: &str) -> Result<Vec<u8>> {
bs58::decode(from)
.into_vec()
.map_err(|_| AddressError::InvalidProtocol)
}
fn peer_id_to_base58(peer_id: &PeerId) -> String {
bs58::encode(peer_id.as_bytes()).into_string()
}
fn vec_to_base58(v: &[u8]) -> String {
bs58::encode(v).into_string()
}
}
impl std::fmt::Display for Protocol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (proto, value) = self.components();
write!(f, "/{}/{}", proto, value)
}
}
impl FromStr for Protocol {
type Err = AddressError;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
let mut parts = s.split('/').peekable();
if Some("") != parts.next() {
// Protocol must start with `/`
return Err(AddressError::InvalidProtocol);
}
Protocol::from_iter(parts)
}
}
|
//! Loading executable binaries into Falcon.
//!
//! ```
//! # use falcon::Error;
//! use falcon::loader::Elf;
//! use falcon::loader::Loader;
//! use std::path::Path;
//!
//! # fn example () -> Result<(), Error> {
//! // Load an elf for analysis
//! let elf = Elf::from_file(Path::new("test_binaries/simple-0/simple-0"))?;
//! // Lift a program from the elf
//! let program = elf.program()?;
//! for function in program.functions() {
//! println!("0x{:08x}: {}", function.address(), function.name());
//! }
//! # Ok(())
//! # }
//! ```
use crate::architecture::Architecture;
use crate::executor::eval;
use crate::il;
use crate::memory;
use crate::translator::Options;
use crate::Error;
use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::fmt;
mod elf;
mod json;
mod pe;
mod symbol;
pub use self::elf::*;
pub use self::json::*;
pub use self::pe::*;
pub use self::symbol::Symbol;
/// A declared entry point for a function.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionEntry {
address: u64,
name: Option<String>,
}
impl FunctionEntry {
/// Create a new `FunctionEntry`.
///
/// If no name is provided: `sup_{:X}` will be used to name the function.
pub fn new(address: u64, name: Option<String>) -> FunctionEntry {
FunctionEntry { address, name }
}
/// Get the address for this `FunctionEntry`.
pub fn address(&self) -> u64 {
self.address
}
/// Get the name for this `FunctionEntry`.
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
}
impl fmt::Display for FunctionEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.name {
Some(ref name) => write!(f, "FunctionEntry({} -> 0x{:X})", name, self.address),
None => write!(f, "FunctionEntry(0x{:X})", self.address),
}
}
}
/// Generic trait for all loaders
pub trait Loader: fmt::Debug + Send + Sync {
/// Get a model of the memory contained in the binary
fn memory(&self) -> Result<memory::backing::Memory, Error>;
/// Get addresses for known function entries
fn function_entries(&self) -> Result<Vec<FunctionEntry>, Error>;
/// The address program execution should begin at
fn program_entry(&self) -> u64;
/// Get the architecture of the binary
fn architecture(&self) -> &dyn Architecture;
/// Lift just one function from the executable
fn function(&self, address: u64) -> Result<il::Function, Error> {
self.function_extended(address, &Options::default())
}
/// Lift just one function from the executable, while also supplying
/// translator options.
fn function_extended(&self, address: u64, options: &Options) -> Result<il::Function, Error> {
let translator = self.architecture().translator();
let memory = self.memory()?;
translator.translate_function_extended(&memory, address, options)
}
/// Cast loader to `Any`
fn as_any(&self) -> &dyn Any;
/// Get the symbols for this loader
fn symbols(&self) -> Vec<Symbol>;
/// Get the symbols as a hashmap by address
fn symbols_map(&self) -> HashMap<u64, Symbol> {
self.symbols()
.into_iter()
.map(|symbol| (symbol.address(), symbol))
.collect()
}
/// Lift executable into an il::Program.
///
/// Individual functions which fail to lift are omitted and ignored.
fn program(&self) -> Result<il::Program, Error> {
Ok(self.program_verbose(&Options::default())?.0)
}
/// Lift executable into an `il::Program`.
///
/// Errors encountered while lifting specific functions are collected, and
/// returned with the `FunctionEntry` identifying the function. Only
/// catastrophic errors should cause this function call to fail.
fn program_verbose(
&self,
options: &Options,
) -> std::result::Result<(il::Program, Vec<(FunctionEntry, Error)>), Error> {
// Get out architecture-specific translator
let translator = self.architecture().translator();
// Create a mapping of the file memory
let memory = self.memory()?;
let mut program = il::Program::new();
let mut translation_errors: Vec<(FunctionEntry, Error)> = Vec::new();
for function_entry in self.function_entries()? {
let address = function_entry.address();
// Ensure this memory is marked executable
if memory
.permissions(address)
.map_or(false, |p| p.contains(memory::MemoryPermissions::EXECUTE))
{
match translator.translate_function_extended(&memory, address, options) {
Ok(mut function) => {
function.set_name(function_entry.name().map(|n| n.to_string()));
program.add_function(function);
}
Err(e) => translation_errors.push((function_entry.clone(), e)),
};
}
}
Ok((program, translation_errors))
}
/// Lift executable into an `il::Program`, while recursively resolving branch
/// targets into functions.
///
/// program_recursive silently drops any functions that cause lifting
/// errors. If you care about those, use `program_recursive_verbose`.
fn program_recursive(&self) -> Result<il::Program, Error> {
Ok(self.program_recursive_verbose(&Options::default())?.0)
}
/// Lift executable into an `il::Program`, while recursively resolving branch
/// targets into functions.
///
/// Works in a similar manner to `program_recursive`
fn program_recursive_verbose(
&self,
options: &Options,
) -> std::result::Result<(il::Program, Vec<(FunctionEntry, Error)>), Error> {
fn call_targets(function: &il::Function) -> Vec<u64> {
let call_targets =
function
.blocks()
.iter()
.fold(Vec::new(), |mut call_targets, block| {
block.instructions().iter().for_each(|instruction| {
if let il::Operation::Branch { ref target } = *instruction.operation() {
if let Ok(constant) = eval(target) {
call_targets.push(constant.value_u64().unwrap())
}
}
});
call_targets
});
call_targets
}
let (mut program, mut translation_errors) = self.program_verbose(options)?;
let mut processed = HashSet::new();
loop {
// Get the address of every function currently in the program
let function_addresses = program
.functions()
.into_iter()
.map(|function| function.address())
.collect::<Vec<u64>>();
let addresses = {
// For every function in the program which is not currentl a
// member of our processed set
let functions = program
.functions()
.into_iter()
.filter(|function| !processed.contains(&function.address()))
.collect::<Vec<&il::Function>>();
// Insert this function into the processed set
functions.iter().for_each(|function| {
processed.insert(function.address());
});
// Collect the call targets in all functions that have not yet
// been processed, and filter them against the functions already
// in program.
let addresses = functions
.into_iter()
.fold(HashSet::new(), |mut targets, function| {
call_targets(function).into_iter().for_each(|target| {
targets.insert(target);
});
targets
})
.into_iter()
.filter(|address| !function_addresses.contains(address))
.collect::<Vec<u64>>();
if addresses.is_empty() {
break;
}
addresses
};
// For each address, attempt to lift a function
for address in addresses {
match self.function_extended(address, options) {
Ok(function) => program.add_function(function),
Err(e) => {
let function_entry = FunctionEntry::new(address, None);
translation_errors.push((function_entry, e));
}
}
}
}
Ok((program, translation_errors))
}
}
|
use crate::generate::ToneKind;
#[derive(Debug, PartialEq, Clone)]
pub struct Note {
frequency: f32,
tone: ToneKind,
volume_from: f32,
volume_to: f32,
offset: f32,
start_at: f32,
end_at: f32,
}
impl Note {
pub fn is_over(&self, position: f32) -> bool {
self.end_at <= position
}
pub fn is_waiting(&self, position: f32) -> bool {
position < self.start_at
}
pub fn is_ringing(&self, position: f32) -> bool {
!self.is_over(position) && !self.is_waiting(position)
}
pub fn get_sample(&self, position: f32) -> f32 {
if !self.is_ringing(position) {
return 0.0;
}
let note_position = position - self.start_at;
let progress_ratio = note_position / (self.end_at - self.start_at);
let volume = self.volume_from + (self.volume_to - self.volume_from) * progress_ratio;
self.tone
.sample(self.frequency, self.offset + note_position)
* volume
}
pub fn end_at(&self) -> f32 {
self.end_at
}
pub fn new(
frequency: f32,
tone: ToneKind,
volume_from: f32,
volume_to: f32,
offset: f32,
start_at: f32,
end_at: f32,
) -> Self {
Self {
frequency,
tone,
volume_from,
volume_to,
offset,
start_at,
end_at,
}
}
}
#[derive(Debug)]
pub struct NotesQueue {
notes: Vec<Note>,
}
impl NotesQueue {
pub fn new(mut notes: Vec<Note>) -> Self {
notes.sort_unstable_by(|a, b| {
b.start_at
.partial_cmp(&a.start_at)
.unwrap_or(std::cmp::Ordering::Equal)
});
NotesQueue { notes }
}
pub fn next_before(&mut self, before: f32) -> Option<Note> {
if self.notes.last()?.is_waiting(before) {
return None;
}
Some(self.notes.remove(self.notes.len() - 1))
}
pub fn iter(&self) -> impl Iterator<Item=&Note> {
self.notes.iter()
}
pub fn is_empty(&self) -> bool {
self.notes.is_empty()
}
}
|
use error::{Error, ErrorKind, Result, StateProblem};
use handshakestate::HandshakeState;
#[cfg(feature = "nightly")] use std::convert::{TryFrom, TryInto};
#[cfg(not(feature = "nightly"))] use utils::{TryFrom, TryInto};
use transportstate::*;
/// A state machine for the entire Noise session.
///
/// Enums provide a convenient interface as it's how Rust implements union structs, meaning this is
/// a sized object.
// TODO: check up on memory usage, since this clippy warning seems like a legit perf issue.
#[cfg_attr(feature = "cargo-clippy", allow(large_enum_variant))]
pub enum Session {
Handshake(HandshakeState),
Transport(TransportState),
}
impl Session {
/// If the payload will be encrypted or not. In a future version of Snow, this interface may
/// change to more proactively prevent unauthenticated, plaintext payloads during handshakes.
///
/// See [Payload Security Properties](http://noiseprotocol.org/noise.html#payload-security-properties)
/// for more information.
pub fn is_payload_encrypted(&self) -> bool {
match *self {
Session::Handshake(ref state) => state.is_write_encrypted(),
Session::Transport(_) => true,
}
}
/// True if the handshake is finished and the Session state machine is ready to be transitioned
/// to transport mode. This function also returns a vacuous true if already in transport mode.
///
/// # Examples
///
/// ```rust,ignore
/// let mut session = NoiseBuilder::new("Noise_NN_25519_AESGCM_SHA256".parse()?)
/// .build_initiator()?;
///
/// if (session.is_handshake_finished()) {
/// session = session.into_transport_mode()?;
/// }
/// ```
pub fn is_handshake_finished(&self) -> bool {
match *self {
Session::Handshake(ref state) => state.is_finished(),
Session::Transport(_) => true,
}
}
/// Construct a message from `payload` (and pending handshake tokens if in handshake state),
/// and writes it to the `output` buffer.
///
/// Returns the size of the written payload.
///
/// # Errors
///
/// Will result in `NoiseError::InputError` if the size of the output exceeds the max message
/// length in the Noise Protocol (65535 bytes).
pub fn write_message(&mut self, payload: &[u8], output: &mut [u8]) -> Result<usize> {
match *self {
Session::Handshake(ref mut state) => state.write_handshake_message(payload, output),
Session::Transport(ref mut state) => state.write_transport_message(payload, output),
}
}
/// Reads a noise message from `input`
///
/// Returns the size of the payload written to `payload`.
///
/// # Errors
///
/// Will result in `NoiseError::DecryptError` if the contents couldn't be decrypted and/or the
/// authentication tag didn't verify.
///
/// # Panics
///
/// This function will panic if there is no key, or if there is a nonce overflow.
pub fn read_message(&mut self, input: &[u8], payload: &mut [u8]) -> Result<usize> {
match *self {
Session::Handshake(ref mut state) => state.read_handshake_message(input, payload),
Session::Transport(ref mut state) => state.read_transport_message(input, payload),
}
}
/// Set a new key for the one or both of the initiator-egress and responder-egress symmetric ciphers.
///
/// # Errors
///
/// Will result in `NoiseError::StateError` if not in transport mode.
pub fn rekey(&mut self, initiator: Option<&[u8]>, responder: Option<&[u8]>) -> Result<()> {
match *self {
Session::Handshake(_) => Err(ErrorKind::State(StateProblem::HandshakeNotFinished).into()),
Session::Transport(ref mut state) => {
if let Some(key) = initiator {
state.rekey_initiator(key);
}
if let Some(key) = responder {
state.rekey_responder(key);
}
Ok(())
},
}
}
/// Get the forthcoming inbound nonce value.
///
/// # Errors
///
/// Will result in `NoiseError::StateError` if not in transport mode.
pub fn receiving_nonce(&self) -> Result<u64> {
match *self {
Session::Handshake(_) => Err(ErrorKind::State(StateProblem::HandshakeNotFinished).into()),
Session::Transport(ref state) => Ok(state.receiving_nonce())
}
}
/// Get the forthcoming outbound nonce value.
///
/// # Errors
///
/// Will result in `NoiseError::StateError` if not in transport mode.
pub fn sending_nonce(&self) -> Result<u64> {
match *self {
Session::Handshake(_) => Err(ErrorKind::State(StateProblem::HandshakeNotFinished).into()),
Session::Transport(ref state) => Ok(state.sending_nonce())
}
}
/// Set the forthcoming incoming nonce value.
///
/// # Errors
///
/// Will result in `NoiseError::StateError` if not in transport mode.
pub fn set_receiving_nonce(&mut self, nonce: u64) -> Result<()> {
match *self {
Session::Handshake(_) => Err(ErrorKind::State(StateProblem::HandshakeNotFinished).into()),
Session::Transport(ref mut state) => Ok(state.set_receiving_nonce(nonce))
}
}
/// Transition the session into transport mode. This can only be done once the handshake
/// has finished.
///
/// Consumes the previous state, and returns the new transport state object, thereby freeing
/// any material only used during the handshake phase.
///
/// # Errors
///
/// Will result in `NoiseError::StateError` if the handshake is not finished.
///
/// # Examples
///
/// ```rust,ignore
/// let mut session = NoiseBuilder::new("Noise_NN_25519_AESGCM_SHA256".parse()?)
/// .build_initiator()?;
///
/// // ... complete handshake ...
///
/// session = session.into_transport_mode()?;
/// ```
///
pub fn into_transport_mode(self) -> Result<Self> {
match self {
Session::Handshake(state) => {
if !state.is_finished() {
Err(ErrorKind::State(StateProblem::HandshakeNotFinished).into())
} else {
Ok(Session::Transport(state.try_into()?))
}
},
_ => Ok(self)
}
}
}
impl Into<Session> for HandshakeState {
fn into(self) -> Session {
Session::Handshake(self)
}
}
impl TryFrom<HandshakeState> for TransportState {
type Error = Error;
fn try_from(old: HandshakeState) -> Result<Self> {
let initiator = old.is_initiator();
let (cipherstates, handshake) = old.finish()?;
Ok(TransportState::new(cipherstates, handshake.pattern, initiator))
}
}
|
use std::cmp::{PartialEq, PartialOrd};
use std::ops::{Range, RangeFrom, RangeFull, RangeTo};
use std::str;
/// Set relationship.
pub trait Set<T> {
/// Whether a set contains an element or not.
fn contains(&self, elem: &T) -> bool;
/// Convert to text for display.
fn to_str(&self) -> &str {
"<set>"
}
}
impl<T: PartialEq> Set<T> for [T] {
fn contains(&self, elem: &T) -> bool {
(self as &[T]).contains(elem)
}
}
impl Set<char> for str {
fn contains(&self, elem: &char) -> bool {
(self as &str).contains(*elem)
}
fn to_str(&self) -> &str {
self
}
}
impl<T: PartialOrd + Copy> Set<T> for Range<T> {
fn contains(&self, elem: &T) -> bool {
self.start <= *elem && self.end > *elem
}
}
impl<T: PartialOrd + Copy> Set<T> for RangeFrom<T> {
fn contains(&self, elem: &T) -> bool {
self.start <= *elem
}
}
impl<T: PartialOrd + Copy> Set<T> for RangeTo<T> {
fn contains(&self, elem: &T) -> bool {
self.end > *elem
}
}
impl<T> Set<T> for RangeFull {
fn contains(&self, _: &T) -> bool {
true
}
fn to_str(&self) -> &str {
".."
}
}
macro_rules! impl_set_for_array {
($n:expr) => {
impl Set<u8> for [u8; $n] {
fn contains(&self, elem: &u8) -> bool {
(self as &[u8]).contains(elem)
}
fn to_str(&self) -> &str {
str::from_utf8(self).unwrap_or("<byte array>")
}
}
};
}
impl_set_for_array!(0);
impl_set_for_array!(1);
impl_set_for_array!(2);
impl_set_for_array!(3);
impl_set_for_array!(4);
impl_set_for_array!(5);
impl_set_for_array!(6);
impl_set_for_array!(7);
impl_set_for_array!(8);
impl_set_for_array!(9);
impl_set_for_array!(10);
impl_set_for_array!(11);
impl_set_for_array!(12);
impl_set_for_array!(13);
impl_set_for_array!(14);
impl_set_for_array!(15);
impl_set_for_array!(16);
impl_set_for_array!(17);
impl_set_for_array!(18);
impl_set_for_array!(19);
impl_set_for_array!(20);
impl_set_for_array!(21);
impl_set_for_array!(22);
impl_set_for_array!(23);
impl_set_for_array!(24);
impl_set_for_array!(25);
impl_set_for_array!(26);
impl_set_for_array!(27);
impl_set_for_array!(28);
impl_set_for_array!(29);
impl_set_for_array!(30);
impl_set_for_array!(31);
impl_set_for_array!(32);
|
use challenges::chal43::{dsa_leaky_k_attack, hash_msg_to_hexstr, DsaPublicParam, DsaSignature};
use challenges::{mod_inv, mod_sub};
use num::BigUint;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::process;
fn main() {
println!("🔓 Challenge 44");
let msgs = read_data();
let pub_parm = DsaPublicParam::default();
// hashmap storing (r, index) where r is part of the signature, index is the index of msgs list
let mut map: HashMap<String, usize> = HashMap::new();
for (i, msg) in msgs.iter().enumerate() {
match map.get(&msg.r) {
None => {
map.insert(msg.r.clone(), i);
}
Some(&index) => {
let guess = repeated_nonce_attack(&msg, &msgs[index], &pub_parm.q);
if is_correct_prikey(&guess) {
println!("Successfully extract your private key!");
process::exit(0);
}
}
};
}
}
#[derive(Deserialize, Debug)]
struct DsaMessage {
msg: String,
s: String,
r: String,
m: String,
}
fn read_data() -> Vec<DsaMessage> {
let data_str = fs::read_to_string("challenges/data/chal44.json").unwrap();
serde_json::from_str::<Vec<DsaMessage>>(&data_str).unwrap()
}
// given two signatures signed using the same nounce k, extract and returns the private key
fn repeated_nonce_attack(m1: &DsaMessage, m2: &DsaMessage, q: &BigUint) -> BigUint {
let m_1 = BigUint::parse_bytes(&m1.m.as_bytes(), 16).unwrap();
let m_2 = BigUint::parse_bytes(&m2.m.as_bytes(), 16).unwrap();
let s_1 = BigUint::parse_bytes(&m1.s.as_bytes(), 10).unwrap();
let s_2 = BigUint::parse_bytes(&m2.s.as_bytes(), 10).unwrap();
// k = (m1 - m1) * (s1 - s2)^-1 mod q
let k = (mod_sub(&m_1, &m_2, &q) * mod_inv(&mod_sub(&s_1, &s_2, &q), &q).unwrap()) % q;
let sig_1 = DsaSignature {
r: BigUint::parse_bytes(&m1.r.as_bytes(), 10).unwrap(),
s: s_1,
};
dsa_leaky_k_attack(&q, &m1.msg.as_bytes(), &k, &sig_1)
}
fn is_correct_prikey(guess: &BigUint) -> bool {
hash_msg_to_hexstr(&guess.to_str_radix(16).as_bytes()) == "ca8f6f7c66fa362d40760d135b763eb8527d3d52"
}
|
use level::place_mob;
use level::tile::{Terrain, TileView};
use prelude::*;
use rand::{thread_rng, Rng};
use world::mob::PLAYER_ID;
pub fn rest(_mob_id: MobId, _world: &mut World) -> Result<(), ()> {
Ok(())
}
pub fn walk(mob_id: MobId, direction: Direction, world: &mut World) -> Result<(), ()> {
let target_pos = world[mob_id].pos + direction;
if world.level[target_pos].mob_id.is_some() {
attack_melee(mob_id, direction, world)
} else if world.level[target_pos].terrain.passable() {
if world[mob_id].guard_recovery > 0 && world[mob_id].facing == direction.rotate(3) {
retreat_unchecked(mob_id, direction, world)
} else {
world.level[target_pos - direction].mob_id = None;
world.level[target_pos].mob_id = Some(mob_id);
world[mob_id].pos = target_pos;
world[mob_id].facing = direction;
Ok(())
}
} else if world.level[target_pos].terrain == Terrain::Exit {
if mob_id.is_player() {
world[mob_id].pos = target_pos;
descend_unchecked(world);
Err(())
} else {
Err(())
}
} else {
Err(())
}
}
fn attack_melee(mob_id: MobId, direction: Direction, world: &mut World) -> Result<(), ()> {
let target_pos = world[mob_id].pos + direction;
if let Some(target) = world.level[target_pos].mob_id {
if mob_id.is_player() || target.is_player() {
let damage = thread_rng().gen_range(1, 7) + thread_rng().gen_range(1, 7);
let guard = world[target].guard;
if damage <= guard {
world[target].guard -= damage;
} else {
let damage = damage - world[target].guard;
world[target].guard = 0;
if damage < world[target].health {
world[target].health -= damage;
} else {
world[target].health = 0;
target.die(world);
}
}
if world[target].facing == direction.rotate(3) {
world[target].guard_recovery = damage / 2;
}
world[mob_id].facing = direction;
Ok(())
} else {
Err(())
}
} else {
Err(())
}
}
fn retreat_unchecked(mob_id: MobId, direction: Direction, world: &mut World) -> Result<(), ()> {
let target_pos = world[mob_id].pos + direction;
world.level[target_pos - direction].mob_id = None;
world.level[target_pos].mob_id = Some(mob_id);
world[mob_id].pos = target_pos;
world[mob_id].guard += world[mob_id].guard_recovery;
Ok(())
}
fn descend_unchecked(world: &mut World) {
let (level, npcs) = world.architect.generate();
world.level = level;
world.npcs = npcs;
let player_pos = place_mob(
&mut world.level,
world.player.pos,
PLAYER_ID,
&mut thread_rng(),
);
world.player.facing = (player_pos - world.player.pos).direction();
world.player.pos = player_pos;
world.fov = Grid::new(|_| TileView::None);
world.update_fov();
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2
use jsonrpc_core::Result;
use jsonrpc_derive::rpc;
pub use self::gen_client::Client as DebugClient;
#[rpc]
pub trait DebugApi {
#[rpc(name = "debug.set_log_level")]
fn set_log_level(&self, level: String) -> Result<()>;
///Trigger the node panic, only work for dev network.
#[rpc(name = "debug.panic")]
fn panic(&self) -> Result<()>;
}
|
/*!
*/
use std::time::Duration;
const REMOTE_MAC: [u8; 6] = *b"RSK\x12\x34\x56";
const LOCAL_MAC: [u8; 6] = *b"RSK\xFE\xFE\xFE";
pub mod tcp;
pub mod ipv4;
pub mod ethernet;
pub struct TestFramework {
socket: std::net::UdpSocket,
remote_addr: std::net::SocketAddr,
process: std::process::Child,
logfile: std::path::PathBuf,
}
impl TestFramework
{
pub fn new(name: &str) -> TestFramework
{
let logfile: std::path::PathBuf = format!("{}.txt", name).into();
// NOTE: Ports allocated seqentially to avoid collisions between threaded tests
static NEXT_PORT: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(12340);
let port = NEXT_PORT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
match std::process::Command::new( env!("CARGO") )
.arg("build").arg("--bin").arg("host")
.spawn().unwrap().wait()
{
Ok(status) if status.success() => {},
Ok(rc) => panic!("Building helper failed: Non-zero exit status - {}", rc),
Err(e) => panic!("Building helper failed: {}", e),
}
let socket = std::net::UdpSocket::bind( ("127.0.0.1", port) ).expect("Unable to bind socket");
println!("Spawning child");
let mut child = std::process::Command::new( env!("CARGO") ).arg("run").arg("--quiet").arg("--bin").arg("host").arg("--")
//let mut child = std::process::Command::new("target/debug/host")
.arg(format!("127.0.0.1:{}", port))
.arg("192.168.1.1")// /24")
//.stdin( std::process::Stdio::piped() )
.stdout(std::fs::File::create(&logfile).unwrap())
//.stderr(std::fs::File::create("stderr.txt").unwrap())
.spawn()
.expect("Can't spawn child")
;
println!("Waiting for child");
socket.set_read_timeout(Some(Duration::from_millis(200))).unwrap();
let addr = match socket.recv_from(&mut [0])
{
Ok( (_len, v) ) => v,
Err(e) => {
match child.try_wait()
{
Ok(_) => {},
Err(_) => child.kill().expect("Unable to terminate child"),
}
panic!("Child didn't connect: {}", e)
},
};
TestFramework {
socket: socket,
remote_addr: addr,
process: child,
logfile: logfile,
}
}
pub fn send_command(&self, s: &str)
{
let mut msg_buf = [0; 4 + 1500];
msg_buf[4..][..s.len()].copy_from_slice( s.as_bytes() );
self.socket.send_to(&msg_buf[.. 4 + s.len()], self.remote_addr).expect("Failed to send to child");
}
/// Encode+send an ethernet frame to the virtualised NIC (addressed correctly)
pub fn send_ethernet_direct(&self, proto: u16, buffers: &[ &[u8] ])
{
let ethernet_hdr = crate::ethernet::EthernetHeader { dst: REMOTE_MAC, src: LOCAL_MAC, proto: proto, }.encode();
let buf: Vec<u8> = Iterator::chain([&[1,0,0,0], ðernet_hdr as &[u8]].iter(), buffers.iter())
.flat_map(|v| v.iter())
.copied()
.collect()
;
println!("TX {:?}", HexDump(&buf));
self.socket.send_to(&buf, self.remote_addr).expect("Failed to send to child");
}
pub fn wait_packet(&self, timeout: Duration) -> Option<Vec<u8>>
{
self.socket.set_read_timeout(Some(timeout)).expect("Zero timeout requested");
let mut buf = vec![0; 1560];
loop
{
let (len, addr) = match self.socket.recv_from(&mut buf)
{
Ok(v) => v,
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => return None,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return None,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => panic!("wait_packet: Error {} (Kind = {:?})", e, e.kind()),
};
if addr != self.remote_addr {
// Hmm...
}
buf.truncate(len);
println!("RX {:?}", HexDump(&buf));
return Some(buf);
}
}
}
impl Drop for TestFramework
{
fn drop(&mut self)
{
if self.process.try_wait().is_err()
{
self.send_command("exit");
std::thread::sleep(std::time::Duration::new(0,500*1000) );
}
if self.process.try_wait().is_err()
{
self.process.kill().expect("Cannot terminate child");
}
if std::thread::panicking() {
println!("See {} for worker log", self.logfile.canonicalize().unwrap().display());
}
}
}
/// Wrapper around a &-ptr that prints a hexdump of the passed data.
pub struct HexDump<'a>(pub &'a [u8]);
impl<'a> HexDump<'a>
{
}
impl<'a> ::std::fmt::Debug for HexDump<'a>
{
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result
{
let slice = self.0;
write!(f, "{} bytes: ", slice.len())?;
for (idx,v) in slice.iter().enumerate()
{
write!(f, "{:02x} ", *v)?;
if idx % 16 == 15 {
write!(f, "| ")?;
}
}
Ok( () )
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::String;
use alloc::vec::Vec;
use core::any::Any;
use socket::unix::transport::unix::BoundEndpoint;
use super::super::super::qlib::common::*;
use super::super::super::qlib::linux_def::*;
use super::super::super::qlib::auth::*;
use super::super::super::kernel::time::*;
use super::super::super::task::*;
use super::super::host::hostinodeop::*;
use super::super::attr::*;
use super::super::file::*;
use super::super::flags::*;
use super::super::dirent::*;
use super::super::mount::*;
use super::super::inode::*;
use super::super::ramfs::dir::*;
pub trait DirDataNode: Send + Sync {
fn Lookup(&self, d: &Dir, task: &Task, dir: &Inode, name: &str) -> Result<Dirent>;
fn GetFile(&self, d: &Dir, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File>;
fn Check(&self, d: &Dir, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {
return d.Check(task, inode, reqPerms);
}
}
#[derive(Clone)]
pub struct DirNode<T: 'static + DirDataNode> {
pub dir: Dir,
pub data: T,
}
impl <T: 'static + DirDataNode> InodeOperations for DirNode <T> {
fn as_any(&self) -> &Any {
return self
}
fn IopsType(&self) -> IopsType {
return IopsType::DirNode;
}
fn InodeType(&self) -> InodeType {
return self.dir.InodeType();
}
fn InodeFileType(&self) -> InodeFileType {
return InodeFileType::DirNode;
}
fn WouldBlock(&self) -> bool {
return false;
}
fn Lookup(&self, task: &Task, dir: &Inode, name: &str) -> Result<Dirent> {
return self.data.Lookup(&self.dir, task, dir, name);
}
fn Create(&self, task: &Task, dir: &mut Inode, name: &str, flags: &FileFlags, perms: &FilePermissions) -> Result<File> {
return self.dir.Create(task, dir, name, flags, perms);
}
fn CreateDirectory(&self, task: &Task, dir: &mut Inode, name: &str, perms: &FilePermissions) -> Result<()> {
return self.dir.CreateDirectory(task, dir, name, perms);
}
fn CreateLink(&self, task: &Task, dir: &mut Inode, oldname: &str, newname: &str) -> Result<()> {
return self.dir.CreateLink(task, dir, oldname, newname);
}
fn CreateHardLink(&self, task: &Task, dir: &mut Inode, target: &Inode, name: &str) -> Result<()> {
return self.dir.CreateHardLink(task, dir, target, name);
}
fn CreateFifo(&self, task: &Task, dir: &mut Inode, name: &str, perms: &FilePermissions) -> Result<()> {
return self.dir.CreateFifo(task, dir, name, perms);
}
//fn RemoveDirent(&mut self, dir: &mut InodeStruStru, remove: &Arc<Mutex<Dirent>>) -> Result<()> ;
fn Remove(&self, task: &Task, dir: &mut Inode, name: &str) -> Result<()> {
return self.dir.Remove(task, dir, name);
}
fn RemoveDirectory(&self, task: &Task, dir: &mut Inode, name: &str) -> Result<()> {
return self.dir.RemoveDirectory(task, dir, name);
}
fn Rename(&self, task: &Task, dir: &mut Inode, oldParent: &Inode, oldname: &str, newParent: &Inode, newname: &str, replacement: bool) -> Result<()> {
return self.dir.Rename(task, dir, oldParent, oldname, newParent, newname, replacement);
}
fn Bind(&self, _task: &Task, _dir: &Inode, _name: &str, _data: &BoundEndpoint, _perms: &FilePermissions) -> Result<Dirent> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn BoundEndpoint(&self, _task: &Task, _inode: &Inode, _path: &str) -> Option<BoundEndpoint> {
return None
}
fn GetFile(&self, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> {
return self.data.GetFile(&self.dir, task, dir, dirent, flags);
}
fn UnstableAttr(&self, task: &Task, dir: &Inode) -> Result<UnstableAttr> {
return self.dir.UnstableAttr(task, dir);
}
fn Getxattr(&self, dir: &Inode, name: &str) -> Result<String> {
return self.dir.Getxattr(dir, name);
}
fn Setxattr(&self, dir: &mut Inode, name: &str, value: &str) -> Result<()> {
return self.dir.Setxattr(dir, name, value);
}
fn Listxattr(&self, dir: &Inode) -> Result<Vec<String>> {
return self.dir.Listxattr(dir);
}
fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {
return self.data.Check(&self.dir, task, inode, reqPerms);
}
fn SetPermissions(&self, task: &Task, dir: &mut Inode, p: FilePermissions) -> bool {
return self.dir.SetPermissions(task, dir, p);
}
fn SetOwner(&self, task: &Task, dir: &mut Inode, owner: &FileOwner) -> Result<()> {
return self.dir.SetOwner(task, dir, owner);
}
fn SetTimestamps(&self, task: &Task, dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> {
return self.dir.SetTimestamps(task, dir, ts);
}
fn Truncate(&self, task: &Task, dir: &mut Inode, size: i64) -> Result<()> {
return self.dir.Truncate(task, dir, size);
}
fn Allocate(&self, task: &Task, dir: &mut Inode, offset: i64, length: i64) -> Result<()> {
return self.dir.Allocate(task, dir, offset, length);
}
fn ReadLink(&self, task: &Task, dir: &Inode) -> Result<String> {
return self.dir.ReadLink(task, dir);
}
fn GetLink(&self, task: &Task, dir: &Inode) -> Result<Dirent> {
return self.dir.GetLink(task, dir);
}
fn AddLink(&self, task: &Task) {
self.dir.AddLink(task);
}
fn DropLink(&self, task: &Task) {
self.dir.DropLink(task);
}
fn IsVirtual(&self) -> bool {
return self.dir.IsVirtual();
}
fn Sync(&self) -> Result<()> {
return self.dir.Sync();
}
fn StatFS(&self, task: &Task) -> Result<FsInfo> {
return self.dir.StatFS(task);
}
fn Mappable(&self) -> Result<HostInodeOp> {
return self.dir.Mappable();
}
} |
use crate::stdio_server::handler::{initialize_provider, CachedPreviewImpl, PreviewTarget};
use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context, ProviderSource};
use crate::stdio_server::vim::VimProgressor;
use anyhow::Result;
use filter::{FilterContext, ParallelSource};
use parking_lot::Mutex;
use printer::{DisplayLines, Printer};
use serde_json::json;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
use subprocess::Exec;
use types::MatchedItem;
#[derive(Debug)]
enum DataSource {
File(PathBuf),
Command(String),
}
#[derive(Debug)]
struct FilterControl {
stop_signal: Arc<AtomicBool>,
join_handle: JoinHandle<()>,
}
impl FilterControl {
fn kill(self) {
self.stop_signal.store(true, Ordering::SeqCst);
let _ = self.join_handle.join();
}
}
/// Start the parallel filter in a new thread.
fn start_filter_parallel(
query: String,
number: usize,
data_source: DataSource,
ctx: &Context,
) -> FilterControl {
let stop_signal = Arc::new(AtomicBool::new(false));
let join_handle = {
let filter_context = FilterContext::new(
ctx.env.icon,
Some(number),
Some(ctx.env.display_winwidth),
ctx.matcher_builder(),
);
let cwd = ctx.cwd.clone();
let vim = ctx.vim.clone();
let stop_signal = stop_signal.clone();
std::thread::spawn(move || {
if let Err(e) = filter::par_dyn_run_inprocess(
&query,
filter_context,
match data_source {
DataSource::File(path) => ParallelSource::File(path),
DataSource::Command(command) => {
ParallelSource::Exec(Box::new(Exec::shell(command).cwd(cwd)))
}
},
VimProgressor::new(vim, stop_signal.clone()),
stop_signal,
) {
tracing::error!(error = ?e, "Error occured when filtering the cache source");
}
})
};
FilterControl {
stop_signal,
join_handle,
}
}
/// Generic provider impl.
#[derive(Debug)]
pub struct GenericProvider {
args: BaseArgs,
runtimepath: Option<String>,
maybe_filter_control: Option<FilterControl>,
current_results: Arc<Mutex<Vec<MatchedItem>>>,
last_filter_control_killed: Arc<AtomicBool>,
}
impl GenericProvider {
pub async fn new(ctx: &Context) -> Result<Self> {
let args = ctx.parse_provider_args().await?;
Ok(Self {
args,
runtimepath: None,
maybe_filter_control: None,
current_results: Arc::new(Mutex::new(Vec::new())),
last_filter_control_killed: Arc::new(AtomicBool::new(true)),
})
}
/// `lnum` is 1-based.
#[allow(unused)]
fn line_at(&self, lnum: usize) -> Option<String> {
self.current_results
.lock()
.get(lnum - 1)
.map(|r| r.item.output_text().to_string())
}
async fn nontypical_preview_target(
&mut self,
curline: &str,
ctx: &Context,
) -> Result<Option<PreviewTarget>> {
let maybe_preview_kind = match ctx.provider_id() {
"help_tags" => {
let runtimepath = match &self.runtimepath {
Some(rtp) => rtp.clone(),
None => {
let rtp: String = ctx.vim.eval("&runtimepath").await?;
self.runtimepath.replace(rtp.clone());
rtp
}
};
let items = curline.split('\t').collect::<Vec<_>>();
if items.len() < 2 {
return Err(anyhow::anyhow!(
"Couldn't extract subject and doc_filename from {curline}"
));
}
Some(PreviewTarget::HelpTags {
subject: items[0].trim().to_string(),
doc_filename: items[1].trim().to_string(),
runtimepath,
})
}
"buffers" => {
let res: [String; 2] = ctx
.vim
.bare_call("clap#provider#buffers#preview_target")
.await?;
let mut iter = res.into_iter();
let path = iter.next().expect("Element must exist").into();
let line_number = iter.next().expect("Element must exist").parse::<usize>()?;
Some(PreviewTarget::LineInFile { path, line_number })
}
_ => None,
};
Ok(maybe_preview_kind)
}
}
#[async_trait::async_trait]
impl ClapProvider for GenericProvider {
async fn on_initialize(&mut self, ctx: &mut Context) -> Result<()> {
let init_display = self.args.query.is_none();
// Always attempt to initialize the source
initialize_provider(ctx, init_display).await?;
ctx.handle_base_args(&self.args).await
}
async fn on_move(&mut self, ctx: &mut Context) -> Result<()> {
if !ctx.env.preview_enabled {
return Ok(());
}
let lnum = ctx.vim.display_getcurlnum().await?;
let curline = ctx.vim.display_getcurline().await?;
if curline.is_empty() {
tracing::debug!("Skipping preview as curline is empty");
return Ok(());
}
let preview_height = ctx.preview_height().await?;
let preview_impl =
if let Some(preview_target) = self.nontypical_preview_target(&curline, ctx).await? {
CachedPreviewImpl {
ctx,
preview_height,
preview_target,
cache_line: None,
}
} else {
CachedPreviewImpl::new(curline, preview_height, ctx)?
};
let (preview_target, preview) = preview_impl.get_preview().await?;
// Ensure the preview result is not out-dated.
let curlnum = ctx.vim.display_getcurlnum().await?;
if curlnum == lnum {
ctx.render_preview(preview)?;
}
ctx.preview_manager.set_preview_target(preview_target);
Ok(())
}
async fn on_typed(&mut self, ctx: &mut Context) -> Result<()> {
let query = ctx.vim.input_get().await?;
let small_list_response =
if let ProviderSource::Small { ref items, .. } = *ctx.provider_source.read() {
let matched_items = filter::par_filter_items(items, &ctx.matcher(&query));
let printer = Printer::new(ctx.env.display_winwidth, ctx.env.icon);
// Take the first 200 entries and add an icon to each of them.
let DisplayLines {
lines,
indices,
truncated_map,
icon_added,
} = printer.to_display_lines(matched_items.iter().take(200).cloned().collect());
let msg = json!({
"total": matched_items.len(),
"lines": lines,
"indices": indices,
"icon_added": icon_added,
"truncated_map": truncated_map,
});
Some((msg, matched_items))
} else {
None
};
if let Some((msg, matched_items)) = small_list_response {
let new_query = ctx.vim.input_get().await?;
if new_query == query {
ctx.vim
.exec("clap#state#process_filter_message", json!([msg, true]))?;
let mut current_results = self.current_results.lock();
*current_results = matched_items;
}
return Ok(());
}
let data_source = match *ctx.provider_source.read() {
ProviderSource::Small { .. } => unreachable!("Handled above; qed"),
ProviderSource::Initializing => {
ctx.vim
.echo_warn("Can not process query: source initialization is in progress")?;
ctx.initializing_prompt_echoed.store(true, Ordering::SeqCst);
return Ok(());
}
ProviderSource::Uninitialized => {
ctx.vim
.echo_warn("Can not process query: source uninitialized")?;
return Ok(());
}
ProviderSource::CachedFile { ref path, .. } | ProviderSource::File { ref path, .. } => {
DataSource::File(path.clone())
}
ProviderSource::Command(ref cmd) => DataSource::Command(cmd.to_string()),
};
if !self.last_filter_control_killed.load(Ordering::SeqCst) {
tracing::debug!(
?query,
"Still busy with killing the last filter control, return..."
);
return Ok(());
}
// Kill the last par_dyn_run job if exists.
if let Some(control) = self.maybe_filter_control.take() {
self.last_filter_control_killed
.store(false, Ordering::SeqCst);
let last_filter_control_killed = self.last_filter_control_killed.clone();
tokio::task::spawn_blocking(move || {
control.kill();
last_filter_control_killed.store(true, Ordering::SeqCst);
});
}
let display_winheight = ctx.env.display_winheight;
let new_control = start_filter_parallel(query, display_winheight, data_source, ctx);
self.maybe_filter_control.replace(new_control);
Ok(())
}
fn on_terminate(&mut self, ctx: &mut Context, session_id: u64) {
if let Some(control) = self.maybe_filter_control.take() {
// NOTE: The kill operation can not block current task.
tokio::task::spawn_blocking(move || control.kill());
}
ctx.signify_terminated(session_id);
}
}
|
// File: Rust built-in function checker
// Purpose: Take the input function name to match with built-in
// function of Rust that is recorded and return the cooresponding
// return type.
// Author : Ziling Zhou (802414)
#[derive(Debug,Clone)]
pub enum Ty{
Ref,
NonPrimitive,
Primitive
}
// Entry point of this file
// Take the function name and receiver, call the relative
// function depends on type of receiver in order to get the
// return type of tunction
pub fn get_func_rety( func_name : &str, var_ty : Option<Ty>) ->Ty{
if let Some(var_type) = var_ty{
match var_type {
Ty::Primitive => get_prim_func_rety(func_name),
Ty::NonPrimitive =>get_non_prim_func_rety(func_name),
Ty::Ref=>get_ref_func_rety(func_name),
}
} else {
get_call_rety(func_name)
}
}
// Return the return type of functions that have
// primitive receiver
fn get_prim_func_rety (func_name:&str) -> Ty {
match func_name {
"to_string" | "into_string" | "repeat" | "to_owned"
=> Ty::NonPrimitive,
_=>Ty::Primitive
}
}
// Return the return type of functions that have
// ref receiver
fn get_ref_func_rety(func_name:&str) -> Ty {
match func_name {
"to_string"| "into_string" | "repeat"|"to_owned"
=> Ty::NonPrimitive,
_=>Ty::Primitive
}
}
// Return the return type of functions that have
// non-primitive receiver
fn get_non_prim_func_rety(func_name:&str) -> Ty {
match func_name{
"split_off" => Ty::NonPrimitive,
"as_ref"=>Ty::Ref,
"is_empty"|"len" =>Ty::Primitive,
_=>Ty::NonPrimitive,
}
}
// Return the return type of functions that have
// do not have receiver
fn get_call_rety (func_name:&str) -> Ty{
match func_name {
"Stringfrom"|"Stringnew"|
"Stringwith_capacity"|"Stringfrom_utf16_lossy"|
"Stringfrom_raw_parts"|"Stringfrom_utf8_unchecked"
=> Ty::NonPrimitive,
"Stringeq"=>Ty::Primitive,
_ => Ty::NonPrimitive,
}
}
|
use std::error::Error;
use std::fmt;
use std::io::Error as IOError;
use std::string::FromUtf8Error;
use serde_json::error::Error as SerdeError;
#[cfg(not(feature = "no_dir_source"))]
use walkdir::Error as WalkdirError;
use crate::template::Parameter;
/// Error when rendering data on template.
#[derive(Debug)]
pub struct RenderError {
pub desc: String,
pub template_name: Option<String>,
pub line_no: Option<usize>,
pub column_no: Option<usize>,
cause: Option<Box<Error + Send + Sync>>,
}
impl fmt::Display for RenderError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match (self.line_no, self.column_no) {
(Some(line), Some(col)) => write!(
f,
"Error rendering \"{}\" line {}, col {}: {}",
self.template_name
.as_ref()
.unwrap_or(&"Unnamed template".to_owned(),),
line,
col,
self.desc
),
_ => write!(f, "{}", self.desc),
}
}
}
impl Error for RenderError {
fn description(&self) -> &str {
&self.desc[..]
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e as &Error)
}
}
impl From<IOError> for RenderError {
fn from(e: IOError) -> RenderError {
RenderError::with(e)
}
}
impl From<SerdeError> for RenderError {
fn from(e: SerdeError) -> RenderError {
RenderError::with(e)
}
}
impl From<FromUtf8Error> for RenderError {
fn from(e: FromUtf8Error) -> RenderError {
RenderError::with(e)
}
}
impl RenderError {
pub fn new<T: AsRef<str>>(desc: T) -> RenderError {
RenderError {
desc: desc.as_ref().to_owned(),
template_name: None,
line_no: None,
column_no: None,
cause: None,
}
}
pub fn strict_error(path: Option<&String>) -> RenderError {
let msg = match path {
Some(path) => format!("Variable {:?} not found in strict mode.", path),
None => "Value is missing in strict mode".to_owned(),
};
RenderError::new(&msg)
}
pub fn with<E>(cause: E) -> RenderError
where
E: Error + Send + Sync + 'static,
{
let mut e = RenderError::new(cause.description());
e.cause = Some(Box::new(cause));
e
}
}
quick_error! {
/// Template parsing error
#[derive(PartialEq, Debug, Clone)]
pub enum TemplateErrorReason {
MismatchingClosedHelper(open: String, closed: String) {
display("helper {:?} was opened, but {:?} is closing",
open, closed)
description("wrong name of closing helper")
}
MismatchingClosedDirective(open: Parameter, closed: Parameter) {
display("directive {:?} was opened, but {:?} is closing",
open, closed)
description("wrong name of closing directive")
}
InvalidSyntax {
display("invalid handlebars syntax.")
description("invalid handlebars syntax")
}
InvalidParam (param: String) {
display("invalid parameter {:?}", param)
description("invalid parameter")
}
NestedSubexpression {
display("nested subexpression is not supported")
description("nested subexpression is not supported")
}
}
}
/// Error on parsing template.
#[derive(Debug, PartialEq)]
pub struct TemplateError {
pub reason: TemplateErrorReason,
pub template_name: Option<String>,
pub line_no: Option<usize>,
pub column_no: Option<usize>,
segment: Option<String>,
}
impl TemplateError {
pub fn of(e: TemplateErrorReason) -> TemplateError {
TemplateError {
reason: e,
template_name: None,
line_no: None,
column_no: None,
segment: None,
}
}
pub fn at(mut self, template_str: &str, line_no: usize, column_no: usize) -> TemplateError {
self.line_no = Some(line_no);
self.column_no = Some(column_no);
self.segment = Some(template_segment(template_str, line_no, column_no));
self
}
pub fn in_template(mut self, name: String) -> TemplateError {
self.template_name = Some(name);
self
}
}
impl Error for TemplateError {
fn description(&self) -> &str {
self.reason.description()
}
}
fn template_segment(template_str: &str, line: usize, col: usize) -> String {
let range = 3;
let line_start = if line >= range { line - range } else { 0 };
let line_end = line + range;
let mut buf = String::new();
for (line_count, line_content) in template_str.lines().enumerate() {
if line_count >= line_start && line_count <= line_end {
buf.push_str(&format!("{:4} | {}\n", line_count, line_content));
if line_count == line - 1 {
buf.push_str(" |");
for c in 0..line_content.len() {
if c != col {
buf.push_str("-");
} else {
buf.push_str("^");
}
}
buf.push_str("\n");
}
}
}
buf
}
impl fmt::Display for TemplateError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match (self.line_no, self.column_no, &self.segment) {
(Some(line), Some(col), &Some(ref seg)) => writeln!(
f,
"Template error: {}\n --> Template error in \"{}\":{}:{}\n |\n{} |\n = reason: {}",
self.reason,
self.template_name
.as_ref()
.unwrap_or(&"Unnamed template".to_owned()),
line,
col,
seg,
self.reason
),
_ => write!(f, "{}", self.reason),
}
}
}
quick_error! {
#[derive(Debug)]
pub enum TemplateFileError {
TemplateError(err: TemplateError) {
from()
cause(err)
description(err.description())
display("{}", err)
}
IOError(err: IOError, name: String) {
cause(err)
description(err.description())
display("Template \"{}\": {}", name, err)
}
}
}
#[cfg(not(feature = "no_dir_source"))]
impl From<WalkdirError> for TemplateFileError {
fn from(error: WalkdirError) -> TemplateFileError {
let path_string: String = error
.path()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
TemplateFileError::IOError(IOError::from(error), path_string)
}
}
quick_error! {
#[derive(Debug)]
pub enum TemplateRenderError {
TemplateError(err: TemplateError) {
from()
cause(err)
description(err.description())
display("{}", err)
}
RenderError(err: RenderError) {
from()
cause(err)
description(err.description())
display("{}", err)
}
IOError(err: IOError, name: String) {
cause(err)
description(err.description())
display("Template \"{}\": {}", name, err)
}
}
}
impl TemplateRenderError {
pub fn as_render_error(&self) -> Option<&RenderError> {
if let TemplateRenderError::RenderError(ref e) = *self {
Some(&e)
} else {
None
}
}
}
|
pub mod airtime_tracker;
pub mod broadcaster;
pub mod chunk_stream;
pub mod clock_synchronizer;
pub mod command_util;
pub mod config;
pub mod datetime_ext;
pub mod eit_feeder;
pub mod epg;
pub mod error;
pub mod filter;
pub mod job;
pub mod models;
pub mod mpeg_ts_stream;
pub mod service_scanner;
pub mod string_table;
pub mod timeshift;
pub mod tracing_ext;
pub mod tuner;
pub mod web;
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use core::convert::TryFrom;
use failure::{err_msg, Error};
use fidl_fuchsia_ui_text as txt;
/// A version of txt::TextFieldState that does not have mandatory fields wrapped in Options.
/// It also implements Clone.
pub struct TextFieldState {
pub document: txt::Range,
pub selection: txt::Selection,
pub revision: u64,
pub composition: Option<txt::Range>,
pub composition_highlight: Option<txt::Range>,
pub dead_key_highlight: Option<txt::Range>,
}
impl Clone for TextFieldState {
fn clone(&self) -> Self {
TextFieldState {
document: clone_range(&self.document),
selection: txt::Selection {
range: clone_range(&self.selection.range),
anchor: self.selection.anchor,
affinity: self.selection.affinity,
},
revision: self.revision,
composition: self.composition.as_ref().map(clone_range),
composition_highlight: self.composition_highlight.as_ref().map(clone_range),
dead_key_highlight: self.dead_key_highlight.as_ref().map(clone_range),
}
}
}
impl TryFrom<txt::TextFieldState> for TextFieldState {
type Error = Error;
fn try_from(state: txt::TextFieldState) -> Result<Self, Self::Error> {
let txt::TextFieldState {
revision,
selection,
document,
composition,
composition_highlight,
dead_key_highlight,
} = state;
let document = match document {
Some(v) => v,
None => {
return Err(err_msg(format!("Expected document field to be set on TextFieldState")))
}
};
let selection = match selection {
Some(v) => v,
None => {
return Err(err_msg(format!(
"Expected selection field to be set on TextFieldState"
)))
}
};
let revision = match revision {
Some(v) => v,
None => {
return Err(err_msg(format!("Expected revision field to be set on TextFieldState")))
}
};
Ok(TextFieldState {
document,
selection,
revision,
composition,
composition_highlight,
dead_key_highlight,
})
}
}
impl Into<txt::TextFieldState> for TextFieldState {
fn into(self) -> txt::TextFieldState {
let TextFieldState {
revision,
selection,
document,
composition,
composition_highlight,
dead_key_highlight,
} = self;
txt::TextFieldState {
document: Some(document),
selection: Some(selection),
revision: Some(revision),
composition,
composition_highlight,
dead_key_highlight,
}
}
}
fn clone_range(range: &txt::Range) -> txt::Range {
txt::Range {
start: txt::Position { id: range.start.id },
end: txt::Position { id: range.end.id },
}
}
|
use rand::Rng;
use std::borrow::BorrowMut;
fn Initialize() -> u8 {
let mut rng = rand::thread_rng();
let num = rng.gen_range(32, 125);
num as u8
}
pub fn scamble_w_char_key<'a>(mut wcToScramble: &mut String, mut key : &mut String) -> (String, String) {
// let wc_key = Initialize();
let hexes = wcToScramble.as_bytes();
let mut output : Vec<u8> = Vec::new();
let mut wc_key : Vec<u8> = Vec::new();
for input in hexes.iter() {
wc_key.push(Initialize());
let mut x = input + *wc_key.last().unwrap();
if x > 126 {
let xtemp = x % 126;
x = xtemp;
output.push(x);
} else {
output.push(x);
}
//println!("{:?} {:?}\n", wc_key, wc_key.last().unwrap());
}
//*key = wc_key;
*key = String::from_utf8(wc_key).unwrap();
*wcToScramble = String::from_utf8(output).unwrap();
(wcToScramble.clone(), key.clone())
}
pub fn scamble_wkey<'a>(mut wcToScramble: &mut String, mut key : &mut u8) -> String {
// let wc_key = Initialize();
let hexes = wcToScramble.as_bytes();
let mut output : Vec<u8> = Vec::new();
let mut wc_key : Vec<u8> = Vec::new();
for input in hexes.iter() {
wc_key.push(Initialize());
let mut x = input + *key;
if x > 126 {
let xtemp = x % 126;
x = xtemp;
output.push(x);
//println!("[>126]Input:{} XOR Key:{} = {}",input, *key, x);
} else {
output.push(x);
//println!("[<126]Input:{} XOR Key:{} = {}",input, *key, x);
}
//*wcToScramble.insert( as usize, x);
//println!("{:?} {:?}\n", wc_key, wc_key.last().unwrap());
}
//*key = wc_key;
*wcToScramble = String::from_utf8(output).unwrap();
wcToScramble.clone()
}
pub fn Scramble<'a>(mut wcToScramble: &mut String, mut key : &mut u8) -> String {
let wc_key = Initialize();
let hexes = wcToScramble.as_bytes();
let mut output : Vec<u8> = Vec::new();
for input in hexes.iter() {
let mut x = input + wc_key;
if x > 126 {
let xtemp = x % 126;
x = xtemp;
output.push(x);
println!("[>126]Input:{} XOR Key:{} = {}",input, wc_key, x);
} else {
output.push(x);
println!("[<126]Input:{} XOR Key:{} = {}",input, wc_key, x);
}
//*wcToScramble.insert( as usize, x);
}
*key = wc_key;
*wcToScramble = String::from_utf8(output).unwrap();
wcToScramble.clone()
}
pub fn GenerateInsert(mut wcUnScramble: &mut String, key: &mut u8 ) {
let sImport = "Rusty-Marbles = {path = \"../Rusty_Marbles\"}";
let sInsert = format!("let mut {} = \
RMBL_CLASS_BUMP1D::uscrambled(String::from({:?}).borrow_mut(), {} )", "TestString", wcUnScramble.clone(), key.clone());
println!("{}", sInsert)
}
pub fn Generate_WCInsert(mut wcUnScramble: &mut String, key: &mut String ) {
let sImport = "Rusty-Marbles = {path = \"../Rusty_Marbles\"}";
let sInsert = format!("let mut {} = \
RMBL_CLASS_BUMP1D::uscramble_Wckey(String::from({:?}).borrow_mut(), {}.borrow_mut());", "TestString", wcUnScramble.clone(), key.clone());
println!("{}", sInsert)
} |
use super::*;
use std::sync::Arc;
use proptest::strategy::{BoxedStrategy, Just, Strategy};
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::charlist_to_string::charlist_to_string;
// `with_20_digits_is_the_same_as_float_to_list_1` in integration tests
// `returns_list_with_coefficient_e_exponent` in integration tests
#[test]
fn always_includes_e() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::float(arc_process.clone()),
digits(arc_process.clone()).prop_map(move |digits| {
arc_process.list_from_slice(&[arc_process.tuple_from_slice(&[tag(), digits])])
}),
)
},
|(arc_process, float, options)| {
let result = result(&arc_process, float, options);
prop_assert!(result.is_ok());
let list = result.unwrap();
let string: String = charlist_to_string(list).unwrap();
prop_assert!(string.contains('e'));
Ok(())
},
);
}
#[test]
fn always_includes_sign_of_exponent() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::float(arc_process.clone()),
digits(arc_process.clone()).prop_map(move |digits| {
arc_process.list_from_slice(&[arc_process.tuple_from_slice(&[tag(), digits])])
}),
)
},
|(arc_process, float, options)| {
let result = result(&arc_process, float, options);
prop_assert!(result.is_ok());
let list = result.unwrap();
let string: String = charlist_to_string(list).unwrap();
let part_vec: Vec<&str> = string.splitn(2, 'e').collect();
prop_assert_eq!(part_vec.len(), 2);
let sign = part_vec[1].chars().nth(0).unwrap();
prop_assert!(sign == '+' || sign == '-');
Ok(())
},
);
}
#[test]
fn exponent_is_at_least_2_digits() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::float(arc_process.clone()),
digits(arc_process.clone()).prop_map(move |digits| {
arc_process.list_from_slice(&[arc_process.tuple_from_slice(&[tag(), digits])])
}),
)
},
|(arc_process, float, options)| {
let result = result(&arc_process, float, options);
prop_assert!(result.is_ok());
let list = result.unwrap();
let string: String = charlist_to_string(list).unwrap();
let part_vec: Vec<&str> = string.splitn(2, 'e').collect();
prop_assert_eq!(part_vec.len(), 2);
prop_assert!(2 <= part_vec[1].chars().skip(1).count());
Ok(())
},
);
}
fn digits(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
(Just(arc_process.clone()), 0..=249)
.prop_map(|(arc_process, u)| arc_process.integer(u))
.boxed()
}
fn tag() -> Term {
Atom::str_to_term("scientific")
}
|
//! Tests auto-converted from "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes"
#[allow(unused)]
use super::rsass;
#[allow(unused)]
use rsass::precision;
/// From "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes/01_inline"
#[test]
fn t01_inline() {
assert_eq!(
rsass(
".result {\n output: \\\"\\\';\n output: #{\\\"\\\'};\n output: \"[#{\\\"\\\'}]\";\n output: \"#{\\\"\\\'}\";\n output: \'#{\\\"\\\'}\';\n output: \"[\'#{\\\"\\\'}\']\";\n}\n"
)
.unwrap(),
".result {\n output: \\\"\\\';\n output: \\\"\\\';\n output: \"[\\\\\\\"\\\\\']\";\n output: \"\\\\\\\"\\\\\'\";\n output: \"\\\\\\\"\\\\\'\";\n output: \"[\'\\\\\\\"\\\\\'\']\";\n}\n"
);
}
/// From "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes/02_variable"
#[test]
fn t02_variable() {
assert_eq!(
rsass(
"$input: \\\"\\\';\n.result {\n output: $input;\n output: #{$input};\n output: \"[#{$input}]\";\n output: \"#{$input}\";\n output: \'#{$input}\';\n output: \"[\'#{$input}\']\";\n}\n"
)
.unwrap(),
".result {\n output: \\\"\\\';\n output: \\\"\\\';\n output: \"[\\\\\\\"\\\\\']\";\n output: \"\\\\\\\"\\\\\'\";\n output: \"\\\\\\\"\\\\\'\";\n output: \"[\'\\\\\\\"\\\\\'\']\";\n}\n"
);
}
/// From "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes/03_inline_double"
#[test]
fn t03_inline_double() {
assert_eq!(
rsass(
".result {\n output: #{#{\\\"\\\'}};\n output: #{\"[#{\\\"\\\'}]\"};\n output: #{\"#{\\\"\\\'}\"};\n output: #{\'#{\\\"\\\'}\'};\n output: #{\"[\'#{\\\"\\\'}\']\"};\n}\n"
)
.unwrap(),
".result {\n output: \\\"\\\';\n output: [\\\"\\\'];\n output: \\\"\\\';\n output: \\\"\\\';\n output: [\'\\\"\\\'\'];\n}\n"
);
}
/// From "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes/04_variable_double"
#[test]
fn t04_variable_double() {
assert_eq!(
rsass(
"$input: \\\"\\\';\n.result {\n output: #{#{$input}};\n output: #{\"[#{$input}]\"};\n output: #{\"#{$input}\"};\n output: #{\'#{$input}\'};\n output: #{\"[\'#{$input}\']\"};\n}\n"
)
.unwrap(),
".result {\n output: \\\"\\\';\n output: [\\\"\\\'];\n output: \\\"\\\';\n output: \\\"\\\';\n output: [\'\\\"\\\'\'];\n}\n"
);
}
/// From "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes/05_variable_quoted_double"
#[test]
fn t05_variable_quoted_double() {
assert_eq!(
rsass(
"$input: \\\"\\\';\n.result {\n dquoted: \"#{#{$input}}\";\n dquoted: \"#{\"[#{$input}]\"}\";\n dquoted: \"#{\"#{$input}\"}\";\n dquoted: \"#{\'#{$input}\'}\";\n dquoted: \"#{\"[\'#{$input}\']\"}\";\n squoted: \'#{#{$input}}\';\n squoted: \'#{\"[#{$input}]\"}\';\n squoted: \'#{\"#{$input}\"}\';\n squoted: \'#{\'#{$input}\'}\';\n squoted: \'#{\"[\'#{$input}\']\"}\';\n}\n"
)
.unwrap(),
".result {\n dquoted: \"\\\\\\\"\\\\\'\";\n dquoted: \"[\\\\\\\"\\\\\']\";\n dquoted: \"\\\\\\\"\\\\\'\";\n dquoted: \"\\\\\\\"\\\\\'\";\n dquoted: \"[\'\\\\\\\"\\\\\'\']\";\n squoted: \"\\\\\\\"\\\\\'\";\n squoted: \"[\\\\\\\"\\\\\']\";\n squoted: \"\\\\\\\"\\\\\'\";\n squoted: \"\\\\\\\"\\\\\'\";\n squoted: \"[\'\\\\\\\"\\\\\'\']\";\n}\n"
);
}
/// From "sass-spec/spec/parser/interpolate/26_escaped_literal_quotes/06_escape_interpolation"
#[test]
fn t06_escape_interpolation() {
assert_eq!(
rsass(
"$input: \\\"\\\';\n.result {\n output: \"[\\#{\\\"\\\'}]\";\n output: \"\\#{\\\"\\\'}\";\n output: \'\\#{\\\"\\\'}\';\n output: \"[\'\\#{\\\"\\\'}\']\";\n}\n"
)
.unwrap(),
".result {\n output: \"[\\#{\\\"\\\'}]\";\n output: \"\\#{\\\"\\\'}\";\n output: \'\\#{\\\"\\\'}\';\n output: \"[\'\\#{\\\"\\\'}\']\";\n}\n"
);
}
|
extern crate fiemap;
use std::io::Error;
use std::env::args;
fn main() -> Result<(), Error> {
for f in args().skip(1) {
println!("{}:", f);
for fe in fiemap::fiemap(f)? {
println!(" {:?}", fe?);
}
}
Ok(())
}
|
//
// Author: Shareef Abdoul-Raheem
// File: sr.rs
//
pub mod lexer;
pub mod ast;
pub mod ast_processor;
pub mod c_api;
|
mod validate_position;
mod validate_move;
mod pawn_moves;
mod king_moves;
mod wrappers;
mod root;
pub use self::root::Position; |
use thiserror::Error;
use super::time::{Milliseconds, Monotonic};
#[derive(Debug, Error)]
#[error("invalid timeout value, must be `infinity` or a non-negative integer value")]
pub struct InvalidTimeoutError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Timeout {
Immediate,
Duration(Milliseconds),
Infinity,
}
impl Timeout {
pub fn from_millis<T: Into<isize>>(to: T) -> Result<Self, InvalidTimeoutError> {
match to.into() {
0 => Ok(Self::Immediate),
ms if ms >= 0 => Ok(Self::Duration(Milliseconds(ms as u64))),
_ => Err(InvalidTimeoutError),
}
}
}
impl Default for Timeout {
#[inline]
fn default() -> Self {
Self::Infinity
}
}
/// This is a more compact encoding of Timeout
///
/// * A value of 0 is Immediate
/// * A value of u64::MAX is infinity
/// * Any other value is the monotonic clock instant at which the timeout occurs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct ReceiveTimeout(u64);
impl ReceiveTimeout {
const IMMEDIATE: Self = Self(0);
const INFINITY: Self = Self(u64::MAX);
/// Creates a new absolute timeout from a monotonic clock
pub const fn absolute(value: Monotonic) -> Self {
Self(value.0)
}
/// Creates a new receive timeout based on the current monotonic clock and the given timeout
pub fn new(monotonic: Monotonic, timeout: Timeout) -> Self {
match timeout {
Timeout::Immediate => Self::IMMEDIATE,
Timeout::Infinity => Self::INFINITY,
Timeout::Duration(ms) => Self(monotonic.0 + ms.0),
}
}
/// Returns this timeout as a monotonic clock value, if applicable
pub const fn monotonic(self) -> Option<Monotonic> {
match self {
Self::IMMEDIATE | Self::INFINITY => None,
Self(value) => Some(Monotonic(value)),
}
}
/// Returns true if this timeout should be considered expired relative to the given monotonic clock time
pub fn is_timed_out(self, time: Monotonic) -> bool {
match self {
Self::IMMEDIATE => true,
Self::INFINITY => false,
Self(value) => value <= time.0,
}
}
}
impl Default for ReceiveTimeout {
#[inline(always)]
fn default() -> Self {
Self::INFINITY
}
}
|
use cw::{CVec, Range};
use dict::{Dict, PatternIter};
/// An iterator over all possibilities to fill one of the given ranges with a word from a set of
/// dictionaries.
pub struct WordRangeIter<'a> {
ranges: Vec<(Range, CVec)>,
dicts: &'a Vec<Dict>,
range_i: usize,
dict_i: usize,
pi: Option<PatternIter<'a>>,
}
impl<'a> WordRangeIter<'a> {
pub fn new(ranges: Vec<(Range, CVec)>, dicts: &'a Vec<Dict>) -> WordRangeIter<'a> {
WordRangeIter {
ranges: ranges,
dicts: dicts,
range_i: 0,
dict_i: 0,
pi: None,
}
}
#[inline]
fn get_word(&mut self) -> Option<CVec> {
match self.pi {
None => None,
Some(ref mut iter) => iter.next().cloned(),
}
}
fn advance(&mut self) -> bool {
if self.pi.is_some() {
self.range_i += 1;
if self.range_i >= self.ranges.len() {
self.range_i = 0;
self.dict_i += 1;
}
}
if let Some(&(_, ref pattern)) = self.ranges.get(self.range_i) {
self.pi = self.dicts.get(self.dict_i).map(|dict| dict.matching_words(pattern.clone()));
self.pi.is_some()
} else {
false
}
}
}
impl<'a> Iterator for WordRangeIter<'a> {
type Item = (Range, CVec);
fn next(&mut self) -> Option<(Range, CVec)> {
let mut oword = self.get_word();
while oword.is_none() && self.advance() {
oword = self.get_word();
}
oword.map(|word| {
let (range, _) = self.ranges[self.range_i];
(range, word)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use cw::{Dir, Point, Range};
use dict::Dict;
#[test]
fn test_range_iter() {
let point = Point::new(0, 0);
let ranges = vec!(
(Range { point: point, dir: Dir::Right, len: 6 }, "######".chars().collect()),
(Range { point: point, dir: Dir::Right, len: 3 }, "###".chars().collect()),
(Range { point: point, dir: Dir::Right, len: 2 }, "##".chars().collect()),
);
let dicts = vec!(
Dict::new(vec!("FAV".chars().collect(),
"TOOLONG".chars().collect()).iter()),
Dict::new(vec!("YO".chars().collect(),
"FOO".chars().collect(),
"FOOBAR".chars().collect()).iter()),
);
let mut iter = WordRangeIter::new(ranges.clone(), &dicts);
assert_eq!(Some((ranges[1].0, "FAV".chars().collect())), iter.next());
assert_eq!(Some((ranges[0].0, "FOOBAR".chars().collect())), iter.next());
assert_eq!(Some((ranges[1].0, "FOO".chars().collect())), iter.next());
assert_eq!(Some((ranges[2].0, "YO".chars().collect())), iter.next());
}
}
|
extern crate libc;
use libc::{c_void, c_int, c_char, c_float, c_ushort};//, c_ulong, c_long, c_uint, c_uchar, size_t};
pub type RustCb = extern fn(data : *mut c_void);
#[repr(C)]
pub struct wl_display;
#[repr(C)]
pub struct wl_client;
#[repr(C)]
pub struct wl_event_loop;
#[repr(C)]
pub struct wl_signal;
#[repr(C)]
pub struct Signals;
extern "C" {
pub fn wl_display_create() -> *const wl_display;
pub fn wl_client_create(display : *const wl_display, fd : c_int) -> *const wl_client;
pub fn wl_display_run(display : *const wl_display);
pub fn wl_display_destroy(display : *const wl_display);
pub fn wl_display_add_socket(display : *const wl_display, name : *const c_char) -> c_int;
pub fn wl_display_add_socket_auto(display : *const wl_display) -> *const c_char;
pub fn wl_display_get_event_loop(display : *const wl_display) -> *const wl_event_loop;
pub fn wl_signal_init(signal : *const wl_signal);
pub fn wl_display_init_shm(display : *const wl_display);
pub fn create_signals() -> *const Signals;
pub fn init_tmp(display : *const wl_display);
}
extern "C" {
pub fn main_wlc() -> c_int;
}
|
use std::{collections::hash_map::HashMap, str::from_utf8};
use strum_macros::FromRepr;
use crate::VEError;
// Data types
type Watt = i32;
type Percent = f32;
type Volt = f32;
type Ampere = f32;
type Minute = i32;
type KiloWattHours = i32;
// Type conversion errors
impl From<std::num::ParseIntError> for VEError {
fn from(src: std::num::ParseIntError) -> VEError {
VEError::Parse(format!("Error parsing integer: {}", src))
}
}
impl From<std::num::ParseFloatError> for VEError {
fn from(src: std::num::ParseFloatError) -> VEError {
VEError::Parse(format!("Error parsing float: {}", src))
}
}
#[derive(FromRepr, PartialEq, Eq, Debug)]
pub enum OffReason {
None = 0x0,
NoInputPower = 0x00000001,
SwitchedOffPowerSwitch = 0x00000002,
SwitchedOffDMR = 0x00000004,
RemoteInput = 0x00000008,
ProtectionActive = 0x000000010,
Paygo = 0x00000020,
BMS = 0x000000040,
EngineShutdownDetection = 0x00000080,
AnalysingInputVoltage = 0x000000100,
}
#[derive(FromRepr, PartialEq, Eq, Debug)]
pub enum TrackerOperationMode {
Off = 0,
VoltageOrCurrentLimited = 1,
MPPTrackerActive = 2,
}
#[derive(FromRepr, PartialEq, Eq, Debug)]
pub enum ErrorCode {
NoError = 0,
BatteryVoltageTooHigh = 2,
ChargerTemperatureTooHigh = 17,
ChargerOverCurrent = 18,
ChargerCurrentReversed = 19,
BulkTimeLimitExceeded = 20,
CurrentSensorIssue = 21,
TerminalsOverheatd = 26,
ConverterIssue = 28,
InputVoltageTooHigh = 33,
InputCurrentTooHigh = 34,
InputShutdownBatVoltage = 38,
InputShutdownCurrentFlow = 39,
LostComWithDevices = 65,
SynchronisedChargingIssue = 66,
BMSConnectionLost = 67,
NetworkMisconfigured = 68,
FactoryCalibrationDataLost = 116,
InvalidFirmware = 117,
UserSettingsInvalid = 119,
}
#[derive(FromRepr, PartialEq, Eq, Debug)]
pub enum StateOfOperation {
Off = 0,
LowPower = 1,
Fault = 2,
Bulk = 3,
Absorption = 4,
Float = 5,
Storage = 6,
Equalize = 7,
Inverting = 9,
PowerSupply = 11,
StartingUp = 245,
RepeatedAbsorption = 246,
AutoEqualize = 247,
BatterySafe = 248,
ExternalControl = 252,
}
pub trait VEDirectData {
fn fill(fields: &HashMap<String, Vec<u8>>) -> Result<Self, VEError>
where
Self: Sized;
}
/// Data for BMV 600 battery monitor series
// struct Bmv600 {}
/// Data for BMV 700 battery monitor series
#[derive(Debug)]
pub struct Bmv700 {
/// Main (channel 1) battery voltage. Labelled `V`
/// Units: V
/// Available on: BMV 600, BMV 700, MPPT, Inverter
pub voltage: Volt,
/// Instantaneous power. Labelled `P`
/// Units: W
/// Available on: BMV 700
pub power: Watt,
/// Consumed Amp Hours. Labelled `CE`
/// Units: mAh (When the BMV is not synchronised, these statistics have no meaning, so "---" will be sent instead of a value)
pub consumed: Option<String>,
/// State of charge. Labelled `SOC`
/// Unit: Percent (When the BMV is not synchronised, these statistics have no meaning, so "---" will be sent instead of a value)
/// Available on: BMV 600, BMV 700
pub soc: Option<Percent>,
/// Time-to-go. Labelled `TTG`
/// Units: Minutes (When the battery is not discharging the time-to-go is infinite. This is represented as -1)
/// Available on: BMV 600, BMV 700
pub ttg: Minute,
}
impl VEDirectData for Bmv700 {
fn fill(fields: &HashMap<String, Vec<u8>>) -> Result<Self, VEError> {
Ok(Bmv700 {
voltage: convert_volt(fields, "V", 10.0)?,
power: convert_watt(fields, "P")?,
consumed: Some(convert_string(fields, "CE")?),
soc: convert_percentage(fields, "SOC")?,
ttg: convert_ttg(fields, "TTG")?,
})
}
}
/// Data for all MPPT solar charge controller
#[derive(Debug)]
pub struct MPPT {
pub channel1_voltage: Volt,
pub panel_voltage: Volt,
pub panel_power: Watt,
pub battery_current: Ampere,
pub load_current: Ampere,
pub load_output_state: bool,
pub relay_state: Option<bool>,
pub off_reason: OffReason,
pub yield_total: KiloWattHours,
pub yield_today: KiloWattHours,
pub max_power_today: Watt,
pub yield_yesterday: KiloWattHours,
pub max_power_yesterday: Watt,
pub error_code: ErrorCode,
pub state_of_operation: StateOfOperation,
pub firmware: u16,
pub product_id: String,
pub serial_number: String,
pub day_sequence: u16,
pub tracker_mode: TrackerOperationMode,
}
impl VEDirectData for MPPT {
fn fill(fields: &HashMap<String, Vec<u8>>) -> Result<Self, VEError> {
Ok(MPPT {
channel1_voltage: convert_volt(fields, "V", 1000.0)?,
panel_voltage: convert_volt(fields, "VPV", 1000.0)?,
panel_power: convert_watt(fields, "PPV")?,
battery_current: convert_ampere(fields, "I", 1000.0)?,
load_current: convert_ampere(fields, "IL", 1000.0)?,
load_output_state: convert_bool(fields, "LOAD")?,
relay_state: if fields.contains_key("Relay") {
Some(convert_bool(fields, "Relay")?)
} else {
None
},
off_reason: convert_off_reason(fields, "OR")?,
yield_total: convert_watt(fields, "H19")?,
yield_today: convert_watt(fields, "H20")?,
max_power_today: convert_watt(fields, "H21")?,
yield_yesterday: convert_watt(fields, "H22")?,
max_power_yesterday: convert_watt(fields, "H23")?,
error_code: convert_error_code(fields, "ERR")?,
state_of_operation: convert_state_of_operation(fields, "CS")?,
firmware: convert_u16(fields, "FW")?,
product_id: convert_string(fields, "PID")?,
serial_number: convert_string(fields, "SER#")?,
day_sequence: convert_u16(fields, "HSDS")?,
tracker_mode: convert_tracker_mode(fields, "MPPT")?,
})
}
}
/// Data for Phoenix Inverters
// struct PhoenixInverter {}
/// Data for Phoenix Chargers
// struct PhoenixCharger {}
/// Data for all devices
// pub struct Everything {}
/// "When the BMV is not synchronised, these statistics have no meaning, so "---" will be sent instead of a value"
fn convert_percentage(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
) -> Result<Option<Percent>, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let s = from_utf8(raw).map_err(|e| {
VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e))
})?;
if s == "---" {
Ok(None)
} else {
Ok(Some(s.parse::<Percent>()? / 10.0))
}
}
fn convert_volt(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
factor: f32,
) -> Result<Volt, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<Volt>()?
/ factor;
Ok(cleaned)
}
fn convert_ampere(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
factor: f32,
) -> Result<Ampere, VEError> {
let raw = (*rawkeys)
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<Ampere>()?
/ factor;
Ok(cleaned)
}
fn convert_watt(rawkeys: &HashMap<String, Vec<u8>>, label: &str) -> Result<Watt, VEError> {
let raw = (*rawkeys)
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<Watt>()?;
Ok(cleaned)
}
fn convert_u16(rawkeys: &HashMap<String, Vec<u8>>, label: &str) -> Result<u16, VEError> {
let raw = (*rawkeys)
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<u16>()?;
Ok(cleaned)
}
fn convert_string(rawkeys: &HashMap<String, Vec<u8>>, label: &str) -> Result<String, VEError> {
let raw = &*rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
String::from_utf8(raw.clone())
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))
}
fn convert_bool(rawkeys: &HashMap<String, Vec<u8>>, label: &str) -> Result<bool, VEError> {
let raw = &*rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let s = from_utf8(raw).map_err(|e| {
VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e))
})?;
if s == "ON" {
Ok(true)
} else if s == "OFF" {
Ok(false)
} else {
Err(VEError::OnOffExpected(String::from(s)))
}
}
fn convert_ttg(rawkeys: &HashMap<String, Vec<u8>>, label: &str) -> Result<Minute, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<Minute>()?;
Ok(cleaned)
}
fn convert_error_code(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
) -> Result<ErrorCode, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<usize>()?;
Ok(ErrorCode::from_repr(cleaned).unwrap_or(ErrorCode::NoError))
}
fn convert_off_reason(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
) -> Result<OffReason, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw).map_err(|e| {
VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e))
})?;
match cleaned {
"0x00000000" => Ok(OffReason::None),
"0x00000001" => Ok(OffReason::NoInputPower),
"0x00000002" => Ok(OffReason::SwitchedOffPowerSwitch),
"0x00000004" => Ok(OffReason::SwitchedOffDMR),
"0x00000008" => Ok(OffReason::RemoteInput),
"0x00000010" => Ok(OffReason::ProtectionActive),
"0x00000020" => Ok(OffReason::Paygo),
"0x00000040" => Ok(OffReason::BMS),
"0x00000080" => Ok(OffReason::EngineShutdownDetection),
"0x00000100" => Ok(OffReason::AnalysingInputVoltage),
_ => Err(VEError::UnknownCode(cleaned.to_string())),
}
}
fn convert_state_of_operation(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
) -> Result<StateOfOperation, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<usize>()?;
Ok(StateOfOperation::from_repr(cleaned).unwrap_or(StateOfOperation::Off))
}
fn convert_tracker_mode(
rawkeys: &HashMap<String, Vec<u8>>,
label: &str,
) -> Result<TrackerOperationMode, VEError> {
let raw = rawkeys
.get(label)
.ok_or_else(|| VEError::MissingField(label.into()))?;
let cleaned = from_utf8(raw)
.map_err(|e| VEError::Parse(format!("Failed to parse {} from {:?} - {}", label, &raw, e)))?
.parse::<usize>()?;
Ok(TrackerOperationMode::from_repr(cleaned).unwrap_or(TrackerOperationMode::Off))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Events;
struct CheckerBmv700 {
block_count: usize,
}
impl Events<Bmv700> for CheckerBmv700 {
fn on_complete_block(&mut self, data: Bmv700) {
self.block_count += 1;
assert_eq!(data.power, 123);
assert_eq!(data.consumed, Some("53".into()));
assert_eq!(data.soc, Some(45.2));
assert_eq!(data.ttg, 60);
assert_eq!(data.voltage, 23.2);
}
fn on_parse_error(&mut self, _error: VEError, _parse_buf: &[u8]) {
assert!(false);
}
}
#[test]
fn test_mapping() {
let input = "\r\nP\t123\r\nCE\t53\r\nSOC\t452\r\nTTG\t60\r\nRelay\tOFF\r\nAlarm\tOFF\r\nV\t232\r\nChecksum\t12";
let mut checker = CheckerBmv700 { block_count: 0 };
let mut parser = crate::Parser::new(&mut checker);
parser.feed(input.as_bytes()).unwrap();
assert_eq!(checker.block_count, 1);
}
struct CheckerMPPT {
block_count: usize,
}
impl Events<MPPT> for CheckerMPPT {
fn on_complete_block(&mut self, data: MPPT) {
self.block_count += 1;
assert_eq!(data.channel1_voltage, 12.54);
assert_eq!(data.battery_current, 0.04);
assert_eq!(data.panel_voltage, 18.54);
assert_eq!(data.panel_power, 5);
assert_eq!(data.load_current, 0.3);
assert_eq!(data.load_output_state, true);
assert_eq!(data.yield_total, 144);
assert_eq!(data.yield_today, 1);
assert_eq!(data.yield_yesterday, 4);
assert_eq!(data.max_power_today, 6);
assert_eq!(data.max_power_yesterday, 14);
assert_eq!(data.day_sequence, 16);
assert_eq!(data.firmware, 159);
assert_eq!(data.tracker_mode, TrackerOperationMode::MPPTrackerActive);
}
fn on_parse_error(&mut self, _error: VEError, _parse_buf: &[u8]) {
assert!(false);
}
}
#[test]
fn test_mapping_mppt() {
let input = "\r\nPID\t0xA053\r\nFW\t159\r\nSER#\tHQ2132QY2KR\r\nV\t12540\r\nI\t40\r\nVPV\t18540\r\nPPV\t5\r\nCS\t3\r\nMPPT\t2\r\nOR\t0x00000000\r\nERR\t0\r\nLOAD\tON\r\nIL\t300\r\nH19\t144\r\nH20\t1\r\nH21\t6\r\nH22\t4\r\nH23\t14\r\nHSDS\t16\r\nChecksum\t?";
let mut checker = CheckerMPPT { block_count: 0 };
let mut parser = crate::Parser::new(&mut checker);
parser.feed(input.as_bytes()).unwrap();
assert_eq!(checker.block_count, 1);
}
}
|
use std::error::Error as StdError;
use futures::{Future, IntoFuture};
use body::Payload;
use super::{MakeService, Service};
/// An asynchronous constructor of `Service`s.
pub trait NewService {
/// The `Payload` body of the `http::Request`.
type ReqBody: Payload;
/// The `Payload` body of the `http::Response`.
type ResBody: Payload;
/// The error type that can be returned by `Service`s.
type Error: Into<Box<StdError + Send + Sync>>;
/// The resolved `Service` from `new_service()`.
type Service: Service<
ReqBody=Self::ReqBody,
ResBody=Self::ResBody,
Error=Self::Error,
>;
/// The future returned from `new_service` of a `Service`.
type Future: Future<Item=Self::Service, Error=Self::InitError>;
/// The error type that can be returned when creating a new `Service`.
type InitError: Into<Box<StdError + Send + Sync>>;
/// Create a new `Service`.
fn new_service(&self) -> Self::Future;
}
impl<F, R, S> NewService for F
where
F: Fn() -> R,
R: IntoFuture<Item=S>,
R::Error: Into<Box<StdError + Send + Sync>>,
S: Service,
{
type ReqBody = S::ReqBody;
type ResBody = S::ResBody;
type Error = S::Error;
type Service = S;
type Future = R::Future;
type InitError = R::Error;
fn new_service(&self) -> Self::Future {
(*self)().into_future()
}
}
impl<N, Ctx> MakeService<Ctx> for N
where
N: NewService,
{
type ReqBody = N::ReqBody;
type ResBody = N::ResBody;
type Error = N::Error;
type Service = N::Service;
type Future = N::Future;
type MakeError = N::InitError;
fn make_service(&mut self, _: Ctx) -> Self::Future {
self.new_service()
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_catalog::table_context::TableContext;
use crate::optimizer::PhysicalProperty;
use crate::optimizer::RelExpr;
use crate::optimizer::RelationalProperty;
use crate::optimizer::RequiredProperty;
use crate::plans::Operator;
use crate::plans::RelOp;
use crate::IndexType;
use crate::ScalarExpr;
/// An item of set-returning function.
/// Contains definition of srf and its output columns.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SrfItem {
pub scalar: ScalarExpr,
// pub srf_name: String,
// pub args: Vec<ScalarExpr>,
pub index: IndexType,
}
/// `ProjectSet` is a plan that evaluate a series of
/// set-returning functions, zip the result together,
/// and return the joined result with input relation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProjectSet {
pub srfs: Vec<SrfItem>,
}
impl Operator for ProjectSet {
fn rel_op(&self) -> RelOp {
RelOp::ProjectSet
}
fn derive_relational_prop(
&self,
rel_expr: &RelExpr,
) -> common_exception::Result<RelationalProperty> {
let mut child_prop = rel_expr.derive_relational_prop_child(0)?;
for srf in &self.srfs {
child_prop.output_columns.insert(srf.index);
}
Ok(child_prop)
}
fn derive_physical_prop(
&self,
rel_expr: &RelExpr,
) -> common_exception::Result<PhysicalProperty> {
rel_expr.derive_physical_prop_child(0)
}
fn compute_required_prop_child(
&self,
_ctx: Arc<dyn TableContext>,
_rel_expr: &RelExpr,
_child_index: usize,
required: &RequiredProperty,
) -> common_exception::Result<RequiredProperty> {
Ok(required.clone())
}
}
|
//! Types and traits for implementing query plans.
use std::collections::HashSet;
use std::ops::Deref;
use std::sync::atomic::{self, AtomicUsize};
use timely::dataflow::scopes::child::Iterative;
use timely::dataflow::Scope;
use timely::progress::Timestamp;
use differential_dataflow::lattice::Lattice;
use crate::binding::{AsBinding, AttributeBinding, Binding};
use crate::domain::Domain;
use crate::timestamp::Rewind;
use crate::{AsAid, Eid, Value, Var};
use crate::{CollectionRelation, Implemented, Relation, ShutdownHandle, VariableMap};
#[cfg(feature = "set-semantics")]
pub mod aggregate;
#[cfg(not(feature = "set-semantics"))]
pub mod aggregate_neu;
pub mod antijoin;
pub mod filter;
#[cfg(feature = "graphql")]
pub mod graphql;
// #[cfg(feature = "graphql")]
// pub mod graphql_v2;
pub mod hector;
pub mod join;
pub mod project;
pub mod pull;
// pub mod pull_v2;
pub mod transform;
pub mod union;
#[cfg(feature = "set-semantics")]
pub use self::aggregate::{Aggregate, AggregationFn};
#[cfg(not(feature = "set-semantics"))]
pub use self::aggregate_neu::{Aggregate, AggregationFn};
pub use self::antijoin::Antijoin;
pub use self::filter::{Filter, Predicate};
#[cfg(feature = "graphql")]
pub use self::graphql::GraphQl;
pub use self::hector::Hector;
pub use self::join::Join;
pub use self::project::Project;
pub use self::pull::{Pull, PullAll, PullLevel};
pub use self::transform::{Function, Transform};
pub use self::union::Union;
static SYM: AtomicUsize = AtomicUsize::new(std::usize::MAX);
/// @FIXME
pub fn gensym() -> Var {
SYM.fetch_sub(1, atomic::Ordering::SeqCst) as Var
}
/// Description of everything a plan needs prior to synthesis.
pub struct Dependencies<A: AsAid> {
/// NameExpr's used by this plan.
pub names: HashSet<A>,
/// Attributes queries in Match* expressions.
pub attributes: HashSet<A>,
}
impl<A: AsAid> Dependencies<A> {
/// A description representing a dependency on nothing.
pub fn none() -> Self {
Dependencies {
names: HashSet::new(),
attributes: HashSet::new(),
}
}
/// A description representing a dependency on a single name.
pub fn name(name: A) -> Self {
let mut names = HashSet::new();
names.insert(name);
Dependencies {
names,
attributes: HashSet::new(),
}
}
/// A description representing a dependency on a single attribute.
pub fn attribute(aid: A) -> Self {
let mut attributes = HashSet::new();
attributes.insert(aid);
Dependencies {
names: HashSet::new(),
attributes,
}
}
}
impl<A: AsAid> std::ops::AddAssign for Dependencies<A> {
fn add_assign(&mut self, other: Self) {
// Merges two dependency descriptions into one, representing
// their union.
self.names.extend(other.names.into_iter());
self.attributes.extend(other.attributes.into_iter());
}
}
impl<A: AsAid> std::ops::Add for Dependencies<A> {
type Output = Self;
fn add(self, other: Self) -> Self {
let mut merged = self;
merged += other;
merged
}
}
impl<A: AsAid> std::iter::Sum<Dependencies<A>> for Dependencies<A> {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::none(), |sum, x| sum + x)
}
}
/// A type that can be implemented as a simple relation.
pub trait Implementable {
/// The type that is used to represent attributes uniquely.
type A: AsAid;
/// Returns names of any other implementable things that need to
/// be available before implementing this one. Attributes are not
/// mentioned explicitley as dependencies.
fn dependencies(&self) -> Dependencies<Self::A>;
/// Transforms an implementable into an equivalent set of bindings
/// that can be unified by Hector.
fn into_bindings(&self) -> Vec<Binding<Self::A>> {
panic!("This plan can't be implemented via Hector.");
}
/// Implements the type as a simple relation.
fn implement<'b, S>(
&self,
nested: &mut Iterative<'b, S, u64>,
domain: &mut Domain<Self::A, S::Timestamp>,
local_arrangements: &VariableMap<Self::A, Iterative<'b, S, u64>>,
) -> (Implemented<'b, Self::A, S>, ShutdownHandle)
where
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind;
}
/// Possible query plan types.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub enum Plan<A: AsAid> {
/// Projection
Project(Project<Plan<A>>),
/// Aggregation
Aggregate(Aggregate<Plan<A>>),
/// Union
Union(Union<Plan<A>>),
/// Equijoin
Join(Join<Plan<A>, Plan<A>>),
/// WCO
Hector(Hector<A>),
/// Antijoin
Antijoin(Antijoin<Plan<A>, Plan<A>>),
/// Negation
Negate(Box<Plan<A>>),
/// Filters bindings by one of the built-in predicates
Filter(Filter<Plan<A>>),
/// Transforms a binding by a function expression
Transform(Transform<Plan<A>>),
/// Data pattern of the form [?e a ?v]
MatchA(Var, A, Var),
/// Data pattern of the form [e a ?v]
MatchEA(Eid, A, Var),
/// Data pattern of the form [?e a v]
MatchAV(Var, A, Value),
/// Sources data from another relation.
NameExpr(Vec<Var>, A),
/// Pull expression
Pull(Pull<Plan<A>>),
/// Single-level pull expression
PullLevel(PullLevel<A, Plan<A>>),
/// Single-level pull expression
PullAll(PullAll<A>),
/// GraphQl pull expression
#[cfg(feature = "graphql")]
GraphQl(GraphQl<A>),
}
impl<A: AsAid> Plan<A> {
/// Returns a plan expressing a base data pattern.
pub fn match_a<X: Into<A>>(e: Var, a: X, v: Var) -> Self {
Plan::MatchA(e, a.into(), v)
}
/// Returns a plan expressing a base data pattern.
pub fn match_ea<AX: Into<A>>(e: Eid, a: AX, v: Var) -> Self {
Plan::MatchEA(e, a.into(), v)
}
/// Returns a plan expressing a base data pattern.
pub fn match_av<AX: Into<A>, VX: Into<Value>>(e: Var, a: AX, v: VX) -> Self {
Plan::MatchAV(e, a.into(), v.into())
}
/// Returns the variables bound by this plan.
pub fn variables(&self) -> Vec<Var> {
match *self {
Plan::Project(ref projection) => projection.variables.clone(),
Plan::Aggregate(ref aggregate) => aggregate.variables.clone(),
Plan::Union(ref union) => union.variables.clone(),
Plan::Join(ref join) => join.variables.clone(),
Plan::Hector(ref hector) => hector.variables.clone(),
Plan::Antijoin(ref antijoin) => antijoin.variables.clone(),
Plan::Negate(ref plan) => plan.variables(),
Plan::Filter(ref filter) => filter.variables.clone(),
Plan::Transform(ref transform) => transform.variables.clone(),
Plan::MatchA(e, _, v) => vec![e, v],
Plan::MatchEA(_, _, v) => vec![v],
Plan::MatchAV(e, _, _) => vec![e],
Plan::NameExpr(ref variables, ref _name) => variables.clone(),
Plan::Pull(ref pull) => pull.variables.clone(),
Plan::PullLevel(ref path) => path.variables.clone(),
Plan::PullAll(ref path) => path.variables.clone(),
#[cfg(feature = "graphql")]
Plan::GraphQl(_) => unimplemented!(),
}
}
}
impl<A> Implementable for Plan<A>
where
A: AsAid,
{
type A = A;
fn dependencies(&self) -> Dependencies<A> {
// @TODO provide a general fold for plans
match *self {
Plan::Project(ref projection) => projection.dependencies(),
Plan::Aggregate(ref aggregate) => aggregate.dependencies(),
Plan::Union(ref union) => union.dependencies(),
Plan::Join(ref join) => join.dependencies(),
Plan::Hector(ref hector) => hector.dependencies(),
Plan::Antijoin(ref antijoin) => antijoin.dependencies(),
Plan::Negate(ref plan) => plan.dependencies(),
Plan::Filter(ref filter) => filter.dependencies(),
Plan::Transform(ref transform) => transform.dependencies(),
Plan::MatchA(_, ref a, _) => Dependencies::attribute(a.clone()),
Plan::MatchEA(_, ref a, _) => Dependencies::attribute(a.clone()),
Plan::MatchAV(_, ref a, _) => Dependencies::attribute(a.clone()),
Plan::NameExpr(_, ref name) => Dependencies::name(name.clone()),
Plan::Pull(ref pull) => pull.dependencies(),
Plan::PullLevel(ref path) => path.dependencies(),
Plan::PullAll(ref path) => path.dependencies(),
#[cfg(feature = "graphql")]
Plan::GraphQl(ref q) => q.dependencies(),
}
}
fn into_bindings(&self) -> Vec<Binding<Self::A>> {
// @TODO provide a general fold for plans
match *self {
Plan::Project(ref projection) => projection.into_bindings(),
Plan::Aggregate(ref aggregate) => aggregate.into_bindings(),
Plan::Union(ref union) => union.into_bindings(),
Plan::Join(ref join) => join.into_bindings(),
Plan::Hector(ref hector) => hector.into_bindings(),
Plan::Antijoin(ref antijoin) => antijoin.into_bindings(),
Plan::Negate(ref plan) => plan.into_bindings(),
Plan::Filter(ref filter) => filter.into_bindings(),
Plan::Transform(ref transform) => transform.into_bindings(),
Plan::MatchA(e, ref a, v) => vec![Binding::attribute(e, a.clone(), v)],
Plan::MatchEA(match_e, ref a, v) => {
let e = gensym();
vec![
Binding::attribute(e, a.clone(), v),
Binding::constant(e, Value::Eid(match_e)),
]
}
Plan::MatchAV(e, ref a, ref match_v) => {
let v = gensym();
vec![
Binding::attribute(e, a.clone(), v),
Binding::constant(v, match_v.clone()),
]
}
Plan::NameExpr(_, ref _name) => unimplemented!(), // @TODO hmm...
Plan::Pull(ref pull) => pull.into_bindings(),
Plan::PullLevel(ref path) => path.into_bindings(),
Plan::PullAll(ref path) => path.into_bindings(),
#[cfg(feature = "graphql")]
Plan::GraphQl(ref q) => q.into_bindings(),
}
}
fn implement<'b, S>(
&self,
nested: &mut Iterative<'b, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
local_arrangements: &VariableMap<Self::A, Iterative<'b, S, u64>>,
) -> (Implemented<'b, Self::A, S>, ShutdownHandle)
where
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind,
{
match *self {
Plan::Project(ref projection) => {
projection.implement(nested, domain, local_arrangements)
}
Plan::Aggregate(ref aggregate) => {
aggregate.implement(nested, domain, local_arrangements)
}
Plan::Union(ref union) => union.implement(nested, domain, local_arrangements),
Plan::Join(ref join) => join.implement(nested, domain, local_arrangements),
Plan::Hector(ref hector) => hector.implement(nested, domain, local_arrangements),
Plan::Antijoin(ref antijoin) => antijoin.implement(nested, domain, local_arrangements),
Plan::Negate(ref plan) => {
let (relation, mut shutdown_handle) =
plan.implement(nested, domain, local_arrangements);
let variables = relation.variables();
let tuples = {
let (projected, shutdown) = relation.projected(nested, domain, &variables);
shutdown_handle.merge_with(shutdown);
projected.negate()
};
(
Implemented::Collection(CollectionRelation { variables, tuples }),
shutdown_handle,
)
}
Plan::Filter(ref filter) => filter.implement(nested, domain, local_arrangements),
Plan::Transform(ref transform) => {
transform.implement(nested, domain, local_arrangements)
}
Plan::MatchA(e, ref a, v) => {
let binding = AttributeBinding {
variables: (e, v),
source_attribute: a.clone(),
};
(Implemented::Attribute(binding), ShutdownHandle::empty())
}
Plan::MatchEA(match_e, ref a, sym1) => {
let (tuples, shutdown_propose) = match domain.forward_propose(a) {
None => panic!("attribute {:?} does not exist", a),
Some(propose_trace) => {
let (propose, shutdown_propose) = propose_trace
.import_frontier(&nested.parent, &format!("Propose({:?})", a));
let tuples = propose
.enter(nested)
.filter(move |e, _v| *e == Value::Eid(match_e))
.as_collection(|_e, v| vec![v.clone()]);
(tuples, shutdown_propose)
}
};
let relation = CollectionRelation {
variables: vec![sym1],
tuples,
};
(
Implemented::Collection(relation),
ShutdownHandle::from_button(shutdown_propose),
)
}
Plan::MatchAV(sym1, ref a, ref match_v) => {
let (tuples, shutdown_propose) = match domain.forward_propose(a) {
None => panic!("attribute {:?} does not exist", a),
Some(propose_trace) => {
let match_v = match_v.clone();
let (propose, shutdown_propose) = propose_trace
.import_frontier(&nested.parent, &format!("Propose({:?})", a));
let tuples = propose
.enter(nested)
.filter(move |_e, v| *v == match_v)
.as_collection(|e, _v| vec![e.clone()]);
(tuples, shutdown_propose)
}
};
let relation = CollectionRelation {
variables: vec![sym1],
tuples,
};
(
Implemented::Collection(relation),
ShutdownHandle::from_button(shutdown_propose),
)
}
Plan::NameExpr(ref syms, ref name) => {
match local_arrangements.get(name) {
None => panic!("{:?} not in relation map", name),
Some(named) => {
let relation = CollectionRelation {
variables: syms.clone(),
tuples: named.deref().clone(), // @TODO re-use variable directly?
};
(Implemented::Collection(relation), ShutdownHandle::empty())
}
}
}
Plan::Pull(ref pull) => pull.implement(nested, domain, local_arrangements),
Plan::PullLevel(ref path) => path.implement(nested, domain, local_arrangements),
Plan::PullAll(ref path) => path.implement(nested, domain, local_arrangements),
#[cfg(feature = "graphql")]
Plan::GraphQl(ref query) => query.implement(nested, domain, local_arrangements),
}
}
}
|
use crate::reader::get_lines;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufReader, Lines};
pub fn part_1(filename: &str) -> usize {
get_paths(filename, false)
}
pub fn part_2(filename: &str) -> usize {
get_paths(filename, true)
}
fn get_paths(filename: &str, allow_revisits : bool) -> usize {
let lines = get_lines(filename);
let maze = parse_maze(lines);
let visited_nodes: HashSet<&str> = HashSet::new();
let paths = maze.find_paths_from_node( "start", visited_nodes, true, allow_revisits);
let nr_paths: usize = paths.len();
nr_paths
}
fn parse_maze(lines: Lines<BufReader<File>>) -> Maze {
let mut graph: HashMap<String, Vec<String>> = HashMap::new();
for line in lines {
let line = line.unwrap();
let parts: Vec<String> = line.split("-").map(|x| x.to_string()).collect();
let node_a = parts[0].to_string();
let node_b = parts[1].to_string();
let nodes_for_a = graph.entry(node_a.clone()).or_insert(Vec::new());
nodes_for_a.push(node_b.clone());
let nodes_for_b = graph.entry(node_b).or_insert(Vec::new());
nodes_for_b.push(node_a);
}
let mut small_caves: HashSet<String> = HashSet::new();
for node in graph.keys() {
if node.chars().any(|c| matches!(c, 'a'..='z')) {
small_caves.insert(node.clone());
}
}
let maze = Maze { small_caves, cave_layout: graph };
maze
}
struct Maze {
small_caves : HashSet<String>,
cave_layout : HashMap<String, Vec<String>>
}
impl Maze {
fn find_paths_from_node<'a>(&'a self, node: &'a str, mut visited_caves: HashSet<&'a str>, free_pass: bool, allow_revisit : bool) -> Vec<Vec<&'a str>> {
if node == "end" {
return vec![vec!["end"]]
}
if self.small_caves.contains(node) {
visited_caves.insert(node);
}
let mut paths_found : Vec<Vec<&str>> = Vec::new();
for node in self.cave_layout.get(&*node).unwrap() {
if node != "start" && (!visited_caves.contains(&**node) || (free_pass && allow_revisit)) {
// this clone needs to be here to make sure we don't infect other paths
let mut free_pass = free_pass.clone();
// this clone also needs to be here to prevent infecting other paths
let caves = visited_caves.clone();
if visited_caves.contains(&**node) {
free_pass = false;
}
let mut paths = self.find_paths_from_node(node, caves, free_pass, allow_revisit);
// add current node to paths found from the next node
for path in &mut paths {
path.push(node)
}
// extend total paths with current paths
paths_found.extend(paths);
}
}
paths_found
}
}
#[cfg(test)]
mod tests {
use crate::day12::{part_1, part_2};
#[test]
fn test_part1() {
assert_eq!(10, part_1("./resources/inputs/day12-example.txt"));
assert_eq!(5104, part_1("./resources/inputs/day12-input.txt"));
}
#[test]
fn test_part2() {
assert_eq!(36, part_2("./resources/inputs/day12-example.txt"));
assert_eq!(149220, part_2("./resources/inputs/day12-input.txt"));
}
}
|
extern crate wasm_bindgen;
mod common;
mod strategy;
use crate::common::{Board, Coordinate, Player};
use crate::strategy::random::RandomStrategy;
use crate::strategy::minmax::MinMaxStrategy;
use crate::strategy::naive::NaiveStrategy;
use crate::strategy::Strategy;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen]
pub struct Reversi {
board: Board,
next: Player,
player_user: Player,
player_cpu: Player,
strategy_cpu: Box<Strategy>,
}
#[wasm_bindgen]
impl Reversi {
pub fn new(player_user: &str, strategy_cpu: &str) -> Result<Reversi, JsValue> {
let player_user = match player_user {
"black" => Player::Black,
"white" => Player::White,
_ => return Err(JsValue::from("player_user should be 'white' or 'black'")),
};
let player_cpu = player_user.other();
let strategy_cpu: Box<Strategy> = match strategy_cpu {
"random" => Box::new(RandomStrategy::new(player_cpu)),
"minmax1" => Box::new(MinMaxStrategy::new(player_cpu, 1)),
"minmax2" => Box::new(MinMaxStrategy::new(player_cpu, 2)),
"minmax4" => Box::new(MinMaxStrategy::new(player_cpu, 4)),
"naive" => Box::new(NaiveStrategy::new(player_cpu)),
_ => {
return Err(JsValue::from(
"strategy_cpu should be 'random', 'minmax1', 'minmax2', 'minmax4' or 'naive'",
))
}
};
Ok(Reversi {
board: Board::initial(),
next: Player::Black,
player_user,
player_cpu,
strategy_cpu,
})
}
pub fn board(&self) -> String {
let mut board = [[0; 8]; 8];
for x in 0..8 {
for y in 0..8 {
match self.board.cell(Coordinate { x, y }) {
Some(Player::Black) => {
board[x][y] = 1;
}
Some(Player::White) => {
board[x][y] = 2;
}
None => {}
}
}
}
serde_json::to_string(&board).unwrap()
}
pub fn has_valid_move(&self) -> bool {
self.board.has_valid_move(self.player_user)
}
// return false if invalid
pub fn pass(&mut self) -> bool {
if self.next != self.player_user {
return false;
}
if self.board.has_valid_move(self.player_user) {
return false;
}
self.next = self.next.other();
true
}
// return false if invalid
pub fn make_move(&mut self, x: i32, y: i32) -> bool {
if self.next != self.player_user {
return false;
}
match self.board.simulate(
Coordinate {
x: x as usize,
y: y as usize,
},
self.player_user,
) {
Some(board_updated) => {
self.board = board_updated;
}
None => return false,
}
self.next = self.next.other();
true
}
pub fn wait_for_cpu(&mut self) {
match self.strategy_cpu.make_move(self.board) {
Some(c) => match self.board.simulate(c, self.player_cpu) {
Some(board_updated) => {
self.board = board_updated;
}
None => panic!("invalid move by cpu"),
},
// pass
None => {
if self.board.has_valid_move(self.player_cpu) {
panic!("invalid pass by cpu");
}
}
}
self.next = self.next.other()
}
// return None if the game has not yet ended
pub fn result(&self) -> Option<String> {
for p in [Player::Black, Player::White].iter() {
if self.board.has_valid_move(*p) {
return None;
}
}
let result = [
self.board.count(Player::Black),
self.board.count(Player::White),
];
Some(serde_json::to_string(&result).unwrap())
}
}
|
use opengl_graphics::{GlGraphics, OpenGL};
use graphics::{Context, Graphics};
use std::collections::HashMap;
use piston::window::{Window, WindowSettings};
use piston::input::*;
use piston::event_loop::*;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
#[cfg(feature = "include_glfw")]
use glfw_window::GlfwWindow as AppWindow;
#[cfg(feature = "include_glutin")]
use glutin_window::GlutinWindow as AppWindow;
#[derive(Debug)]
struct Block {
kind: u32,
x: i32,
y: i32,
z: i32,
flags: u32,
}
impl Block {
fn from_hashmap(map: HashMap<prc::hash40::Hash40, prc::param::ParamKind>) -> Self {
Self {
kind: *map[&prc::hash40::to_hash40("kind")].unwrap(),
x: *map[&prc::hash40::to_hash40("x")].unwrap(),
y: *map[&prc::hash40::to_hash40("y")].unwrap(),
z: *map[&prc::hash40::to_hash40("z")].unwrap(),
flags: *map[&prc::hash40::to_hash40("flags")].unwrap(),
}
}
}
const BLOCK_SIZE: f64 = 20.0;
fn main() {
let breakable_stdat = std::env::args().skip(1).next().unwrap();
let param = prc::open(breakable_stdat).unwrap();
let blocks: Vec<Block> = if let prc::param::ParamKind::List(list) = param.into_iter().next().unwrap().1 {
list.into_iter()
.map(|x| Block::from_hashmap(x.unwrap_as_hashmap().unwrap()))
.collect()
} else {
panic!("Invalid structure")
};
let mut window: AppWindow = WindowSettings::new("Minecraft Viewing", [600, 600])
.exit_on_esc(true).build().unwrap();
let opengl = OpenGL::V3_2;
let ref mut gl = GlGraphics::new(opengl);
let mut events = Events::new(EventSettings::new().lazy(true));
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
gl.draw(args.viewport(), |c, g| {
graphics::clear([1.0; 4], g);
let size = window.draw_size();
let height = size.height as isize;
let width = size.width as isize;
let width_center = (width / 2) as f64;
let vert_center = (height / 2) as f64;
for block in &blocks {
block.draw((width_center, vert_center), &c, g);
}
//draw_state(&state, &window, &c, g);
}
);
}
}
}
const DIRT_BROWN: [f32; 4] = [
(0x85 as f32) / (255 as f32),
(0x4F as f32) / (255 as f32),
(0x2B as f32) / (255 as f32),
1.0,
];
impl Block {
fn draw<G: Graphics>(&self, center: (f64, f64), c: &Context, g: &mut G) {
let rect = graphics::Rectangle::new_round(
DIRT_BROWN,
2.0
);
rect.draw(
[
(center.0 + ((-self.x as f64) * BLOCK_SIZE) - (BLOCK_SIZE / 2.0)),
(center.1 + ((-self.y as f64) * BLOCK_SIZE) - (BLOCK_SIZE / 2.0)),
BLOCK_SIZE,
BLOCK_SIZE
],
&c.draw_state,
c.transform,
g
);
}
}
|
use std::collections::HashSet;
use nalgebra::Vector3;
use crate::{
prelude::*,
material::*,
};
/// Gives the color to an existing material.
#[derive(Clone, Debug)]
pub struct Colored<M: Material> {
pub material: M,
pub color: Vector3<f64>,
}
impl<M: Material> Colored<M> {
pub fn new(material: M, color: Vector3<f64>) -> Self {
Self { material, color }
}
}
impl<M: Material> Material for Colored<M> {
fn brightness(&self) -> f64 {
self.material.brightness()*
self.color.data.iter().fold(0.0, |a, b| f64::max(a, *b))
}
}
impl<M: Material> Instance<MaterialClass> for Colored<M> {
fn source(cache: &mut HashSet<u64>) -> String {
if !cache.insert(Self::type_hash()) {
return String::new()
}
[
M::source(cache),
"#include <clay_core/material/colored.h>".to_string(),
format!(
"COLORED_MATERIAL_FN_DEF({}, {}, {}, {})",
Self::inst_name(),
M::inst_name(),
M::size_int(),
M::size_float(),
),
].join("\n")
}
fn inst_name() -> String {
format!(
"__{}_colored_{:x}",
M::inst_name(),
Self::type_hash(),
)
}
}
impl<M: Material> Pack for Colored<M> {
fn size_int() -> usize { M::size_int() + 0 }
fn size_float() -> usize { M::size_float() + 3 }
fn pack_to(&self, buffer_int: &mut [i32], buffer_float: &mut [f32]) {
self.material.pack_to(buffer_int, buffer_float);
self.color.pack_float_to(&mut buffer_float[M::size_float()..]);
}
}
|
test_stdout!(
without_normal_exit_in_child_process_exits_linked_parent_process,
"{child, exited, abnormal}\n"
);
test_stdout!(
with_normal_exit_in_child_process_exits_linked_parent_process,
"{child, exited, normal}\n"
);
|
use diesel::deserialize::{self, FromSql};
use diesel::pg::Pg;
use diesel::serialize::{self, IsNull, Output, ToSql};
use diesel::sql_types::Text;
use schema::{profiles, sessions, users};
use std::io::Write;
use validator::Validate;
#[derive(Clone, Queryable)]
pub struct Session {
pub id: i32,
pub uid: i32,
pub token: String,
pub active: bool,
pub created: chrono::NaiveDateTime,
pub updated: chrono::NaiveDateTime,
}
#[derive(Insertable)]
#[table_name = "sessions"]
pub struct NewSession {
pub uid: i32,
pub token: String,
pub active: bool,
pub created: chrono::NaiveDateTime,
pub updated: chrono::NaiveDateTime,
}
#[derive(Serialize, Debug, Default, Identifiable, Clone, Queryable)]
#[table_name = "users"]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
#[serde(skip_serializing)]
pub password_hash: String,
pub roles: Vec<Role>,
}
#[derive(Serialize, Debug)]
pub enum CurrentUser {
Anonymous,
Authenticated(User),
Admin(User),
}
#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser {
pub name: String,
pub email: String,
pub password_hash: String,
pub roles: Vec<Role>,
}
/*
* Deal status
*/
#[derive(Serialize, Deserialize, Debug, Copy, Clone, AsExpression, FromSqlRow)]
#[sql_type = "Text"]
pub enum Role {
Anonymous,
Authenticated,
Admin,
}
impl ToSql<Text, Pg> for Role {
fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
match *self {
Role::Anonymous => out.write_all(b"anonymous")?,
Role::Authenticated => out.write_all(b"authenticated")?,
Role::Admin => out.write_all(b"admin")?,
}
Ok(IsNull::No)
}
}
impl FromSql<Text, Pg> for Role {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
match not_none!(bytes) {
b"anonymous" => Ok(Role::Anonymous),
b"authenticated" => Ok(Role::Authenticated),
b"admin" => Ok(Role::Admin),
_ => Err("Unrecognized enum variant".into()),
}
}
}
#[derive(Deserialize, Validate)]
pub struct LoginInput {
#[validate(length(min = "1", max = "256", message = "Cannot be blank"))]
pub email: String,
#[validate(length(min = "1", max = "256", message = "Cannot be blank"))]
pub password: String,
}
/// Input used for registratoin
#[derive(Deserialize, Clone, Validate)]
pub struct RegistrationInput {
#[validate(length(min = "1", max = "256", message = "Cannot be blank"))]
pub name: String,
#[validate(email(message = "Email is not valid"))]
pub email: String,
#[validate(length(
min = "6",
max = "30",
message = "Password length must be between 6 and 30"
))]
pub password: String,
}
#[derive(Serialize, Clone, Default)]
pub struct AuthPayload {
pub token: Option<String>,
pub user: Option<User>,
}
/// Input used for registratoin
#[derive(Deserialize, Clone, Validate)]
pub struct CreateUserInput {
#[validate(length(min = "1", max = "256", message = "Cannot be blank"))]
pub name: String,
#[validate(email(message = "Email is not valid"))]
pub email: String,
#[validate(length(
min = "6",
max = "30",
message = "Password length must be between 6 and 30"
))]
pub password: String,
pub roles: Vec<Role>,
}
#[derive(Clone, Queryable, Serialize, Default, Identifiable)]
pub struct Profile {
pub id: i32,
pub uid: i32,
pub title: String,
pub intro: String,
pub body: String,
}
#[derive(Clone, Insertable)]
#[table_name = "profiles"]
pub struct NewProfile {
pub uid: i32,
pub title: String,
pub intro: String,
pub body: String,
}
#[derive(Clone, Deserialize, Validate, AsChangeset)]
#[table_name = "profiles"]
pub struct ProfileInput {
#[validate(length(min = "1", max = "256", message = "Cannot be blank"))]
pub title: String,
#[validate(length(min = "1", max = "256", message = "Cannot be blank"))]
pub intro: String,
#[validate(length(min = "1", max = "2000", message = "Cannot be blank"))]
pub body: String,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.