text
stringlengths
8
4.13M
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub const ICW_ALREADYRUN: u32 = 4u32; pub const ICW_CHECKSTATUS: u32 = 1u32; pub const ICW_FULLPRESENT: u32 = 1u32; pub const ICW_FULL_SMARTSTART: u32 = 2048u32; pub const ICW_LAUNCHEDFULL: u32 = 256u32; pub const ICW_LAUNCHEDMANUAL: u32 = 512u32; pub const ICW_LAUNCHFULL: u32 = 256u32; pub const ICW_LAUNCHMANUAL: u32 = 512u32; pub const ICW_MANUALPRESENT: u32 = 2u32; pub const ICW_MAX_ACCTNAME: u32 = 256u32; pub const ICW_MAX_EMAILADDR: u32 = 128u32; pub const ICW_MAX_EMAILNAME: u32 = 64u32; pub const ICW_MAX_LOGONNAME: u32 = 256u32; pub const ICW_MAX_PASSWORD: u32 = 256u32; pub const ICW_MAX_RASNAME: u32 = 256u32; pub const ICW_MAX_SERVERNAME: u32 = 64u32; pub const ICW_USEDEFAULTS: u32 = 1u32; pub const ICW_USE_SHELLNEXT: u32 = 1024u32; pub type PFNCHECKCONNECTIONWIZARD = ::core::option::Option<unsafe extern "system" fn(param0: u32, param1: *mut u32) -> u32>; #[cfg(feature = "Win32_Foundation")] pub type PFNSETSHELLNEXT = ::core::option::Option<unsafe extern "system" fn(param0: super::super::Foundation::PSTR) -> u32>;
#[doc = "Reader of register OPAMP2_CSR"] pub type R = crate::R<u32, super::OPAMP2_CSR>; #[doc = "Writer for register OPAMP2_CSR"] pub type W = crate::W<u32, super::OPAMP2_CSR>; #[doc = "Register OPAMP2_CSR `reset()`'s with value 0"] impl crate::ResetValue for super::OPAMP2_CSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "OPAMP2 enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OPAMP2EN_A { #[doc = "0: OPAMP2 is disabled"] DISABLED = 0, #[doc = "1: OPAMP2 is enabled"] ENABLED = 1, } impl From<OPAMP2EN_A> for bool { #[inline(always)] fn from(variant: OPAMP2EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OPAMP2EN`"] pub type OPAMP2EN_R = crate::R<bool, OPAMP2EN_A>; impl OPAMP2EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OPAMP2EN_A { match self.bits { false => OPAMP2EN_A::DISABLED, true => OPAMP2EN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == OPAMP2EN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == OPAMP2EN_A::ENABLED } } #[doc = "Write proxy for field `OPAMP2EN`"] pub struct OPAMP2EN_W<'a> { w: &'a mut W, } impl<'a> OPAMP2EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OPAMP2EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "OPAMP2 is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(OPAMP2EN_A::DISABLED) } #[doc = "OPAMP2 is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(OPAMP2EN_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 = "FORCE_VP\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FORCE_VP_A { #[doc = "0: Normal operating mode"] NORMAL = 0, #[doc = "1: Calibration mode. Non-inverting input connected to calibration reference"] CALIBRATION = 1, } impl From<FORCE_VP_A> for bool { #[inline(always)] fn from(variant: FORCE_VP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FORCE_VP`"] pub type FORCE_VP_R = crate::R<bool, FORCE_VP_A>; impl FORCE_VP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FORCE_VP_A { match self.bits { false => FORCE_VP_A::NORMAL, true => FORCE_VP_A::CALIBRATION, } } #[doc = "Checks if the value of the field is `NORMAL`"] #[inline(always)] pub fn is_normal(&self) -> bool { *self == FORCE_VP_A::NORMAL } #[doc = "Checks if the value of the field is `CALIBRATION`"] #[inline(always)] pub fn is_calibration(&self) -> bool { *self == FORCE_VP_A::CALIBRATION } } #[doc = "Write proxy for field `FORCE_VP`"] pub struct FORCE_VP_W<'a> { w: &'a mut W, } impl<'a> FORCE_VP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FORCE_VP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Normal operating mode"] #[inline(always)] pub fn normal(self) -> &'a mut W { self.variant(FORCE_VP_A::NORMAL) } #[doc = "Calibration mode. Non-inverting input connected to calibration reference"] #[inline(always)] pub fn calibration(self) -> &'a mut W { self.variant(FORCE_VP_A::CALIBRATION) } #[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 = "OPAMP Non inverting input selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum VP_SEL_A { #[doc = "1: PB14 used as OPAMP2 non-inverting input"] PB14 = 1, #[doc = "2: PB0 used as OPAMP2 non-inverting input"] PB0 = 2, #[doc = "3: PA7 used as OPAMP2 non-inverting input"] PA7 = 3, } impl From<VP_SEL_A> for u8 { #[inline(always)] fn from(variant: VP_SEL_A) -> Self { variant as _ } } #[doc = "Reader of field `VP_SEL`"] pub type VP_SEL_R = crate::R<u8, VP_SEL_A>; impl VP_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, VP_SEL_A> { use crate::Variant::*; match self.bits { 1 => Val(VP_SEL_A::PB14), 2 => Val(VP_SEL_A::PB0), 3 => Val(VP_SEL_A::PA7), i => Res(i), } } #[doc = "Checks if the value of the field is `PB14`"] #[inline(always)] pub fn is_pb14(&self) -> bool { *self == VP_SEL_A::PB14 } #[doc = "Checks if the value of the field is `PB0`"] #[inline(always)] pub fn is_pb0(&self) -> bool { *self == VP_SEL_A::PB0 } #[doc = "Checks if the value of the field is `PA7`"] #[inline(always)] pub fn is_pa7(&self) -> bool { *self == VP_SEL_A::PA7 } } #[doc = "Write proxy for field `VP_SEL`"] pub struct VP_SEL_W<'a> { w: &'a mut W, } impl<'a> VP_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VP_SEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "PB14 used as OPAMP2 non-inverting input"] #[inline(always)] pub fn pb14(self) -> &'a mut W { self.variant(VP_SEL_A::PB14) } #[doc = "PB0 used as OPAMP2 non-inverting input"] #[inline(always)] pub fn pb0(self) -> &'a mut W { self.variant(VP_SEL_A::PB0) } #[doc = "PA7 used as OPAMP2 non-inverting input"] #[inline(always)] pub fn pa7(self) -> &'a mut W { self.variant(VP_SEL_A::PA7) } #[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 & !(0x03 << 2)) | (((value as u32) & 0x03) << 2); self.w } } #[doc = "OPAMP inverting input selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum VM_SEL_A { #[doc = "0: PC5 (VM0) used as OPAMP2 inverting input"] PC5 = 0, #[doc = "1: PA5 (VM1) used as OPAMP2 inverting input"] PA5 = 1, #[doc = "2: Resistor feedback output (PGA mode)"] PGA = 2, #[doc = "3: Follower mode"] FOLLOWER = 3, } impl From<VM_SEL_A> for u8 { #[inline(always)] fn from(variant: VM_SEL_A) -> Self { variant as _ } } #[doc = "Reader of field `VM_SEL`"] pub type VM_SEL_R = crate::R<u8, VM_SEL_A>; impl VM_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> VM_SEL_A { match self.bits { 0 => VM_SEL_A::PC5, 1 => VM_SEL_A::PA5, 2 => VM_SEL_A::PGA, 3 => VM_SEL_A::FOLLOWER, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PC5`"] #[inline(always)] pub fn is_pc5(&self) -> bool { *self == VM_SEL_A::PC5 } #[doc = "Checks if the value of the field is `PA5`"] #[inline(always)] pub fn is_pa5(&self) -> bool { *self == VM_SEL_A::PA5 } #[doc = "Checks if the value of the field is `PGA`"] #[inline(always)] pub fn is_pga(&self) -> bool { *self == VM_SEL_A::PGA } #[doc = "Checks if the value of the field is `FOLLOWER`"] #[inline(always)] pub fn is_follower(&self) -> bool { *self == VM_SEL_A::FOLLOWER } } #[doc = "Write proxy for field `VM_SEL`"] pub struct VM_SEL_W<'a> { w: &'a mut W, } impl<'a> VM_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VM_SEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "PC5 (VM0) used as OPAMP2 inverting input"] #[inline(always)] pub fn pc5(self) -> &'a mut W { self.variant(VM_SEL_A::PC5) } #[doc = "PA5 (VM1) used as OPAMP2 inverting input"] #[inline(always)] pub fn pa5(self) -> &'a mut W { self.variant(VM_SEL_A::PA5) } #[doc = "Resistor feedback output (PGA mode)"] #[inline(always)] pub fn pga(self) -> &'a mut W { self.variant(VM_SEL_A::PGA) } #[doc = "Follower mode"] #[inline(always)] pub fn follower(self) -> &'a mut W { self.variant(VM_SEL_A::FOLLOWER) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 5)) | (((value as u32) & 0x03) << 5); self.w } } #[doc = "Timer controlled Mux mode enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TCM_EN_A { #[doc = "0: Timer controlled mux disabled"] DISABLED = 0, #[doc = "1: Timer controlled mux enabled"] ENABLED = 1, } impl From<TCM_EN_A> for bool { #[inline(always)] fn from(variant: TCM_EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TCM_EN`"] pub type TCM_EN_R = crate::R<bool, TCM_EN_A>; impl TCM_EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TCM_EN_A { match self.bits { false => TCM_EN_A::DISABLED, true => TCM_EN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TCM_EN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TCM_EN_A::ENABLED } } #[doc = "Write proxy for field `TCM_EN`"] pub struct TCM_EN_W<'a> { w: &'a mut W, } impl<'a> TCM_EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TCM_EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer controlled mux disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TCM_EN_A::DISABLED) } #[doc = "Timer controlled mux enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TCM_EN_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "OPAMP inverting input secondary selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VMS_SEL_A { #[doc = "0: PC5 (VM0) used as OPAMP2 inverting input when TCM_EN=1"] PC5 = 0, #[doc = "1: PA5 (VM1) used as OPAMP2 inverting input when TCM_EN=1"] PA5 = 1, } impl From<VMS_SEL_A> for bool { #[inline(always)] fn from(variant: VMS_SEL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `VMS_SEL`"] pub type VMS_SEL_R = crate::R<bool, VMS_SEL_A>; impl VMS_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> VMS_SEL_A { match self.bits { false => VMS_SEL_A::PC5, true => VMS_SEL_A::PA5, } } #[doc = "Checks if the value of the field is `PC5`"] #[inline(always)] pub fn is_pc5(&self) -> bool { *self == VMS_SEL_A::PC5 } #[doc = "Checks if the value of the field is `PA5`"] #[inline(always)] pub fn is_pa5(&self) -> bool { *self == VMS_SEL_A::PA5 } } #[doc = "Write proxy for field `VMS_SEL`"] pub struct VMS_SEL_W<'a> { w: &'a mut W, } impl<'a> VMS_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VMS_SEL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "PC5 (VM0) used as OPAMP2 inverting input when TCM_EN=1"] #[inline(always)] pub fn pc5(self) -> &'a mut W { self.variant(VMS_SEL_A::PC5) } #[doc = "PA5 (VM1) used as OPAMP2 inverting input when TCM_EN=1"] #[inline(always)] pub fn pa5(self) -> &'a mut W { self.variant(VMS_SEL_A::PA5) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "OPAMP Non inverting input secondary selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum VPS_SEL_A { #[doc = "1: PB14 used as OPAMP2 non-inverting input when TCM_EN=1"] PB14 = 1, #[doc = "2: PB0 used as OPAMP2 non-inverting input when TCM_EN=1"] PB0 = 2, #[doc = "3: PA7 used as OPAMP2 non-inverting input when TCM_EN=1"] PA7 = 3, } impl From<VPS_SEL_A> for u8 { #[inline(always)] fn from(variant: VPS_SEL_A) -> Self { variant as _ } } #[doc = "Reader of field `VPS_SEL`"] pub type VPS_SEL_R = crate::R<u8, VPS_SEL_A>; impl VPS_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, VPS_SEL_A> { use crate::Variant::*; match self.bits { 1 => Val(VPS_SEL_A::PB14), 2 => Val(VPS_SEL_A::PB0), 3 => Val(VPS_SEL_A::PA7), i => Res(i), } } #[doc = "Checks if the value of the field is `PB14`"] #[inline(always)] pub fn is_pb14(&self) -> bool { *self == VPS_SEL_A::PB14 } #[doc = "Checks if the value of the field is `PB0`"] #[inline(always)] pub fn is_pb0(&self) -> bool { *self == VPS_SEL_A::PB0 } #[doc = "Checks if the value of the field is `PA7`"] #[inline(always)] pub fn is_pa7(&self) -> bool { *self == VPS_SEL_A::PA7 } } #[doc = "Write proxy for field `VPS_SEL`"] pub struct VPS_SEL_W<'a> { w: &'a mut W, } impl<'a> VPS_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VPS_SEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "PB14 used as OPAMP2 non-inverting input when TCM_EN=1"] #[inline(always)] pub fn pb14(self) -> &'a mut W { self.variant(VPS_SEL_A::PB14) } #[doc = "PB0 used as OPAMP2 non-inverting input when TCM_EN=1"] #[inline(always)] pub fn pb0(self) -> &'a mut W { self.variant(VPS_SEL_A::PB0) } #[doc = "PA7 used as OPAMP2 non-inverting input when TCM_EN=1"] #[inline(always)] pub fn pa7(self) -> &'a mut W { self.variant(VPS_SEL_A::PA7) } #[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 & !(0x03 << 9)) | (((value as u32) & 0x03) << 9); self.w } } #[doc = "Calibration mode enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CALON_A { #[doc = "0: Calibration mode disabled"] DISABLED = 0, #[doc = "1: Calibration mode enabled"] ENABLED = 1, } impl From<CALON_A> for bool { #[inline(always)] fn from(variant: CALON_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CALON`"] pub type CALON_R = crate::R<bool, CALON_A>; impl CALON_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CALON_A { match self.bits { false => CALON_A::DISABLED, true => CALON_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == CALON_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == CALON_A::ENABLED } } #[doc = "Write proxy for field `CALON`"] pub struct CALON_W<'a> { w: &'a mut W, } impl<'a> CALON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CALON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Calibration mode disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(CALON_A::DISABLED) } #[doc = "Calibration mode enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(CALON_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Calibration selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CALSEL_A { #[doc = "0: VREFOPAMP=3.3% VDDA"] PERCENT3_3 = 0, #[doc = "1: VREFOPAMP=10% VDDA"] PERCENT10 = 1, #[doc = "2: VREFOPAMP=50% VDDA"] PERCENT50 = 2, #[doc = "3: VREFOPAMP=90% VDDA"] PERCENT90 = 3, } impl From<CALSEL_A> for u8 { #[inline(always)] fn from(variant: CALSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `CALSEL`"] pub type CALSEL_R = crate::R<u8, CALSEL_A>; impl CALSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CALSEL_A { match self.bits { 0 => CALSEL_A::PERCENT3_3, 1 => CALSEL_A::PERCENT10, 2 => CALSEL_A::PERCENT50, 3 => CALSEL_A::PERCENT90, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PERCENT3_3`"] #[inline(always)] pub fn is_percent3_3(&self) -> bool { *self == CALSEL_A::PERCENT3_3 } #[doc = "Checks if the value of the field is `PERCENT10`"] #[inline(always)] pub fn is_percent10(&self) -> bool { *self == CALSEL_A::PERCENT10 } #[doc = "Checks if the value of the field is `PERCENT50`"] #[inline(always)] pub fn is_percent50(&self) -> bool { *self == CALSEL_A::PERCENT50 } #[doc = "Checks if the value of the field is `PERCENT90`"] #[inline(always)] pub fn is_percent90(&self) -> bool { *self == CALSEL_A::PERCENT90 } } #[doc = "Write proxy for field `CALSEL`"] pub struct CALSEL_W<'a> { w: &'a mut W, } impl<'a> CALSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CALSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "VREFOPAMP=3.3% VDDA"] #[inline(always)] pub fn percent3_3(self) -> &'a mut W { self.variant(CALSEL_A::PERCENT3_3) } #[doc = "VREFOPAMP=10% VDDA"] #[inline(always)] pub fn percent10(self) -> &'a mut W { self.variant(CALSEL_A::PERCENT10) } #[doc = "VREFOPAMP=50% VDDA"] #[inline(always)] pub fn percent50(self) -> &'a mut W { self.variant(CALSEL_A::PERCENT50) } #[doc = "VREFOPAMP=90% VDDA"] #[inline(always)] pub fn percent90(self) -> &'a mut W { self.variant(CALSEL_A::PERCENT90) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "Gain in PGA mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PGA_GAIN_A { #[doc = "0: Gain 2"] GAIN2 = 0, #[doc = "1: Gain 4"] GAIN4 = 1, #[doc = "2: Gain 8"] GAIN8 = 2, #[doc = "4: Gain 16"] GAIN16 = 4, #[doc = "8: Gain 2, feedback connected to VM0"] GAIN2_VM0 = 8, #[doc = "9: Gain 4, feedback connected to VM0"] GAIN4_VM0 = 9, #[doc = "10: Gain 8, feedback connected to VM0"] GAIN8_VM0 = 10, #[doc = "11: Gain 16, feedback connected to VM0"] GAIN16_VM0 = 11, #[doc = "12: Gain 2, feedback connected to VM1"] GAIN2_VM1 = 12, #[doc = "13: Gain 4, feedback connected to VM1"] GAIN4_VM1 = 13, #[doc = "14: Gain 8, feedback connected to VM1"] GAIN8_VM1 = 14, #[doc = "15: Gain 16, feedback connected to VM1"] GAIN16_VM1 = 15, } impl From<PGA_GAIN_A> for u8 { #[inline(always)] fn from(variant: PGA_GAIN_A) -> Self { variant as _ } } #[doc = "Reader of field `PGA_GAIN`"] pub type PGA_GAIN_R = crate::R<u8, PGA_GAIN_A>; impl PGA_GAIN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, PGA_GAIN_A> { use crate::Variant::*; match self.bits { 0 => Val(PGA_GAIN_A::GAIN2), 1 => Val(PGA_GAIN_A::GAIN4), 2 => Val(PGA_GAIN_A::GAIN8), 4 => Val(PGA_GAIN_A::GAIN16), 8 => Val(PGA_GAIN_A::GAIN2_VM0), 9 => Val(PGA_GAIN_A::GAIN4_VM0), 10 => Val(PGA_GAIN_A::GAIN8_VM0), 11 => Val(PGA_GAIN_A::GAIN16_VM0), 12 => Val(PGA_GAIN_A::GAIN2_VM1), 13 => Val(PGA_GAIN_A::GAIN4_VM1), 14 => Val(PGA_GAIN_A::GAIN8_VM1), 15 => Val(PGA_GAIN_A::GAIN16_VM1), i => Res(i), } } #[doc = "Checks if the value of the field is `GAIN2`"] #[inline(always)] pub fn is_gain2(&self) -> bool { *self == PGA_GAIN_A::GAIN2 } #[doc = "Checks if the value of the field is `GAIN4`"] #[inline(always)] pub fn is_gain4(&self) -> bool { *self == PGA_GAIN_A::GAIN4 } #[doc = "Checks if the value of the field is `GAIN8`"] #[inline(always)] pub fn is_gain8(&self) -> bool { *self == PGA_GAIN_A::GAIN8 } #[doc = "Checks if the value of the field is `GAIN16`"] #[inline(always)] pub fn is_gain16(&self) -> bool { *self == PGA_GAIN_A::GAIN16 } #[doc = "Checks if the value of the field is `GAIN2_VM0`"] #[inline(always)] pub fn is_gain2_vm0(&self) -> bool { *self == PGA_GAIN_A::GAIN2_VM0 } #[doc = "Checks if the value of the field is `GAIN4_VM0`"] #[inline(always)] pub fn is_gain4_vm0(&self) -> bool { *self == PGA_GAIN_A::GAIN4_VM0 } #[doc = "Checks if the value of the field is `GAIN8_VM0`"] #[inline(always)] pub fn is_gain8_vm0(&self) -> bool { *self == PGA_GAIN_A::GAIN8_VM0 } #[doc = "Checks if the value of the field is `GAIN16_VM0`"] #[inline(always)] pub fn is_gain16_vm0(&self) -> bool { *self == PGA_GAIN_A::GAIN16_VM0 } #[doc = "Checks if the value of the field is `GAIN2_VM1`"] #[inline(always)] pub fn is_gain2_vm1(&self) -> bool { *self == PGA_GAIN_A::GAIN2_VM1 } #[doc = "Checks if the value of the field is `GAIN4_VM1`"] #[inline(always)] pub fn is_gain4_vm1(&self) -> bool { *self == PGA_GAIN_A::GAIN4_VM1 } #[doc = "Checks if the value of the field is `GAIN8_VM1`"] #[inline(always)] pub fn is_gain8_vm1(&self) -> bool { *self == PGA_GAIN_A::GAIN8_VM1 } #[doc = "Checks if the value of the field is `GAIN16_VM1`"] #[inline(always)] pub fn is_gain16_vm1(&self) -> bool { *self == PGA_GAIN_A::GAIN16_VM1 } } #[doc = "Write proxy for field `PGA_GAIN`"] pub struct PGA_GAIN_W<'a> { w: &'a mut W, } impl<'a> PGA_GAIN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PGA_GAIN_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Gain 2"] #[inline(always)] pub fn gain2(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN2) } #[doc = "Gain 4"] #[inline(always)] pub fn gain4(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN4) } #[doc = "Gain 8"] #[inline(always)] pub fn gain8(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN8) } #[doc = "Gain 16"] #[inline(always)] pub fn gain16(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN16) } #[doc = "Gain 2, feedback connected to VM0"] #[inline(always)] pub fn gain2_vm0(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN2_VM0) } #[doc = "Gain 4, feedback connected to VM0"] #[inline(always)] pub fn gain4_vm0(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN4_VM0) } #[doc = "Gain 8, feedback connected to VM0"] #[inline(always)] pub fn gain8_vm0(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN8_VM0) } #[doc = "Gain 16, feedback connected to VM0"] #[inline(always)] pub fn gain16_vm0(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN16_VM0) } #[doc = "Gain 2, feedback connected to VM1"] #[inline(always)] pub fn gain2_vm1(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN2_VM1) } #[doc = "Gain 4, feedback connected to VM1"] #[inline(always)] pub fn gain4_vm1(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN4_VM1) } #[doc = "Gain 8, feedback connected to VM1"] #[inline(always)] pub fn gain8_vm1(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN8_VM1) } #[doc = "Gain 16, feedback connected to VM1"] #[inline(always)] pub fn gain16_vm1(self) -> &'a mut W { self.variant(PGA_GAIN_A::GAIN16_VM1) } #[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 << 14)) | (((value as u32) & 0x0f) << 14); self.w } } #[doc = "User trimming enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USER_TRIM_A { #[doc = "0: User trimming disabled"] DISABLED = 0, #[doc = "1: User trimming enabled"] ENABLED = 1, } impl From<USER_TRIM_A> for bool { #[inline(always)] fn from(variant: USER_TRIM_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `USER_TRIM`"] pub type USER_TRIM_R = crate::R<bool, USER_TRIM_A>; impl USER_TRIM_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USER_TRIM_A { match self.bits { false => USER_TRIM_A::DISABLED, true => USER_TRIM_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == USER_TRIM_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == USER_TRIM_A::ENABLED } } #[doc = "Write proxy for field `USER_TRIM`"] pub struct USER_TRIM_W<'a> { w: &'a mut W, } impl<'a> USER_TRIM_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USER_TRIM_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "User trimming disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(USER_TRIM_A::DISABLED) } #[doc = "User trimming enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(USER_TRIM_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `TRIMOFFSETP`"] pub type TRIMOFFSETP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TRIMOFFSETP`"] pub struct TRIMOFFSETP_W<'a> { w: &'a mut W, } impl<'a> TRIMOFFSETP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 19)) | (((value as u32) & 0x1f) << 19); self.w } } #[doc = "Reader of field `TRIMOFFSETN`"] pub type TRIMOFFSETN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TRIMOFFSETN`"] pub struct TRIMOFFSETN_W<'a> { w: &'a mut W, } impl<'a> TRIMOFFSETN_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 24)) | (((value as u32) & 0x1f) << 24); self.w } } #[doc = "TSTREF\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TSTREF_A { #[doc = "0: VREFOPAMP2 is output"] OUTPUT = 0, #[doc = "1: VREFOPAMP2 is not output"] NOTOUTPUT = 1, } impl From<TSTREF_A> for bool { #[inline(always)] fn from(variant: TSTREF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TSTREF`"] pub type TSTREF_R = crate::R<bool, TSTREF_A>; impl TSTREF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TSTREF_A { match self.bits { false => TSTREF_A::OUTPUT, true => TSTREF_A::NOTOUTPUT, } } #[doc = "Checks if the value of the field is `OUTPUT`"] #[inline(always)] pub fn is_output(&self) -> bool { *self == TSTREF_A::OUTPUT } #[doc = "Checks if the value of the field is `NOTOUTPUT`"] #[inline(always)] pub fn is_not_output(&self) -> bool { *self == TSTREF_A::NOTOUTPUT } } #[doc = "Write proxy for field `TSTREF`"] pub struct TSTREF_W<'a> { w: &'a mut W, } impl<'a> TSTREF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TSTREF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "VREFOPAMP2 is output"] #[inline(always)] pub fn output(self) -> &'a mut W { self.variant(TSTREF_A::OUTPUT) } #[doc = "VREFOPAMP2 is not output"] #[inline(always)] pub fn not_output(self) -> &'a mut W { self.variant(TSTREF_A::NOTOUTPUT) } #[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 } } #[doc = "OPAMP ouput status flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OUTCAL_A { #[doc = "0: Non-inverting < inverting"] LOW = 0, #[doc = "1: Non-inverting > inverting"] HIGH = 1, } impl From<OUTCAL_A> for bool { #[inline(always)] fn from(variant: OUTCAL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OUTCAL`"] pub type OUTCAL_R = crate::R<bool, OUTCAL_A>; impl OUTCAL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OUTCAL_A { match self.bits { false => OUTCAL_A::LOW, true => OUTCAL_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == OUTCAL_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == OUTCAL_A::HIGH } } #[doc = "OPAMP lock\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LOCK_A { #[doc = "0: Comparator CSR bits are read-write"] UNLOCKED = 0, #[doc = "1: Comparator CSR bits are read-only"] LOCKED = 1, } impl From<LOCK_A> for bool { #[inline(always)] fn from(variant: LOCK_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LOCK`"] pub type LOCK_R = crate::R<bool, LOCK_A>; impl LOCK_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LOCK_A { match self.bits { false => LOCK_A::UNLOCKED, true => LOCK_A::LOCKED, } } #[doc = "Checks if the value of the field is `UNLOCKED`"] #[inline(always)] pub fn is_unlocked(&self) -> bool { *self == LOCK_A::UNLOCKED } #[doc = "Checks if the value of the field is `LOCKED`"] #[inline(always)] pub fn is_locked(&self) -> bool { *self == LOCK_A::LOCKED } } #[doc = "Write proxy for field `LOCK`"] pub struct LOCK_W<'a> { w: &'a mut W, } impl<'a> LOCK_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LOCK_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(LOCK_A::UNLOCKED) } #[doc = "Comparator CSR bits are read-only"] #[inline(always)] pub fn locked(self) -> &'a mut W { self.variant(LOCK_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 } } impl R { #[doc = "Bit 0 - OPAMP2 enable"] #[inline(always)] pub fn opamp2en(&self) -> OPAMP2EN_R { OPAMP2EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - FORCE_VP"] #[inline(always)] pub fn force_vp(&self) -> FORCE_VP_R { FORCE_VP_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bits 2:3 - OPAMP Non inverting input selection"] #[inline(always)] pub fn vp_sel(&self) -> VP_SEL_R { VP_SEL_R::new(((self.bits >> 2) & 0x03) as u8) } #[doc = "Bits 5:6 - OPAMP inverting input selection"] #[inline(always)] pub fn vm_sel(&self) -> VM_SEL_R { VM_SEL_R::new(((self.bits >> 5) & 0x03) as u8) } #[doc = "Bit 7 - Timer controlled Mux mode enable"] #[inline(always)] pub fn tcm_en(&self) -> TCM_EN_R { TCM_EN_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - OPAMP inverting input secondary selection"] #[inline(always)] pub fn vms_sel(&self) -> VMS_SEL_R { VMS_SEL_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bits 9:10 - OPAMP Non inverting input secondary selection"] #[inline(always)] pub fn vps_sel(&self) -> VPS_SEL_R { VPS_SEL_R::new(((self.bits >> 9) & 0x03) as u8) } #[doc = "Bit 11 - Calibration mode enable"] #[inline(always)] pub fn calon(&self) -> CALON_R { CALON_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bits 12:13 - Calibration selection"] #[inline(always)] pub fn calsel(&self) -> CALSEL_R { CALSEL_R::new(((self.bits >> 12) & 0x03) as u8) } #[doc = "Bits 14:17 - Gain in PGA mode"] #[inline(always)] pub fn pga_gain(&self) -> PGA_GAIN_R { PGA_GAIN_R::new(((self.bits >> 14) & 0x0f) as u8) } #[doc = "Bit 18 - User trimming enable"] #[inline(always)] pub fn user_trim(&self) -> USER_TRIM_R { USER_TRIM_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bits 19:23 - Offset trimming value (PMOS)"] #[inline(always)] pub fn trimoffsetp(&self) -> TRIMOFFSETP_R { TRIMOFFSETP_R::new(((self.bits >> 19) & 0x1f) as u8) } #[doc = "Bits 24:28 - Offset trimming value (NMOS)"] #[inline(always)] pub fn trimoffsetn(&self) -> TRIMOFFSETN_R { TRIMOFFSETN_R::new(((self.bits >> 24) & 0x1f) as u8) } #[doc = "Bit 29 - TSTREF"] #[inline(always)] pub fn tstref(&self) -> TSTREF_R { TSTREF_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - OPAMP ouput status flag"] #[inline(always)] pub fn outcal(&self) -> OUTCAL_R { OUTCAL_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - OPAMP lock"] #[inline(always)] pub fn lock(&self) -> LOCK_R { LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - OPAMP2 enable"] #[inline(always)] pub fn opamp2en(&mut self) -> OPAMP2EN_W { OPAMP2EN_W { w: self } } #[doc = "Bit 1 - FORCE_VP"] #[inline(always)] pub fn force_vp(&mut self) -> FORCE_VP_W { FORCE_VP_W { w: self } } #[doc = "Bits 2:3 - OPAMP Non inverting input selection"] #[inline(always)] pub fn vp_sel(&mut self) -> VP_SEL_W { VP_SEL_W { w: self } } #[doc = "Bits 5:6 - OPAMP inverting input selection"] #[inline(always)] pub fn vm_sel(&mut self) -> VM_SEL_W { VM_SEL_W { w: self } } #[doc = "Bit 7 - Timer controlled Mux mode enable"] #[inline(always)] pub fn tcm_en(&mut self) -> TCM_EN_W { TCM_EN_W { w: self } } #[doc = "Bit 8 - OPAMP inverting input secondary selection"] #[inline(always)] pub fn vms_sel(&mut self) -> VMS_SEL_W { VMS_SEL_W { w: self } } #[doc = "Bits 9:10 - OPAMP Non inverting input secondary selection"] #[inline(always)] pub fn vps_sel(&mut self) -> VPS_SEL_W { VPS_SEL_W { w: self } } #[doc = "Bit 11 - Calibration mode enable"] #[inline(always)] pub fn calon(&mut self) -> CALON_W { CALON_W { w: self } } #[doc = "Bits 12:13 - Calibration selection"] #[inline(always)] pub fn calsel(&mut self) -> CALSEL_W { CALSEL_W { w: self } } #[doc = "Bits 14:17 - Gain in PGA mode"] #[inline(always)] pub fn pga_gain(&mut self) -> PGA_GAIN_W { PGA_GAIN_W { w: self } } #[doc = "Bit 18 - User trimming enable"] #[inline(always)] pub fn user_trim(&mut self) -> USER_TRIM_W { USER_TRIM_W { w: self } } #[doc = "Bits 19:23 - Offset trimming value (PMOS)"] #[inline(always)] pub fn trimoffsetp(&mut self) -> TRIMOFFSETP_W { TRIMOFFSETP_W { w: self } } #[doc = "Bits 24:28 - Offset trimming value (NMOS)"] #[inline(always)] pub fn trimoffsetn(&mut self) -> TRIMOFFSETN_W { TRIMOFFSETN_W { w: self } } #[doc = "Bit 29 - TSTREF"] #[inline(always)] pub fn tstref(&mut self) -> TSTREF_W { TSTREF_W { w: self } } #[doc = "Bit 31 - OPAMP lock"] #[inline(always)] pub fn lock(&mut self) -> LOCK_W { LOCK_W { w: self } } }
use std::io::{self, Write}; use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; use nalgebra::{Point3, Translation3, UnitQuaternion, Vector3}; pub struct Client { socket: UdpSocket, target: SocketAddr, buf: Vec<u8>, } impl Client { pub fn new<A: ToSocketAddrs>(bind: A, target: SocketAddr) -> io::Result<Self> { let socket = UdpSocket::bind(bind)?; let client = Client { socket, target, buf: Vec::with_capacity(1024), }; Ok(client) } pub fn send<M: Message>(&mut self, message: M) -> io::Result<()> { let writer = OscPadWriter::new(&mut self.buf); message.encode(writer)?; self.socket.send_to(&self.buf, self.target)?; self.buf.clear(); Ok(()) } } pub trait Message { fn encode<W: Write>(&self, w: OscPadWriter<W>) -> io::Result<usize>; } pub struct PoseMessage { pub id: u32, pub is_valid: bool, pub wfd_rotation: UnitQuaternion<f64>, pub wfd_translation: Translation3<f64>, pub position: Point3<f64>, pub orientation: UnitQuaternion<f64>, pub velocity: Vector3<f64>, } impl Message for PoseMessage { fn encode<W: Write>(&self, mut w: OscPadWriter<W>) -> io::Result<usize> { let mut len = 0; len += w.write_string("/Tracker/Pose")?; len += w.write_string(",iiddddddddddddddddd")?; len += w.write_int(self.id as i32)?; len += w.write_int(if self.is_valid { 1 } else { 0 })?; len += w.write_double(self.wfd_rotation.w)?; len += w.write_double(self.wfd_rotation.i)?; len += w.write_double(self.wfd_rotation.j)?; len += w.write_double(self.wfd_rotation.k)?; len += w.write_double(self.wfd_translation.x)?; len += w.write_double(self.wfd_translation.y)?; len += w.write_double(self.wfd_translation.z)?; len += w.write_double(self.position.x)?; len += w.write_double(self.position.y)?; len += w.write_double(self.position.z)?; len += w.write_double(self.orientation.w)?; len += w.write_double(self.orientation.i)?; len += w.write_double(self.orientation.j)?; len += w.write_double(self.orientation.k)?; len += w.write_double(self.velocity.x)?; len += w.write_double(self.velocity.y)?; len += w.write_double(self.velocity.z)?; Ok(len) } } pub struct NoBodyMessage { pub id: u32, } impl Message for NoBodyMessage { fn encode<W: Write>(&self, mut w: OscPadWriter<W>) -> io::Result<usize> { let mut len = 0; len += w.write_string("/Tracker/NoBody")?; len += w.write_string(",i")?; len += w.write_int(self.id as i32)?; Ok(len) } } pub struct OscPadWriter<W> { inner: W, } impl<W> OscPadWriter<W> where W: Write, { pub fn new(inner: W) -> Self { Self { inner } } pub fn write_string(&mut self, s: &str) -> io::Result<usize> { let bytes = s.as_bytes(); let pad_len = 0b100 - (bytes.len() & 0b11); let pad = &[0u8; 4][..pad_len]; self.inner.write_all(bytes)?; self.inner.write_all(pad)?; Ok(bytes.len() + pad_len) } pub fn write_int(&mut self, u: i32) -> io::Result<usize> { self.inner.write_all(&u.to_be_bytes())?; Ok(4) } pub fn write_double(&mut self, d: f64) -> io::Result<usize> { self.inner.write_all(&d.to_be_bytes())?; Ok(8) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_write_string() { let mut buf = Vec::new(); let mut w = OscPadWriter::new(&mut buf); w.write_string("abc").unwrap(); assert_eq!(vec![0x61, 0x62, 0x63, 0x00], buf); } }
use crate::physics; use crate::physics::{EntityToBody, EventQueue, Gravity, RapierPhysicsScale}; use bevy::prelude::*; use rapier::dynamics::{IntegrationParameters, JointSet, RigidBodySet}; use rapier::geometry::{BroadPhase, ColliderSet, NarrowPhase}; use rapier::math::Vector; use rapier::pipeline::PhysicsPipeline; /// A plugin responsible for setting up a full Rapier physics simulation pipeline and resources. /// /// This will automatically setup all the resources needed to run a Rapier physics simulation including: /// - The physics pipeline. /// - The integration parameters. /// - The rigid-body, collider, and joint, sets. /// - The gravity. /// - The broad phase and narrow-phase. /// - The event queue. /// - Systems responsible for executing one physics timestep at each Bevy update stage. pub struct RapierPhysicsPlugin; impl Plugin for RapierPhysicsPlugin { fn build(&self, app: &mut AppBuilder) { app.add_resource(PhysicsPipeline::new()) .add_resource(IntegrationParameters::default()) .add_resource(Gravity(Vector::y() * -9.81)) .add_resource(BroadPhase::new()) .add_resource(NarrowPhase::new()) .add_resource(RigidBodySet::new()) .add_resource(ColliderSet::new()) .add_resource(JointSet::new()) .add_resource(RapierPhysicsScale(1.0)) .add_resource(EventQueue::new(true)) // TODO: can we avoid this map? We are only using this // to avoid some borrowing issue when joints creations // are needed. .add_resource(EntityToBody::new()) .add_system_to_stage_front( stage::PRE_UPDATE, physics::create_body_and_collider_system.system(), ) .add_system_to_stage(stage::PRE_UPDATE, physics::create_joints_system.system()) .add_system_to_stage(stage::UPDATE, physics::step_world_system.system()) .add_system_to_stage(stage::POST_UPDATE, physics::sync_transform_system.system()); } }
// 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::collections::BTreeMap; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; use chrono::DateTime; use chrono::Utc; use common_exception::ErrorCode; use common_exception::Result; use common_io::constants::NAN_BYTES_SNAKE; use common_io::escape_string; use crate::principal::UserIdentity; use crate::storage::StorageParams; // -- Internal stage // CREATE [ OR REPLACE ] [ TEMPORARY ] STAGE [ IF NOT EXISTS ] <internal_stage_name> // internalStageParams // directoryTableParams // [ FILE_FORMAT = ( { FORMAT_NAME = '<file_format_name>' | TYPE = { CSV | JSON | AVRO | ORC | PARQUET | XML } [ formatTypeOptions ] ) } ] // [ COPY_OPTIONS = ( copyOptions ) ] // [ COMMENT = '<string_literal>' ] // // -- External stage // CREATE [ OR REPLACE ] [ TEMPORARY ] STAGE [ IF NOT EXISTS ] <external_stage_name> // externalStageParams // directoryTableParams // [ FILE_FORMAT = ( { FORMAT_NAME = '<file_format_name>' | TYPE = { CSV | JSON | AVRO | ORC | PARQUET | XML } [ formatTypeOptions ] ) } ] // [ COPY_OPTIONS = ( copyOptions ) ] // [ COMMENT = '<string_literal>' ] // // // WHERE // // externalStageParams (for Amazon S3) ::= // URL = 's3://<bucket>[/<path>/]' // [ { CREDENTIALS = ( { { AWS_KEY_ID = '<string>' AWS_SECRET_KEY = '<string>' [ AWS_TOKEN = '<string>' ] } | AWS_ROLE = '<string>' } ) ) } ] // // copyOptions ::= // ON_ERROR = { CONTINUE | SKIP_FILE | SKIP_FILE_<num> | SKIP_FILE_<num>% | ABORT_STATEMENT } // SIZE_LIMIT = <num> #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)] pub enum StageType { /// LegacyInternal will be deprecated. /// /// Please never use this variant except in `proto_conv`. We keep this /// stage type for backword compatible. /// /// TODO(xuanwo): remove this when we are releasing v0.9. LegacyInternal, External, Internal, /// User Stage is the stage for every sql user. /// /// This is a stage that just in memory. We will not persist in metasrv User, } impl fmt::Display for StageType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let name = match self { // LegacyInternal will print the same name as Internal, this is by design. StageType::LegacyInternal => "Internal", StageType::External => "External", StageType::Internal => "Internal", StageType::User => "User", }; write!(f, "{}", name) } } impl Default for StageType { fn default() -> Self { Self::External } } #[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, Eq, PartialEq)] pub enum StageFileCompression { Auto, Gzip, Bz2, Brotli, Zstd, Deflate, RawDeflate, Lzo, Snappy, Xz, None, } impl StageFileFormatType { pub fn has_inner_schema(&self) -> bool { matches!(self, StageFileFormatType::Parquet) } } impl Default for StageFileCompression { fn default() -> Self { Self::None } } impl FromStr for StageFileCompression { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, String> { match s.to_lowercase().as_str() { "auto" => Ok(StageFileCompression::Auto), "gzip" => Ok(StageFileCompression::Gzip), "bz2" => Ok(StageFileCompression::Bz2), "brotli" => Ok(StageFileCompression::Brotli), "zstd" => Ok(StageFileCompression::Zstd), "deflate" => Ok(StageFileCompression::Deflate), "rawdeflate" | "raw_deflate" => Ok(StageFileCompression::RawDeflate), "lzo" => Ok(StageFileCompression::Lzo), "snappy" => Ok(StageFileCompression::Snappy), "xz" => Ok(StageFileCompression::Xz), "none" => Ok(StageFileCompression::None), _ => Err("Unknown file compression type, must one of { auto | gzip | bz2 | brotli | zstd | deflate | raw_deflate | lzo | snappy | xz | none }" .to_string()), } } } impl ToString for StageFileCompression { fn to_string(&self) -> String { match *self { StageFileCompression::Auto => "auto".to_string(), StageFileCompression::Gzip => "gzip".to_string(), StageFileCompression::Bz2 => "bz2".to_string(), StageFileCompression::Brotli => "brotli".to_string(), StageFileCompression::Zstd => "zstd".to_string(), StageFileCompression::Deflate => "deflate".to_string(), StageFileCompression::RawDeflate => "raw_deflate".to_string(), StageFileCompression::Lzo => "lzo".to_string(), StageFileCompression::Snappy => "snappy".to_string(), StageFileCompression::Xz => "xz".to_string(), StageFileCompression::None => "none".to_string(), } } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)] pub enum StageFileFormatType { Csv, Tsv, Json, NdJson, Avro, Orc, Parquet, Xml, None, } impl Default for StageFileFormatType { fn default() -> Self { Self::Parquet } } impl FromStr for StageFileFormatType { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, String> { match s.to_uppercase().as_str() { "CSV" => Ok(StageFileFormatType::Csv), "TSV" | "TABSEPARATED" => Ok(StageFileFormatType::Tsv), "NDJSON" | "JSONEACHROW" => Ok(StageFileFormatType::NdJson), "PARQUET" => Ok(StageFileFormatType::Parquet), "XML" => Ok(StageFileFormatType::Xml), "JSON" => Ok(StageFileFormatType::Json), "ORC" | "AVRO" => Err(format!( "File format type '{s}' not implemented yet', must be one of ( CSV | TSV | NDJSON | PARQUET | XML)" )), _ => Err(format!( "Unknown file format type '{s}', must be one of ( CSV | TSV | NDJSON | PARQUET | XML)" )), } } } impl ToString for StageFileFormatType { fn to_string(&self) -> String { format!("{:?}", *self) } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(default)] pub struct FileFormatOptions { pub format: StageFileFormatType, // Number of lines at the start of the file to skip. pub skip_header: u64, pub field_delimiter: String, pub record_delimiter: String, pub nan_display: String, pub escape: String, pub compression: StageFileCompression, pub row_tag: String, pub quote: String, pub name: Option<String>, } impl Default for FileFormatOptions { fn default() -> Self { Self { format: StageFileFormatType::default(), record_delimiter: "\n".to_string(), field_delimiter: ",".to_string(), nan_display: NAN_BYTES_SNAKE.to_string(), skip_header: 0, escape: "".to_string(), compression: StageFileCompression::default(), row_tag: "row".to_string(), quote: "".to_string(), name: None, } } } impl FileFormatOptions { pub fn new() -> Self { Self { format: StageFileFormatType::None, field_delimiter: "".to_string(), record_delimiter: "".to_string(), nan_display: "".to_string(), skip_header: 0, escape: "".to_string(), compression: StageFileCompression::None, row_tag: "".to_string(), quote: "".to_string(), name: None, } } pub fn from_map(opts: &BTreeMap<String, String>) -> Result<Self> { let mut file_format_options = Self::new(); file_format_options.apply(opts, false)?; if file_format_options.format == StageFileFormatType::None { return Err(ErrorCode::SyntaxException( "File format type must be specified", )); } Ok(file_format_options) } pub fn default_by_type(format_type: StageFileFormatType) -> Self { let mut options = Self::default(); match &format_type { StageFileFormatType::Csv => { options.quote = "\"".to_string(); } StageFileFormatType::Tsv => { options.field_delimiter = "\t".to_string(); options.escape = "\\".to_string(); } _ => {} } options } pub fn apply(&mut self, opts: &BTreeMap<String, String>, ignore_unknown: bool) -> Result<()> { if opts.is_empty() { return Ok(()); } for (k, v) in opts.iter() { match k.as_str() { "format" | "type" => { let format = StageFileFormatType::from_str(v)?; self.format = format; } "skip_header" => { let skip_header = u64::from_str(v)?; self.skip_header = skip_header; } "field_delimiter" => self.field_delimiter = v.clone(), "record_delimiter" => self.record_delimiter = v.clone(), "nan_display" => self.nan_display = v.clone(), "escape" => self.escape = v.clone(), "compression" => { let compression = StageFileCompression::from_str(v)?; self.compression = compression; } "row_tag" => self.row_tag = v.clone(), "quote" => self.quote = v.clone(), _ => { if !ignore_unknown { return Err(ErrorCode::BadArguments(format!( "Unknown stage file format option {}", k ))); } } } } Ok(()) } } impl Display for FileFormatOptions { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "TYPE = {}", self.format.to_string().to_uppercase())?; match self.format { StageFileFormatType::Csv => { write!( f, " FIELD_DELIMITER = '{}'", escape_string(&self.field_delimiter) )?; write!( f, " RECORD_DELIMITER = '{}'", escape_string(&self.record_delimiter) )?; write!(f, " QUOTE = '{}'", escape_string(&self.quote))?; write!(f, " ESCAPE = '{}'", escape_string(&self.escape))?; write!(f, " SKIP_HEADER = {}", &self.skip_header)?; write!(f, " NAN_DISPLAY = '{}'", escape_string(&self.nan_display))?; } StageFileFormatType::Tsv => { write!( f, " FIELD_DELIMITER = '{}'", escape_string(&self.field_delimiter) )?; write!( f, " RECORD_DELIMITER = '{}'", escape_string(&self.record_delimiter) )?; } StageFileFormatType::Xml => { write!(f, " ROW_TAG = {}", escape_string(&self.row_tag))?; } _ => {} } Ok(()) } } #[derive(serde::Serialize, serde::Deserialize, Default, Clone, Debug, Eq, PartialEq)] #[serde(default)] pub struct StageParams { pub storage: StorageParams, } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)] pub enum OnErrorMode { Continue, SkipFileNum(u64), AbortNum(u64), } impl Default for OnErrorMode { fn default() -> Self { Self::AbortNum(1) } } impl Display for OnErrorMode { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { OnErrorMode::Continue => { write!(f, "continue") } OnErrorMode::SkipFileNum(n) => { if *n <= 1 { write!(f, "skipfile") } else { write!(f, "skipfile_{}", n) } } OnErrorMode::AbortNum(n) => { if *n <= 1 { write!(f, "abort") } else { write!(f, "abort_{}", n) } } } } } impl FromStr for OnErrorMode { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, String> { match s.to_uppercase().as_str() { "" | "ABORT" => Ok(OnErrorMode::AbortNum(1)), "CONTINUE" => Ok(OnErrorMode::Continue), "SKIP_FILE" => Ok(OnErrorMode::SkipFileNum(1)), v => { if v.starts_with("ABORT_") { let num_str = v.replace("ABORT_", ""); let nums = num_str.parse::<u64>(); match nums { Ok(n) if n < 1 => { Err("OnError mode `ABORT_<num>` num must be greater than 0".to_string()) } Ok(n) => Ok(OnErrorMode::AbortNum(n)), Err(_) => Err(format!( "Unknown OnError mode:{:?}, must one of {{ CONTINUE | SKIP_FILE | SKIP_FILE_<num> | ABORT | ABORT_<num> }}", v )), } } else { let num_str = v.replace("SKIP_FILE_", ""); let nums = num_str.parse::<u64>(); match nums { Ok(n) if n < 1 => { Err("OnError mode `SKIP_FILE_<num>` num must be greater than 0" .to_string()) } Ok(n) => Ok(OnErrorMode::SkipFileNum(n)), Err(_) => Err(format!( "Unknown OnError mode:{:?}, must one of {{ CONTINUE | SKIP_FILE | SKIP_FILE_<num> | ABORT | ABORT_<num> }}", v )), } } } } } } #[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug, Eq, PartialEq)] #[serde(default)] pub struct CopyOptions { pub on_error: OnErrorMode, pub size_limit: usize, pub split_size: usize, pub purge: bool, pub single: bool, pub max_file_size: usize, } impl CopyOptions { pub fn apply(&mut self, opts: &BTreeMap<String, String>, ignore_unknown: bool) -> Result<()> { if opts.is_empty() { return Ok(()); } for (k, v) in opts.iter() { match k.as_str() { "on_error" => { let on_error = OnErrorMode::from_str(v)?; self.on_error = on_error; } "size_limit" => { let size_limit = usize::from_str(v)?; self.size_limit = size_limit; } "split_size" => { let split_size = usize::from_str(v)?; self.split_size = split_size; } "purge" => { let purge = bool::from_str(v).map_err(|_| { ErrorCode::StrParseError(format!("Cannot parse purge: {} as bool", v)) })?; self.purge = purge; } "single" => { let single = bool::from_str(v).map_err(|_| { ErrorCode::StrParseError(format!("Cannot parse single: {} as bool", v)) })?; self.single = single; } "max_file_size" => { let max_file_size = usize::from_str(v)?; self.max_file_size = max_file_size; } _ => { if !ignore_unknown { return Err(ErrorCode::BadArguments(format!( "Unknown stage copy option {}", k ))); } } } } Ok(()) } } #[derive(serde::Serialize, serde::Deserialize, Default, Clone, Debug, Eq, PartialEq)] #[serde(default)] pub struct StageInfo { pub stage_name: String, pub stage_type: StageType, pub stage_params: StageParams, pub file_format_options: FileFormatOptions, pub copy_options: CopyOptions, pub comment: String, /// TODO(xuanwo): stage doesn't have this info anymore, remove it. pub number_of_files: u64, pub creator: Option<UserIdentity>, } impl StageInfo { /// Create a new internal stage. pub fn new_internal_stage(name: &str) -> StageInfo { StageInfo { stage_name: name.to_string(), stage_type: StageType::Internal, ..Default::default() } } pub fn new_external_stage(storage: StorageParams, path: &str) -> StageInfo { StageInfo { stage_name: format!("{storage},path={path}"), stage_type: StageType::External, stage_params: StageParams { storage }, ..Default::default() } } /// Create a new user stage. pub fn new_user_stage(user: &str) -> StageInfo { StageInfo { stage_name: user.to_string(), stage_type: StageType::User, ..Default::default() } } /// Update user stage with stage name. pub fn with_stage_name(mut self, name: &str) -> StageInfo { self.stage_name = name.to_string(); self } /// Get the prefix of stage. /// /// Use this function to get the prefix of this stage in the data operator. /// /// # Notes /// /// This function should never be called on external stage because it's meanless. Something must be wrong. pub fn stage_prefix(&self) -> String { match self.stage_type { StageType::LegacyInternal => format!("/stage/{}/", self.stage_name), StageType::External => { unreachable!("stage_prefix should never be called on external stage, must be a bug") } StageType::Internal => format!("/stage/internal/{}/", self.stage_name), StageType::User => format!("/stage/user/{}/", self.stage_name), } } } #[derive(Default, Debug, Clone, PartialEq, Eq)] pub struct StageFile { pub path: String, pub size: u64, pub md5: Option<String>, pub last_modified: DateTime<Utc>, pub creator: Option<UserIdentity>, pub etag: Option<String>, }
use std::collections::HashMap; fn main() { } fn create_shift_substitutions(n: i32) -> (HashMap<char, char>, HashMap<char, char>) { let mut encoding: HashMap<char, char> = HashMap::new(); let mut decoding: HashMap<char, char> = HashMap::new(); let ascii_char = get_ascii(); let alphabet_size = &ascii_char.len(); let nsize = n as usize; for i in 0usize..*alphabet_size { let letter = &ascii_char[i]; let subst_letter = &ascii_char[(i + nsize) % alphabet_size]; encoding[&letter] = *subst_letter; decoding[&subst_letter] = *letter; } (encoding, decoding) } fn get_ascii() -> Vec<char> { let mut res = Vec::new(); let ascii = (b'A'..=b'Z').map(char::from); for x in ascii { res.push(x); } res }
#[macro_use] extern crate log; extern crate net_gazer_core as core; use core::*; use pnet::packet::ethernet::EthernetPacket; use pnet::datalink::NetworkInterface; const ID:u8=core::PLUGIN_ID_DEMO; const NAME:&str="Demo plugin"; #[derive(Default)] pub struct DemoPlugin; impl Plugin for DemoPlugin{ fn get_name(&self)->&str{NAME} fn get_id(&self) -> u8 {ID} fn on_load(&mut self, _iface:&NetworkInterface, _tx:CoreSender){ env_logger::init(); info!("Hello from \"{}\"(message_id:{}), ! ", NAME, ID); } fn on_unload(&mut self){ info!("Good bye from \"{}\"(message_id:{})! ", NAME, ID); } fn process(&self, _pkt:&EthernetPacket){ info!("Processing with \"{}\"(message_id:{})", NAME,ID); } } #[no_mangle] pub extern "C" fn net_gazer_plugin_new () -> * mut dyn Plugin{ let boxed:Box<DemoPlugin> = Box::new(DemoPlugin::default()); Box::into_raw(boxed) }
use async_trait::async_trait; use chrono::{Duration, Utc}; use crate::db::{self, Db}; pub async fn save_credentials( db: &Db, true_layer: &true_layer::Client, token_res: true_layer::TokenResponse, ) -> anyhow::Result<String> { let metadata = true_layer.token_metadata(&token_res.access_token).await?; let expires_at = Utc::now() + Duration::seconds(token_res.expires_in); let id = &metadata.provider.provider_id; let access_token = &token_res.access_token; let refresh_token = &token_res.refresh_token; db::providers::update_credentials(db, id, access_token, expires_at, refresh_token).await?; Ok(token_res.access_token) } pub async fn fetch_provider_accounts( db: &Db, true_layer: &true_layer::Client, provider: &str, ) -> anyhow::Result<()> { let accounts = true_layer.accounts(&provider).await?; for account in accounts { let id = &account.account_id; let name = &account.display_name; let created = db::accounts::insert(db, id, &provider, name).await?; if created { log::info!("new account '{}' added to db", account.display_name); } else { log::info!("account '{}' already exists", account.display_name); } } Ok(()) } pub struct AuthProvider(Db); impl AuthProvider { pub fn new(db: Db) -> AuthProvider { AuthProvider(db) } } #[async_trait] impl true_layer::AuthProvider for AuthProvider { async fn token_for_provider( &self, true_layer: &true_layer::Client, provider_id: &str, ) -> anyhow::Result<String> { let (access_token, expires_at, refresh_token) = db::providers::credentials(&self.0, provider_id).await?; if expires_at > Utc::now() { return Ok(access_token); } let token_res = true_layer.renew_token(&refresh_token).await?; let access_token = save_credentials(&self.0, true_layer, token_res).await?; Ok(access_token) } async fn token_for_account( &self, true_layer: &true_layer::Client, account_id: &str, ) -> anyhow::Result<String> { let (access_token, expires_at, refresh_token) = db::accounts::credentials(&self.0, account_id).await?; if expires_at > Utc::now() { return Ok(access_token); } let token_res = true_layer.renew_token(&refresh_token).await?; let access_token = save_credentials(&self.0, true_layer, token_res).await?; Ok(access_token) } }
#[doc = "Reader of register CCONF"] pub type R = crate::R<u8, super::CCONF>; #[doc = "Writer for register CCONF"] pub type W = crate::W<u8, super::CCONF>; #[doc = "Register CCONF `reset()`'s with value 0"] impl crate::ResetValue for super::CCONF { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RXEDMA`"] pub type RXEDMA_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXEDMA`"] pub struct RXEDMA_W<'a> { w: &'a mut W, } impl<'a> RXEDMA_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) | ((value as u8) & 0x01); self.w } } #[doc = "Reader of field `TXEDMA`"] pub type TXEDMA_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXEDMA`"] pub struct TXEDMA_W<'a> { w: &'a mut W, } impl<'a> TXEDMA_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 << 1)) | (((value as u8) & 0x01) << 1); self.w } } impl R { #[doc = "Bit 0 - TX Early DMA Enable"] #[inline(always)] pub fn rxedma(&self) -> RXEDMA_R { RXEDMA_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TX Early DMA Enable"] #[inline(always)] pub fn txedma(&self) -> TXEDMA_R { TXEDMA_R::new(((self.bits >> 1) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TX Early DMA Enable"] #[inline(always)] pub fn rxedma(&mut self) -> RXEDMA_W { RXEDMA_W { w: self } } #[doc = "Bit 1 - TX Early DMA Enable"] #[inline(always)] pub fn txedma(&mut self) -> TXEDMA_W { TXEDMA_W { w: self } } }
use std::collections::BTreeMap; use rustc_serialize::json::{Json,ToJson}; use parse::*; use record::Record; use message::Message; use method::SetError; make_prop_type!(MessageCopy, "MessageCopy", message_id: String => "messageId", mailbox_ids: Vec<String> => "mailboxIds", is_unread: bool => "isUnread", is_flagged: bool => "isFlagged", is_answered: bool => "isAnswered", is_draft: bool => "isDraft" ); make_method_args_type!(CopyMessagesRequestArgs, "CopyMessagesRequestArgs", from_account_id: Presence<String> => "accountId", to_account_id: Presence<String> => "accountId", messages: BTreeMap<String,MessageCopy> => "messages" ); make_method_args_type!(CopyMessagesResponseArgs, "CopyMessagesResponseArgs", from_account_id: String => "accountId", to_account_id: String => "accountId", created: BTreeMap<String,<Message as Record>::Partial> => "created", not_created: BTreeMap<String,SetError> => "notCreated" );
use crate::accessor; use crate::{Buffer, Skin}; /// Inverse Bind Matrices of type `[[f32; 4]; 4]`. pub type ReadInverseBindMatrices<'a> = accessor::Iter<'a, [[f32; 4]; 4]>; /// Skin reader. #[derive(Clone, Debug)] pub struct Reader<'a, 's, F> where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, { pub(crate) skin: Skin<'a>, pub(crate) get_buffer_data: F, } impl<'a, 's, F> Reader<'a, 's, F> where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, { /// Returns an `Iterator` that reads the inverse bind matrices of /// the skin. pub fn read_inverse_bind_matrices(&self) -> Option<ReadInverseBindMatrices<'s>> { if let Some(accessor) = self.skin.inverse_bind_matrices() { if let Some(slice) = (self.get_buffer_data)(accessor.view().buffer()) { return Some(accessor::Iter::new(accessor, slice)) } } None } }
use std::path::Path; use std::fs; use regex::Regex; use node_version::NodeVersion; use home_directory::HomeDirectory; pub struct Ls { home: HomeDirectory } impl Ls { fn is_directory<P: AsRef<Path>>(&self, path: P) -> bool { match fs::metadata(path) { Ok(metadata) => metadata.is_dir(), Err(_) => false } } fn directory_name(&self, full_path: &String) -> String { let components = Path::new(full_path).components(); components.last().unwrap() .as_os_str() .to_str() .unwrap() .into() } fn is_version_directory(&self, path: &String) -> bool { let re = Regex::new(r"\d+\.\d+\.\d+").unwrap(); re.is_match(path) } fn follow_symlink(&self) -> Option<String> { let path = fs::read_link(Path::new(&self.home.language_dir).join("bin")); if path.is_err() { match fs::read_link(Path::new(&self.home.language_dir).join("bin").join("node")) { Ok(p) => Some(p.as_os_str() .to_str() .unwrap() .into()), Err(_) => None } } else { Some(path.unwrap() .as_os_str() .to_str() .unwrap() .into()) } } pub fn new(home: HomeDirectory) -> Ls { Ls { home: home } } pub fn current_version(&self) -> Option<NodeVersion> { let re = Regex::new(r"\d+\.\d+\.\d+").unwrap(); let path_str = match self.follow_symlink() { Some(p) => p, None => return None }; match re.captures_iter(&path_str).next() { Some(m) => { match m.at(0) { Some(version) => { Some(NodeVersion { name: version.to_string(), path: path_str.replace("/bin", "").to_string() }) } None => None } }, None => Some(NodeVersion{ name: path_str.to_string(), path: path_str.to_string() }) } } pub fn ls_versions(&self) -> Vec<NodeVersion> { if !self.home.is_present() { return vec!(); } let mut installed_versions = Vec::new(); for path in fs::read_dir(&self.home.language_dir).unwrap() { let path_str = path.unwrap().path().display().to_string(); if self.is_directory(&path_str) && self.is_version_directory(&path_str) { let version = NodeVersion{ name: self.directory_name(&path_str), path: path_str.to_string() }; installed_versions.push(version); } } installed_versions } }
#[cfg(feature = "async")] use crate::protocol::util_async; #[cfg(feature = "sync")] use crate::protocol::util_sync; #[cfg(feature = "sync")] use byteorder::{LittleEndian, ReadBytesExt}; use crate::{ protocol::{parts::field_metadata::InnerFieldMetadata, util}, FieldMetadata, HdbResult, TypeId, }; use std::{ops::Deref, sync::Arc}; use vec_map::VecMap; /// List of metadata of the fields of a resultset. #[derive(Debug)] pub struct ResultSetMetadata(Vec<FieldMetadata>); impl Deref for ResultSetMetadata { type Target = Vec<FieldMetadata>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::fmt::Display for ResultSetMetadata { // Writes a header and then the data fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { writeln!(fmt)?; for field_metadata in &self.0 { write!(fmt, "{}, ", field_metadata.displayname())?; } writeln!(fmt)?; Ok(()) } } impl ResultSetMetadata { #[cfg(feature = "sync")] pub(crate) fn parse_sync(count: usize, rdr: &mut dyn std::io::Read) -> HdbResult<Self> { let mut inner_fms = Vec::<InnerFieldMetadata>::new(); let mut names = VecMap::<String>::new(); trace!("ResultSetMetadata::parse_sync: Got count = {count}"); for _ in 0..count { let column_options = rdr.read_u8()?; let type_code = rdr.read_u8()?; let scale = rdr.read_i16::<LittleEndian>()?; let precision = rdr.read_i16::<LittleEndian>()?; rdr.read_i16::<LittleEndian>()?; let tablename_idx = rdr.read_u32::<LittleEndian>()?; add_to_names(&mut names, tablename_idx); let schemaname_idx = rdr.read_u32::<LittleEndian>()?; add_to_names(&mut names, schemaname_idx); let columnname_idx = rdr.read_u32::<LittleEndian>()?; add_to_names(&mut names, columnname_idx); let displayname_idx = rdr.read_u32::<LittleEndian>()?; add_to_names(&mut names, displayname_idx); let type_id = TypeId::try_new(type_code)?; inner_fms.push(InnerFieldMetadata::new( schemaname_idx, tablename_idx, columnname_idx, displayname_idx, column_options, type_id, scale, precision, )); } // now we read the names let mut offset = 0; for _ in 0..names.len() { let nl = rdr.read_u8()?; let name = util::string_from_cesu8(util_sync::parse_bytes(nl as usize, rdr)?) .map_err(util::io_error)?; trace!("offset = {offset}, name = {name}"); names.insert(offset as usize, name); offset += u32::from(nl) + 1; } let names = Arc::new(names); Ok(ResultSetMetadata( inner_fms .into_iter() .map(|inner| FieldMetadata::new(inner, Arc::clone(&names))) .collect(), )) } #[cfg(feature = "async")] pub(crate) async fn parse_async<R: std::marker::Unpin + tokio::io::AsyncReadExt>( count: usize, rdr: &mut R, ) -> HdbResult<Self> { let mut inner_fms = Vec::<InnerFieldMetadata>::new(); let mut names = VecMap::<String>::new(); trace!("ResultSetMetadata::parse_sync: Got count = {count}"); for _ in 0..count { let column_options = rdr.read_u8().await?; let type_code = rdr.read_u8().await?; let scale = rdr.read_i16_le().await?; let precision = rdr.read_i16_le().await?; rdr.read_i16_le().await?; let tablename_idx = rdr.read_u32_le().await?; add_to_names(&mut names, tablename_idx); let schemaname_idx = rdr.read_u32_le().await?; add_to_names(&mut names, schemaname_idx); let columnname_idx = rdr.read_u32_le().await?; add_to_names(&mut names, columnname_idx); let displayname_idx = rdr.read_u32_le().await?; add_to_names(&mut names, displayname_idx); let type_id = TypeId::try_new(type_code)?; inner_fms.push(InnerFieldMetadata::new( schemaname_idx, tablename_idx, columnname_idx, displayname_idx, column_options, type_id, scale, precision, )); } // now we read the names let mut offset = 0; for _ in 0..names.len() { let nl = rdr.read_u8().await?; let name = util::string_from_cesu8(util_async::parse_bytes(nl as usize, rdr).await?) .map_err(util::io_error)?; trace!("offset = {offset}, name = {name}"); names.insert(offset as usize, name); offset += u32::from(nl) + 1; } let names = Arc::new(names); Ok(ResultSetMetadata( inner_fms .into_iter() .map(|inner| FieldMetadata::new(inner, Arc::clone(&names))) .collect(), )) } } fn add_to_names(names: &mut VecMap<String>, offset: u32) { if offset != u32::max_value() { let offset = offset as usize; if !names.contains_key(offset) { names.insert(offset, String::new()); }; } }
use std::{convert::{Into, TryFrom}, fmt, ops::{Index, IndexMut}, str}; use serde::{Deserialize, Serialize}; use crate::*; /// Cargo - map of resource amounts by resource type /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#Resources> #[derive(Clone, Copy, Default, fmt::Debug)] pub struct Cargo { /// Amount of wood held by Unit pub wood: ResourceAmount, /// Amount of coal held by Unit pub coal: ResourceAmount, /// Amount of uranium held by Unit pub uranium: ResourceAmount, } impl Index<ResourceType> for Cargo { type Output = ResourceAmount; /// Returns amount of resource for given [`ResourceType`] /// /// # Arguments: /// /// - `self` - reference to Self /// - `resource_type` - type of [`Resource`] /// /// Returns: /// /// [`ResourceAmount`] fn index(&self, resource_type: ResourceType) -> &Self::Output { match resource_type { ResourceType::Wood => &self.wood, ResourceType::Coal => &self.coal, ResourceType::Uranium => &self.uranium, } } } impl IndexMut<ResourceType> for Cargo { /// Returns mutable reference to amount of resource for given /// [`ResourceType`] /// /// # Arguments: /// /// - `self` - reference to Self /// - `resource_type` - type of [`Resource`] /// /// Returns: /// /// mutable reference to [`ResourceAmount`] fn index_mut(&mut self, resource_type: ResourceType) -> &mut Self::Output { match resource_type { ResourceType::Wood => &mut self.wood, ResourceType::Coal => &mut self.coal, ResourceType::Uranium => &mut self.uranium, } } } /// Represents type of Unit /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#Units> #[derive(Eq, PartialEq, Clone, Copy, fmt::Debug, Hash, Serialize, Deserialize)] #[serde(try_from = "String", into = "String")] pub enum UnitType { /// Worker unit Worker, /// Cart unit Cart, } /// Convert from command argument impl str::FromStr for UnitType { type Err = LuxAiError; fn from_str(string: &str) -> Result<Self, Self::Err> { let value = match string { "0" => Self::Worker, "1" => Self::Cart, _ => Err(Self::Err::UnknownUnit(string.to_string()))?, }; Ok(value) } } /// Convert from SCREAMING_SNAKE_CASE string impl TryFrom<String> for UnitType { type Error = LuxAiError; fn try_from(string: String) -> Result<Self, Self::Error> { let value = match string.as_str() { "WORKER" => Self::Worker, "CART" => Self::Cart, _ => Err(Self::Error::UnknownUnit(string.to_string()))?, }; Ok(value) } } /// Convert into SCREAMING_SNAKE_CASE string impl Into<String> for UnitType { fn into(self) -> String { match self { Self::Worker => "WORKER".to_string(), Self::Cart => "CART".to_string(), } } } impl UnitType { /// Returns cargo space available for unit /// /// # Examples /// /// ``` /// let space = UnitType::Worker::cargo_space_available(); /// ``` /// /// # Arguments /// /// - `self` - reference to Self /// /// # Returns /// /// [`ResourceAmount`] that given unit type can hold /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#Units> pub fn cargo_space_available(&self) -> ResourceAmount { GAME_CONSTANTS.parameters.resource_capacity[self] } } /// Represents Unit on [`GameMap`] #[derive(Clone, fmt::Debug)] pub struct Unit { /// [`Position`] of unit on 2D grid pub pos: Position, /// Team, whom unit belongs to pub team: TeamId, /// Unit id, used in command arguments pub id: EntityId, /// Amount of turns to next action /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#Cooldown> pub cooldown: Cooldown, /// [`Cargo`], map amount of resources by types pub cargo: Cargo, /// Type of unit pub unit_type: UnitType, } impl Unit { /// Creates new [`CityTile`] /// /// # Parameters /// /// - `team_id` - Team id, whom this city belongs to /// - `unit_type` - Unit type of /// - `unit_id` - Unit id used as command arguments /// - `position` - Where city tile is located /// - `cooldown` - turns to next action /// /// # Returns /// /// A new created [`Unit`] /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#Units> pub fn new( team: TeamId, unit_type: UnitType, id: EntityId, pos: Position, cooldown: Cooldown, ) -> Self { Self { team, unit_type, id, pos, cooldown, cargo: Cargo::default(), } } /// Returns sum of all resource amounts in Unit's cargo /// /// # Parameters /// /// - `self` - Self reference /// /// # Returns /// /// Cargo space used by all resources, [`ResourceAmount`] pub fn cargo_space_used(&self) -> ResourceAmount { ResourceType::VALUES .into_iter() .map(|resource_type| self.cargo[resource_type]) .sum() } /// Returns free cargo space (space available - space used) /// /// Note that any Resource takes up the same space, e.g. 70 wood takes up as /// much space as 70 uranium, but 70 uranium would produce much more fuel /// than wood when deposited at a City /// /// # Parameters /// /// - `self` - Self reference /// /// # Returns /// /// Free cargo space, [`ResourceAmount`] pub fn get_cargo_space_left(&self) -> ResourceAmount { self.unit_type.cargo_space_available() - self.cargo_space_used() } /// Check if [`Unit`] can perform action, i.e. cooldown is less than 1 /// /// # Parameters /// /// - `self` - reference to Self /// /// # Returns /// /// `bool` value /// /// # See also /// /// Check <https://www.lux-ai.org/specs-2021#Cooldown> pub fn can_act(&self) -> bool { self.cooldown < 1.0 } /// Check if Unit can build [`CityTile`], i.e. cooldown is less than 1 and /// unit is worker and cell not has resource and amount of resources is /// greater or equal than needed /// /// # Parameters /// /// - `self` - reference to Self /// - `game_map` - reference to [`GameMap`] /// /// # Returns /// /// `true` if the [`Unit`] can build a [`City`] on the tile it is on now. pub fn can_build(&self, game_map: &GameMap) -> bool { let ref cell = game_map[self.pos]; self.unit_type == UnitType::Worker && !cell.has_resource() && self.can_act() && self.cargo_space_used() >= City::city_build_cost() } /// Check if Unit can pillage road, i.e. cooldown is 0 and unit is worker /// and road development progress > 0 /// /// # Parameters /// /// - `self` - reference to Self /// - `game_map` - reference to `GameMap` /// /// # Returns /// /// `bool` value pub fn can_pillage(&self, game_map: &GameMap) -> bool { let ref cell = game_map[self.pos]; self.unit_type == UnitType::Worker && self.can_act() && cell.road > 0.0 } /// Returns action to move unit to given `direction` /// /// When applied, Unit will move in the specified direction by one Unit, /// provided there are no other units in the way or opposition cities. /// (Units can stack on top of each other however when over a friendly City) /// /// # Parameters /// /// - `self` - reference to Self /// - `direction` - [`Direction`] to move to /// /// # Returns /// /// Action to perform pub fn move_(&self, direction: Direction) -> Action { format!("{} {} {}", Commands::MOVE, self.id, direction.to_argument()) } /// Returns action to transfer resource to other (`to_unit`) [`Unit`] /// /// # Parameters /// /// - `self` - reference to Self /// - `to_unit` - [`Unit`] reference, transfered to /// - `resource_type` - [`ResourceType`] of transfering resource /// - `resource_amount` - [`ResourceAmount`] of transfering resource /// /// # Returns /// /// Action to perform pub fn transfer( &self, to_unit: &Unit, resource_type: ResourceType, resource_amount: ResourceAmount, ) -> Action { format!( "{} {} {} {} {}", Commands::TRANSFER, self.id, to_unit.id, resource_type.to_argument(), resource_amount ) } /// Returns action to build [`City`] /// /// # Parameters /// /// - `self` - reference to Self /// /// # Returns /// /// Action to perform pub fn build_city(&self) -> Action { format!("{} {}", Commands::BUILD_CITY, self.id) } /// Returns action to pillage road /// /// # Parameters /// /// - `self` - reference to Self /// /// # Returns /// /// Action to perform pub fn pillage(&self) -> Action { format!("{} {}", Commands::PILLAGE, self.id) } }
use fraction::ToPrimitive; use crate::io::*; pub const _MAX_LYRICS_LINE_COUNT: u8 = 5; /// Struct to keep lyrics /// On guitar pro files (gp4 or later), you can have 5 lines of lyrics. /// It is store on a BTreeMap: /// * the key is the mesure number. The start mesure is 1 /// * the value is the text. Syntax: /// * " " (spaces or carry returns): separates the syllables of a word /// * "+": merge two syllables for the same beat /// * "\[lorem ipsum...\]": hidden text #[derive(Debug,Clone,Default)] pub struct Lyrics { pub track_choice: u8, pub lines: Vec<(u8, u16, String)>, } //impl Default for Lyrics { fn default() -> Self { Lyrics { track_choice: 0, line1: BTreeMap::new(), line2: BTreeMap::new(), line3: BTreeMap::new(), line4: BTreeMap::new(), line5: BTreeMap::new(), }}} impl std::fmt::Display for Lyrics { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let mut s = String::new(); for l in &self.lines { s.push_str(&l.2); s.push('\n'); } write!(f, "{}", s.trim().replace(['\n', '\r'], " ")) } } impl crate::gp::Song { /// Read lyrics. /// /// First, read an `i32` that points to the track lyrics are bound to. Then it is followed by 5 lyric lines. Each one consists of /// number of starting measure encoded in`i32` and`int-size-string` holding text of the lyric line. pub(crate) fn read_lyrics(&self, data: &[u8], seek: &mut usize) -> Lyrics { let mut lyrics = Lyrics{track_choice: read_int(data, seek).to_u8().unwrap(), ..Default::default()}; for i in 0..5u8 { let starting_measure = read_int(data, seek).to_u16().unwrap(); lyrics.lines.push((i, starting_measure, read_int_size_string(data, seek))); } lyrics } pub(crate) fn write_lyrics(&self, data: &mut Vec<u8>) { write_i32(data, self.lyrics.track_choice.to_i32().unwrap()); for i in 0..5 { write_i32(data, self.lyrics.lines[i].1.to_i32().unwrap()); write_int_size_string(data, &self.lyrics.lines[i].2); } } }
#[doc = "Reader of register PCTL"] pub type R = crate::R<u32, super::PCTL>; #[doc = "Writer for register PCTL"] pub type W = crate::W<u32, super::PCTL>; #[doc = "Register PCTL `reset()`'s with value 0"] impl crate::ResetValue for super::PCTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `PMC0`"] pub type PMC0_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC0`"] pub struct PMC0_W<'a> { w: &'a mut W, } impl<'a> PMC0_W<'a> { #[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) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `PMC1`"] pub type PMC1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC1`"] pub struct PMC1_W<'a> { w: &'a mut W, } impl<'a> PMC1_W<'a> { #[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 << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `PMC2`"] pub type PMC2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC2`"] pub struct PMC2_W<'a> { w: &'a mut W, } impl<'a> PMC2_W<'a> { #[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 << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `PMC3`"] pub type PMC3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC3`"] pub struct PMC3_W<'a> { w: &'a mut W, } impl<'a> PMC3_W<'a> { #[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 << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `PMC4`"] pub type PMC4_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC4`"] pub struct PMC4_W<'a> { w: &'a mut W, } impl<'a> PMC4_W<'a> { #[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 << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `PMC5`"] pub type PMC5_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC5`"] pub struct PMC5_W<'a> { w: &'a mut W, } impl<'a> PMC5_W<'a> { #[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 << 20)) | (((value as u32) & 0x0f) << 20); self.w } } #[doc = "Reader of field `PMC6`"] pub type PMC6_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC6`"] pub struct PMC6_W<'a> { w: &'a mut W, } impl<'a> PMC6_W<'a> { #[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 << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `PMC7`"] pub type PMC7_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PMC7`"] pub struct PMC7_W<'a> { w: &'a mut W, } impl<'a> PMC7_W<'a> { #[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 << 28)) | (((value as u32) & 0x0f) << 28); self.w } } impl R { #[doc = "Bits 0:3 - Port Mux Control 0"] #[inline(always)] pub fn pmc0(&self) -> PMC0_R { PMC0_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - Port Mux Control 1"] #[inline(always)] pub fn pmc1(&self) -> PMC1_R { PMC1_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - Port Mux Control 2"] #[inline(always)] pub fn pmc2(&self) -> PMC2_R { PMC2_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - Port Mux Control 3"] #[inline(always)] pub fn pmc3(&self) -> PMC3_R { PMC3_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:19 - Port Mux Control 4"] #[inline(always)] pub fn pmc4(&self) -> PMC4_R { PMC4_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - Port Mux Control 5"] #[inline(always)] pub fn pmc5(&self) -> PMC5_R { PMC5_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - Port Mux Control 6"] #[inline(always)] pub fn pmc6(&self) -> PMC6_R { PMC6_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - Port Mux Control 7"] #[inline(always)] pub fn pmc7(&self) -> PMC7_R { PMC7_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Port Mux Control 0"] #[inline(always)] pub fn pmc0(&mut self) -> PMC0_W { PMC0_W { w: self } } #[doc = "Bits 4:7 - Port Mux Control 1"] #[inline(always)] pub fn pmc1(&mut self) -> PMC1_W { PMC1_W { w: self } } #[doc = "Bits 8:11 - Port Mux Control 2"] #[inline(always)] pub fn pmc2(&mut self) -> PMC2_W { PMC2_W { w: self } } #[doc = "Bits 12:15 - Port Mux Control 3"] #[inline(always)] pub fn pmc3(&mut self) -> PMC3_W { PMC3_W { w: self } } #[doc = "Bits 16:19 - Port Mux Control 4"] #[inline(always)] pub fn pmc4(&mut self) -> PMC4_W { PMC4_W { w: self } } #[doc = "Bits 20:23 - Port Mux Control 5"] #[inline(always)] pub fn pmc5(&mut self) -> PMC5_W { PMC5_W { w: self } } #[doc = "Bits 24:27 - Port Mux Control 6"] #[inline(always)] pub fn pmc6(&mut self) -> PMC6_W { PMC6_W { w: self } } #[doc = "Bits 28:31 - Port Mux Control 7"] #[inline(always)] pub fn pmc7(&mut self) -> PMC7_W { PMC7_W { w: self } } }
/// O(sqrt(N)) /// 与えられた数の素因数分解を行う /// TODO: HashMap<usize, usize>にして素因数の数を数えても良いかも知れない fn bunkai(mut n: usize) -> Vec<usize> { let mut ans = vec![]; let mut pivot = 2; while pivot * pivot <= n { while n / pivot * pivot == n { ans.push(pivot); n /= pivot; } pivot += 1; } if n != 1 { ans.push(n); } ans } fn main() { }
//! Miscellaneous solver state. use crate::solver::SolverError; /// Satisfiability state. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum SatState { Unknown, Sat, Unsat, UnsatUnderAssumptions, } impl Default for SatState { fn default() -> SatState { SatState::Unknown } } /// Miscellaneous solver state. /// /// Anything larger or any larger group of related state variables should be moved into a separate /// part of [`Context`](crate::context::Context). pub struct SolverState { pub sat_state: SatState, pub formula_is_empty: bool, /// Whether solve was called at least once. pub solver_invoked: bool, pub state_is_invalid: bool, pub solver_error: Option<SolverError>, } impl Default for SolverState { fn default() -> SolverState { SolverState { sat_state: SatState::Unknown, formula_is_empty: true, solver_invoked: false, state_is_invalid: false, solver_error: None, } } }
use crate::{match_controller::*, GameState}; use derive_more::Display; use futures::{ prelude::*, stream::{SplitSink, SplitStream}, }; use mahjong::{anyhow::*, messages::*, tile::Wind}; use std::sync::atomic::{AtomicU64, Ordering}; use thespian::{Actor, Remote, StageBuilder}; use tracing::*; use warp::{filters::ws::Message as WsMessage, ws::WebSocket}; /// Actor managing an active session with a client. #[derive(Debug, Actor)] pub struct ClientController { id: ClientId, /// The sender half of the socket connection with the client. sink: SplitSink<WebSocket, WsMessage>, game: <GameState as Actor>::Proxy, state: ClientState, remote: Remote<Self>, } impl ClientController { /// Attempts to perform the session handshake with the client, returning a new /// `ClientConnection` if it succeeds. #[instrument(skip(socket, game))] pub async fn perform_handshake( id: ClientId, socket: WebSocket, mut game: <GameState as Actor>::Proxy, ) -> Result<(<ClientController as Actor>::Proxy, SplitStream<WebSocket>)> { info!("Starting client handshake"); let (mut sink, mut stream) = socket.split(); // HACK: Send an initial text message to the client after establishing a // connection. It looks like there's a bug in WebSocketSharp that means it won't // recognize that the connection has been established unit it receives a message, // causing the client to hang. This won't be necessary once we move off of web // sockets. sink.send(WsMessage::text("ping")) .await .expect("Failed to send initial ping"); trace!("Sent the client the initial ping, awaiting the handshake request"); // Wait for the client to send the handshake. // // TODO: Include a timeout so that we don't wait forever, otherwise this is a vector // for DOS attacks. let request = stream .next() .await .ok_or(anyhow!("Client disconnected during initial handshake"))? .context("Waiting for response to handshake ping")?; // Parse the request data. let request = request .to_str() .map_err(|_| anyhow!("Incoming socket message is not a string: {:?}", request))?; let request: HandshakeRequest = serde_json::from_str(request)?; trace!("Received handshake request from client"); // Verify that the client is compatible with the current server version. For now // we only check that the client version matches the server version, which is // enough for development purposes. Once we're in production we may want a more // permissive strategy that allows us to push server updates without invalidating // existing clients. let server_version = Version::parse(env!("CARGO_PKG_VERSION")).expect("Failed to parse server version"); if server_version != request.client_version { todo!("Handle incompatible client version"); } // Get account information from the server, creating a new account if the client // did not provide credentials for an existing account. let account = match request.credentials { Some(..) => todo!("Support logging into an existing account"), None => game.create_account()?.await, }; info!("Verified handshake request, completing client connection"); // Create the response message and send it to the client. let response = HandshakeResponse { server_version, new_credentials: Some(account.credentials), account_data: account.data, }; let response = serde_json::to_string(&response).expect("Failed to serialize `HandshakeResponse`"); sink.send(WsMessage::text(response)).await?; // Create the actor for the client connection and spawn it. let (builder, remote) = StageBuilder::new(); let stage = builder.finish(ClientController { id, sink, game, state: ClientState::Idle, remote, }); let client = stage.proxy(); tokio::spawn(stage.run()); // TODO: Track the active session in the central game state. Ok((client, stream)) } /// Sends the provided string as a message to the client. async fn send_text(&mut self, text: String) -> Result<()> { self.sink .send(WsMessage::text(text)) .await .context("Failed to send message to client") } } #[thespian::actor] impl ClientController { pub async fn handle_message(&mut self, message: WsMessage) -> Result<()> { let span = trace_span!("handle_message", id = %self.id); let _span = span.enter(); let text = match message.to_str() { Ok(text) => text, Err(_) => bail!("Received non-text message: {:?}", message), }; let request = serde_json::from_str::<ClientRequest>(text)?; info!(?request, "Handling incoming request"); match request { ClientRequest::StartMatch => { // TODO: Do an error if the client is already in a match (or would otherwise not be // able to start a match). trace!("Asking the game controller to start a match..."); let mut controller = self.game.start_match().unwrap().await; // Join the match as the East player. let state = controller .join(self.remote.proxy(), Wind::East) .unwrap() .await .expect("Failed to join the match that we just started???"); trace!("Match started, joined as East player"); let response = serde_json::to_string(&StartMatchResponse { state }) .expect("Failed to serialize `StartMatchResponse`"); self.send_text(response).await?; trace!("Sent initial state to client, transitioning controller to `InMatch`"); self.state = ClientState::InMatch { controller }; } ClientRequest::DiscardTile(request) => { let controller = match &mut self.state { ClientState::InMatch { controller } => controller, _ => bail!("Cannot discard a tile when not in a match"), }; trace!("Forwarding discard request to match controller"); let result = controller .discard_tile(request.player, request.tile) .expect("Match controller died before match ended") .await; match result { Ok(()) => {} Err(err) => todo!("Notify client that discard failed? {}", err), } } } Ok(()) } /// Sends an event to the client independent of the request/response flow. // TODO: Generalize this to work for all kinds of server-sent events once we have // other events to send. pub async fn send_event(&mut self, event: MatchEvent) { trace!(id = %self.id, ?event, "Sending a server event to the client"); assert!( matches!(self.state, ClientState::InMatch { .. }), "Received match event when client wasn't in a match" ); let message = serde_json::to_string(&event).expect("Failed to serialize match event"); self.send_text(message) .await .expect("Disconnected from the client, probably"); } } #[derive(Debug, Clone)] enum ClientState { Idle, InMatch { controller: MatchControllerProxy }, } /// Identifier for a connected client session. /// /// Each connected client session is given an ID when the connection is established. /// IDs are not guaranteed to be unique over the lifetime of the server application /// (IDs may be reused after enough sessions are created), but are guaranteed to be /// unique while the session is active (i.e. no two active sessions will have the /// same ID). // TODO: Actually guarantee that IDs are unique. This will require some kind of // tracking of active sessions IDs to prevent duplicates from being issued. #[derive(Debug, Display, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[display(fmt = "{}", _0)] pub struct ClientId(u64); pub struct ClientIdGenerator(AtomicU64); impl ClientIdGenerator { pub fn new() -> Self { Self(AtomicU64::new(0)) } pub fn next(&self) -> ClientId { ClientId(self.0.fetch_add(1, Ordering::SeqCst)) } }
use dynasm::dynasm; use dynasmrt::{x64::Assembler, DynasmApi}; // Syscalls are in r0, r7, r6, r2, r10, r8, r9, returns in r0, r1 clobbers r11 // See <https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI> A.2.1 // See <https://github.com/apple/darwin-xnu/blob/master/bsd/kern/syscalls.master> // TODO: These intrinsics don't need a closure to be passed. They can have a // more optimized calling convention. pub(crate) fn intrinsic(ops: &mut Assembler, name: &str) { match name { "exit" => sys_exit(ops), "print" => sys_print(ops), "add" => add(ops), "sub" => sub(ops), "mul" => mul(ops), "divmod" => divmod(ops), "isZero" => is_zero(ops), // TODO: "input" => is_zero(ops), "parseInt" => is_zero(ops), _ => panic!("Unknown intrinsic {}", name), } } /// Emit the exit builtin /// `exit code` fn sys_exit(ops: &mut Assembler) { dynasm!(ops // sys_exit(code) ; mov r0d, WORD 0x0200_0001 ; mov r7, r1 ; syscall ); } /// Emit the print builtin /// `print str ret` fn sys_print(ops: &mut Assembler) { dynasm!(ops // Back up ret to r15 ; mov r15, r2 // sys_write(fd, buffer, length) ; mov r0d, WORD 0x0200_0004 ; mov r7d, BYTE 1 ; lea r6, [r1 + 4] ; mov r2d, [r1] ; syscall // call ret from r15 ; mov r0, r15 ; jmp QWORD [r0] ); } /// Emit the add builtin /// `add a b ret` fn add(ops: &mut Assembler) { dynasm!(ops ; add r1, r2 ; mov r0, r3 ; jmp QWORD [r0] ); } /// Emit the add builtin /// `sub a b ret` fn sub(ops: &mut Assembler) { dynasm!(ops ; sub r1, r2 ; mov r0, r3 ; jmp QWORD [r0] ); } /// Emit the mul builtin /// `mul a b ret` fn mul(ops: &mut Assembler) { dynasm!(ops ; mulx r0, r1, r1 // r0:r1 = r1 * r2 ; mov r0, r3 ; jmp QWORD [r0] ); } /// Emit the div builtin /// `divmod a b ret` fn divmod(ops: &mut Assembler) { // TODO: Expose high bits // See <https://www.felixcloutier.com/x86/div> // TODO: Capture #DE event dynasm!(ops ; mov r4, r2 ; mov r0, r1 ; xor r2, r2 ; div r4 // r0 = r2:r0 / r4 // r2 = r2:r0 % r4 ; mov r1, r0 ; mov r0, r3 ; jmp QWORD [r0] ); } /// Emit the isZero builtin /// `isZero n true false` fn is_zero(ops: &mut Assembler) { dynasm!(ops ; test r1, r1 ; mov r0, r2 ; cmovnz r0, r3 ; jmp QWORD [r0] ); }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::HB16CFG2 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = "Possible values of the field `EPI_HB16CFG2_MODE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_MODER { #[doc = "ADMUX - AD\\[15:0\\]"] EPI_HB16CFG2_MODE_ADMUX, #[doc = "ADNONMUX - D\\[15:0\\]"] EPI_HB16CFG2_MODE_AD, #[doc = r"Reserved"] _Reserved(u8), } impl EPI_HB16CFG2_MODER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG2_MODER::EPI_HB16CFG2_MODE_ADMUX => 0, EPI_HB16CFG2_MODER::EPI_HB16CFG2_MODE_AD => 1, EPI_HB16CFG2_MODER::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG2_MODER { match value { 0 => EPI_HB16CFG2_MODER::EPI_HB16CFG2_MODE_ADMUX, 1 => EPI_HB16CFG2_MODER::EPI_HB16CFG2_MODE_AD, i => EPI_HB16CFG2_MODER::_Reserved(i), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_MODE_ADMUX`"] #[inline(always)] pub fn is_epi_hb16cfg2_mode_admux(&self) -> bool { *self == EPI_HB16CFG2_MODER::EPI_HB16CFG2_MODE_ADMUX } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_MODE_AD`"] #[inline(always)] pub fn is_epi_hb16cfg2_mode_ad(&self) -> bool { *self == EPI_HB16CFG2_MODER::EPI_HB16CFG2_MODE_AD } } #[doc = "Values that can be written to the field `EPI_HB16CFG2_MODE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_MODEW { #[doc = "ADMUX - AD\\[15:0\\]"] EPI_HB16CFG2_MODE_ADMUX, #[doc = "ADNONMUX - D\\[15:0\\]"] EPI_HB16CFG2_MODE_AD, } impl EPI_HB16CFG2_MODEW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG2_MODEW::EPI_HB16CFG2_MODE_ADMUX => 0, EPI_HB16CFG2_MODEW::EPI_HB16CFG2_MODE_AD => 1, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_MODEW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_MODEW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG2_MODEW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "ADMUX - AD\\[15:0\\]"] #[inline(always)] pub fn epi_hb16cfg2_mode_admux(self) -> &'a mut W { self.variant(EPI_HB16CFG2_MODEW::EPI_HB16CFG2_MODE_ADMUX) } #[doc = "ADNONMUX - D\\[15:0\\]"] #[inline(always)] pub fn epi_hb16cfg2_mode_ad(self) -> &'a mut W { self.variant(EPI_HB16CFG2_MODEW::EPI_HB16CFG2_MODE_AD) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 0); self.w.bits |= ((value as u32) & 3) << 0; self.w } } #[doc = "Possible values of the field `EPI_HB16CFG2_RDWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_RDWSR { #[doc = "Active RDn is 2 EPI clocks"] EPI_HB16CFG2_RDWS_2, #[doc = "Active RDn is 4 EPI clocks"] EPI_HB16CFG2_RDWS_4, #[doc = "Active RDn is 6 EPI clocks"] EPI_HB16CFG2_RDWS_6, #[doc = "Active RDn is 8 EPI clocks"] EPI_HB16CFG2_RDWS_8, } impl EPI_HB16CFG2_RDWSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_2 => 0, EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_4 => 1, EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_6 => 2, EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_8 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG2_RDWSR { match value { 0 => EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_2, 1 => EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_4, 2 => EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_6, 3 => EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_RDWS_2`"] #[inline(always)] pub fn is_epi_hb16cfg2_rdws_2(&self) -> bool { *self == EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_2 } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_RDWS_4`"] #[inline(always)] pub fn is_epi_hb16cfg2_rdws_4(&self) -> bool { *self == EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_4 } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_RDWS_6`"] #[inline(always)] pub fn is_epi_hb16cfg2_rdws_6(&self) -> bool { *self == EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_6 } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_RDWS_8`"] #[inline(always)] pub fn is_epi_hb16cfg2_rdws_8(&self) -> bool { *self == EPI_HB16CFG2_RDWSR::EPI_HB16CFG2_RDWS_8 } } #[doc = "Values that can be written to the field `EPI_HB16CFG2_RDWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_RDWSW { #[doc = "Active RDn is 2 EPI clocks"] EPI_HB16CFG2_RDWS_2, #[doc = "Active RDn is 4 EPI clocks"] EPI_HB16CFG2_RDWS_4, #[doc = "Active RDn is 6 EPI clocks"] EPI_HB16CFG2_RDWS_6, #[doc = "Active RDn is 8 EPI clocks"] EPI_HB16CFG2_RDWS_8, } impl EPI_HB16CFG2_RDWSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_2 => 0, EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_4 => 1, EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_6 => 2, EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_8 => 3, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_RDWSW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_RDWSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG2_RDWSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Active RDn is 2 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_rdws_2(self) -> &'a mut W { self.variant(EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_2) } #[doc = "Active RDn is 4 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_rdws_4(self) -> &'a mut W { self.variant(EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_4) } #[doc = "Active RDn is 6 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_rdws_6(self) -> &'a mut W { self.variant(EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_6) } #[doc = "Active RDn is 8 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_rdws_8(self) -> &'a mut W { self.variant(EPI_HB16CFG2_RDWSW::EPI_HB16CFG2_RDWS_8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 4); self.w.bits |= ((value as u32) & 3) << 4; self.w } } #[doc = "Possible values of the field `EPI_HB16CFG2_WRWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_WRWSR { #[doc = "Active WRn is 2 EPI clocks"] EPI_HB16CFG2_WRWS_2, #[doc = "Active WRn is 4 EPI clocks"] EPI_HB16CFG2_WRWS_4, #[doc = "Active WRn is 6 EPI clocks"] EPI_HB16CFG2_WRWS_6, #[doc = "Active WRn is 8 EPI clocks"] EPI_HB16CFG2_WRWS_8, } impl EPI_HB16CFG2_WRWSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_2 => 0, EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_4 => 1, EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_6 => 2, EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_8 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG2_WRWSR { match value { 0 => EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_2, 1 => EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_4, 2 => EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_6, 3 => EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_WRWS_2`"] #[inline(always)] pub fn is_epi_hb16cfg2_wrws_2(&self) -> bool { *self == EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_2 } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_WRWS_4`"] #[inline(always)] pub fn is_epi_hb16cfg2_wrws_4(&self) -> bool { *self == EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_4 } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_WRWS_6`"] #[inline(always)] pub fn is_epi_hb16cfg2_wrws_6(&self) -> bool { *self == EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_6 } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_WRWS_8`"] #[inline(always)] pub fn is_epi_hb16cfg2_wrws_8(&self) -> bool { *self == EPI_HB16CFG2_WRWSR::EPI_HB16CFG2_WRWS_8 } } #[doc = "Values that can be written to the field `EPI_HB16CFG2_WRWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_WRWSW { #[doc = "Active WRn is 2 EPI clocks"] EPI_HB16CFG2_WRWS_2, #[doc = "Active WRn is 4 EPI clocks"] EPI_HB16CFG2_WRWS_4, #[doc = "Active WRn is 6 EPI clocks"] EPI_HB16CFG2_WRWS_6, #[doc = "Active WRn is 8 EPI clocks"] EPI_HB16CFG2_WRWS_8, } impl EPI_HB16CFG2_WRWSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_2 => 0, EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_4 => 1, EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_6 => 2, EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_8 => 3, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_WRWSW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_WRWSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG2_WRWSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Active WRn is 2 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_wrws_2(self) -> &'a mut W { self.variant(EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_2) } #[doc = "Active WRn is 4 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_wrws_4(self) -> &'a mut W { self.variant(EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_4) } #[doc = "Active WRn is 6 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_wrws_6(self) -> &'a mut W { self.variant(EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_6) } #[doc = "Active WRn is 8 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg2_wrws_8(self) -> &'a mut W { self.variant(EPI_HB16CFG2_WRWSW::EPI_HB16CFG2_WRWS_8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 6); self.w.bits |= ((value as u32) & 3) << 6; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_BURSTR { bits: bool, } impl EPI_HB16CFG2_BURSTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_BURSTW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_BURSTW<'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 &= !(1 << 16); self.w.bits |= ((value as u32) & 1) << 16; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_RDCRER { bits: bool, } impl EPI_HB16CFG2_RDCRER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_RDCREW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_RDCREW<'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 &= !(1 << 17); self.w.bits |= ((value as u32) & 1) << 17; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_WRCRER { bits: bool, } impl EPI_HB16CFG2_WRCRER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_WRCREW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_WRCREW<'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 &= !(1 << 18); self.w.bits |= ((value as u32) & 1) << 18; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_ALEHIGHR { bits: bool, } impl EPI_HB16CFG2_ALEHIGHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_ALEHIGHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_ALEHIGHW<'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 &= !(1 << 19); self.w.bits |= ((value as u32) & 1) << 19; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_RDHIGHR { bits: bool, } impl EPI_HB16CFG2_RDHIGHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_RDHIGHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_RDHIGHW<'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 &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_WRHIGHR { bits: bool, } impl EPI_HB16CFG2_WRHIGHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_WRHIGHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_WRHIGHW<'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 &= !(1 << 21); self.w.bits |= ((value as u32) & 1) << 21; self.w } } #[doc = "Possible values of the field `EPI_HB16CFG2_CSCFG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_CSCFGR { #[doc = "ALE Configuration"] EPI_HB16CFG2_CSCFG_ALE, #[doc = "CSn Configuration"] EPI_HB16CFG2_CSCFG_CS, #[doc = "Dual CSn Configuration"] EPI_HB16CFG2_CSCFG_DCS, #[doc = "ALE with Dual CSn Configuration"] EPI_HB16CFG2_CSCFG_ADCS, } impl EPI_HB16CFG2_CSCFGR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_ALE => 0, EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_CS => 1, EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_DCS => 2, EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_ADCS => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG2_CSCFGR { match value { 0 => EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_ALE, 1 => EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_CS, 2 => EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_DCS, 3 => EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_ADCS, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_CSCFG_ALE`"] #[inline(always)] pub fn is_epi_hb16cfg2_cscfg_ale(&self) -> bool { *self == EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_ALE } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_CSCFG_CS`"] #[inline(always)] pub fn is_epi_hb16cfg2_cscfg_cs(&self) -> bool { *self == EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_CS } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_CSCFG_DCS`"] #[inline(always)] pub fn is_epi_hb16cfg2_cscfg_dcs(&self) -> bool { *self == EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_DCS } #[doc = "Checks if the value of the field is `EPI_HB16CFG2_CSCFG_ADCS`"] #[inline(always)] pub fn is_epi_hb16cfg2_cscfg_adcs(&self) -> bool { *self == EPI_HB16CFG2_CSCFGR::EPI_HB16CFG2_CSCFG_ADCS } } #[doc = "Values that can be written to the field `EPI_HB16CFG2_CSCFG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG2_CSCFGW { #[doc = "ALE Configuration"] EPI_HB16CFG2_CSCFG_ALE, #[doc = "CSn Configuration"] EPI_HB16CFG2_CSCFG_CS, #[doc = "Dual CSn Configuration"] EPI_HB16CFG2_CSCFG_DCS, #[doc = "ALE with Dual CSn Configuration"] EPI_HB16CFG2_CSCFG_ADCS, } impl EPI_HB16CFG2_CSCFGW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_ALE => 0, EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_CS => 1, EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_DCS => 2, EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_ADCS => 3, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_CSCFGW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_CSCFGW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG2_CSCFGW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "ALE Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfg_ale(self) -> &'a mut W { self.variant(EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_ALE) } #[doc = "CSn Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfg_cs(self) -> &'a mut W { self.variant(EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_CS) } #[doc = "Dual CSn Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfg_dcs(self) -> &'a mut W { self.variant(EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_DCS) } #[doc = "ALE with Dual CSn Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfg_adcs(self) -> &'a mut W { self.variant(EPI_HB16CFG2_CSCFGW::EPI_HB16CFG2_CSCFG_ADCS) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 24); self.w.bits |= ((value as u32) & 3) << 24; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_CSBAUDR { bits: bool, } impl EPI_HB16CFG2_CSBAUDR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_CSBAUDW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_CSBAUDW<'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 &= !(1 << 26); self.w.bits |= ((value as u32) & 1) << 26; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG2_CSCFGEXTR { bits: bool, } impl EPI_HB16CFG2_CSCFGEXTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG2_CSCFGEXTW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG2_CSCFGEXTW<'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 &= !(1 << 27); self.w.bits |= ((value as u32) & 1) << 27; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:1 - CS1n Host Bus Sub-Mode"] #[inline(always)] pub fn epi_hb16cfg2_mode(&self) -> EPI_HB16CFG2_MODER { EPI_HB16CFG2_MODER::_from(((self.bits >> 0) & 3) as u8) } #[doc = "Bits 4:5 - CS1n Read Wait States"] #[inline(always)] pub fn epi_hb16cfg2_rdws(&self) -> EPI_HB16CFG2_RDWSR { EPI_HB16CFG2_RDWSR::_from(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 6:7 - CS1n Write Wait States"] #[inline(always)] pub fn epi_hb16cfg2_wrws(&self) -> EPI_HB16CFG2_WRWSR { EPI_HB16CFG2_WRWSR::_from(((self.bits >> 6) & 3) as u8) } #[doc = "Bit 16 - CS1n Burst Mode"] #[inline(always)] pub fn epi_hb16cfg2_burst(&self) -> EPI_HB16CFG2_BURSTR { let bits = ((self.bits >> 16) & 1) != 0; EPI_HB16CFG2_BURSTR { bits } } #[doc = "Bit 17 - CS1n PSRAM Configuration Register Read"] #[inline(always)] pub fn epi_hb16cfg2_rdcre(&self) -> EPI_HB16CFG2_RDCRER { let bits = ((self.bits >> 17) & 1) != 0; EPI_HB16CFG2_RDCRER { bits } } #[doc = "Bit 18 - CS1n PSRAM Configuration Register Write"] #[inline(always)] pub fn epi_hb16cfg2_wrcre(&self) -> EPI_HB16CFG2_WRCRER { let bits = ((self.bits >> 18) & 1) != 0; EPI_HB16CFG2_WRCRER { bits } } #[doc = "Bit 19 - CS1n ALE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg2_alehigh(&self) -> EPI_HB16CFG2_ALEHIGHR { let bits = ((self.bits >> 19) & 1) != 0; EPI_HB16CFG2_ALEHIGHR { bits } } #[doc = "Bit 20 - CS1n READ Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg2_rdhigh(&self) -> EPI_HB16CFG2_RDHIGHR { let bits = ((self.bits >> 20) & 1) != 0; EPI_HB16CFG2_RDHIGHR { bits } } #[doc = "Bit 21 - CS1n WRITE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg2_wrhigh(&self) -> EPI_HB16CFG2_WRHIGHR { let bits = ((self.bits >> 21) & 1) != 0; EPI_HB16CFG2_WRHIGHR { bits } } #[doc = "Bits 24:25 - Chip Select Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfg(&self) -> EPI_HB16CFG2_CSCFGR { EPI_HB16CFG2_CSCFGR::_from(((self.bits >> 24) & 3) as u8) } #[doc = "Bit 26 - Chip Select Baud Rate and Multiple Sub-Mode Configuration enable"] #[inline(always)] pub fn epi_hb16cfg2_csbaud(&self) -> EPI_HB16CFG2_CSBAUDR { let bits = ((self.bits >> 26) & 1) != 0; EPI_HB16CFG2_CSBAUDR { bits } } #[doc = "Bit 27 - Chip Select Extended Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfgext(&self) -> EPI_HB16CFG2_CSCFGEXTR { let bits = ((self.bits >> 27) & 1) != 0; EPI_HB16CFG2_CSCFGEXTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - CS1n Host Bus Sub-Mode"] #[inline(always)] pub fn epi_hb16cfg2_mode(&mut self) -> _EPI_HB16CFG2_MODEW { _EPI_HB16CFG2_MODEW { w: self } } #[doc = "Bits 4:5 - CS1n Read Wait States"] #[inline(always)] pub fn epi_hb16cfg2_rdws(&mut self) -> _EPI_HB16CFG2_RDWSW { _EPI_HB16CFG2_RDWSW { w: self } } #[doc = "Bits 6:7 - CS1n Write Wait States"] #[inline(always)] pub fn epi_hb16cfg2_wrws(&mut self) -> _EPI_HB16CFG2_WRWSW { _EPI_HB16CFG2_WRWSW { w: self } } #[doc = "Bit 16 - CS1n Burst Mode"] #[inline(always)] pub fn epi_hb16cfg2_burst(&mut self) -> _EPI_HB16CFG2_BURSTW { _EPI_HB16CFG2_BURSTW { w: self } } #[doc = "Bit 17 - CS1n PSRAM Configuration Register Read"] #[inline(always)] pub fn epi_hb16cfg2_rdcre(&mut self) -> _EPI_HB16CFG2_RDCREW { _EPI_HB16CFG2_RDCREW { w: self } } #[doc = "Bit 18 - CS1n PSRAM Configuration Register Write"] #[inline(always)] pub fn epi_hb16cfg2_wrcre(&mut self) -> _EPI_HB16CFG2_WRCREW { _EPI_HB16CFG2_WRCREW { w: self } } #[doc = "Bit 19 - CS1n ALE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg2_alehigh(&mut self) -> _EPI_HB16CFG2_ALEHIGHW { _EPI_HB16CFG2_ALEHIGHW { w: self } } #[doc = "Bit 20 - CS1n READ Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg2_rdhigh(&mut self) -> _EPI_HB16CFG2_RDHIGHW { _EPI_HB16CFG2_RDHIGHW { w: self } } #[doc = "Bit 21 - CS1n WRITE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg2_wrhigh(&mut self) -> _EPI_HB16CFG2_WRHIGHW { _EPI_HB16CFG2_WRHIGHW { w: self } } #[doc = "Bits 24:25 - Chip Select Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfg(&mut self) -> _EPI_HB16CFG2_CSCFGW { _EPI_HB16CFG2_CSCFGW { w: self } } #[doc = "Bit 26 - Chip Select Baud Rate and Multiple Sub-Mode Configuration enable"] #[inline(always)] pub fn epi_hb16cfg2_csbaud(&mut self) -> _EPI_HB16CFG2_CSBAUDW { _EPI_HB16CFG2_CSBAUDW { w: self } } #[doc = "Bit 27 - Chip Select Extended Configuration"] #[inline(always)] pub fn epi_hb16cfg2_cscfgext(&mut self) -> _EPI_HB16CFG2_CSCFGEXTW { _EPI_HB16CFG2_CSCFGEXTW { w: self } } }
// xfail-stage0 // -*- rust -*- use std; import std._str; import std._vec; fn test_simple() { let str s1 = "All mimsy were the borogoves"; /* * FIXME from_bytes(vec[u8] v) has constraint is_utf(v), which is * unimplemented and thereby just fails. This doesn't stop us from * using from_bytes for now since the constraint system isn't fully * working, but we should implement is_utf8 before that happens. */ let vec[u8] v = _str.bytes(s1); let str s2 = _str.from_bytes(v); let uint i = 0u; let uint n1 = _str.byte_len(s1); let uint n2 = _vec.len[u8](v); check (n1 == n2); while (i < n1) { let u8 a = s1.(i); let u8 b = s2.(i); log a; log b; check (a == b); i += 1u; } log "refcnt is"; log _str.refcount(s1); } fn main() { test_simple(); }
use std::collections::HashMap; //hashmap相对之前的vector和string来说用的较少,因此没有包括在自动引入的特点中 //所以使用时需要使用use引入. //同时也没有内置的宏支持 //hashmap的所有key必须是同一类型,value也必须是同一类型 pub fn map() { //根据new关联方法构造 let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); //使用vector[元组]来构建map let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); //hash map 与 Ownership //对于实现了Copy特征的类型像i32,这些值会被拷贝进hash map //对于owned values,会被move进hashmap并且hashmap会拥有这些值的所有权 let k = 2; let v = 3; let mut h = HashMap::new(); h.insert(k, v); println!("k={},v={}", k, v); //因为i32是copy,所以这里仍然能继续使用 let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); //这里field_name和field_value所有权移到map中了,后面就不能继续使用了 //println!("fieldname={},fieldvalue={}", field_name, field_value); //field_name and field_value are invalid at this point //如果我们通过引用往hashmap中存值,那么所有权不会转移到map中。 //但是必须保证这些引用指向的值在map的生命周期里是有效的 //从map中获取值 let score = scores.get(&String::from("Blue")); //返回Option<&V>类型。使用模式匹配来取值: match score { Some(v) => println!("Blue score = {}", v), None => println!("Blue key not exist!"), } //map迭代 for (key, value) in &scores { println!("{}: {}", key, value); } //重复插入相同的key会覆盖旧的值 let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 30); scores.insert(String::from("Blue"), 10); println!("{:?}", scores); //如果key不存在则插入,否则忽略 //or_insert会返回新值的可变引用 scores.entry(String::from("Yellow")).or_insert(50); scores.entry(String::from("Blue")).or_insert(20); println!("{:?}", scores); //根据旧值更新新值 let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); //这里会返回value的可变引用 *count += 1; //解引用后自增 } println!("{:?}", map); }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::CHMAP1 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH8SELR { bits: u8, } impl UDMA_CHMAP1_CH8SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH8SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH8SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 0); self.w.bits |= ((value as u32) & 15) << 0; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH9SELR { bits: u8, } impl UDMA_CHMAP1_CH9SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH9SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH9SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 4); self.w.bits |= ((value as u32) & 15) << 4; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH10SELR { bits: u8, } impl UDMA_CHMAP1_CH10SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH10SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH10SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 8); self.w.bits |= ((value as u32) & 15) << 8; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH11SELR { bits: u8, } impl UDMA_CHMAP1_CH11SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH11SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH11SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 12); self.w.bits |= ((value as u32) & 15) << 12; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH12SELR { bits: u8, } impl UDMA_CHMAP1_CH12SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH12SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH12SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 16); self.w.bits |= ((value as u32) & 15) << 16; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH13SELR { bits: u8, } impl UDMA_CHMAP1_CH13SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH13SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH13SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 20); self.w.bits |= ((value as u32) & 15) << 20; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH14SELR { bits: u8, } impl UDMA_CHMAP1_CH14SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH14SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH14SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 24); self.w.bits |= ((value as u32) & 15) << 24; self.w } } #[doc = r"Value of the field"] pub struct UDMA_CHMAP1_CH15SELR { bits: u8, } impl UDMA_CHMAP1_CH15SELR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _UDMA_CHMAP1_CH15SELW<'a> { w: &'a mut W, } impl<'a> _UDMA_CHMAP1_CH15SELW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 28); self.w.bits |= ((value as u32) & 15) << 28; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:3 - uDMA Channel 8 Source Select"] #[inline(always)] pub fn udma_chmap1_ch8sel(&self) -> UDMA_CHMAP1_CH8SELR { let bits = ((self.bits >> 0) & 15) as u8; UDMA_CHMAP1_CH8SELR { bits } } #[doc = "Bits 4:7 - uDMA Channel 9 Source Select"] #[inline(always)] pub fn udma_chmap1_ch9sel(&self) -> UDMA_CHMAP1_CH9SELR { let bits = ((self.bits >> 4) & 15) as u8; UDMA_CHMAP1_CH9SELR { bits } } #[doc = "Bits 8:11 - uDMA Channel 10 Source Select"] #[inline(always)] pub fn udma_chmap1_ch10sel(&self) -> UDMA_CHMAP1_CH10SELR { let bits = ((self.bits >> 8) & 15) as u8; UDMA_CHMAP1_CH10SELR { bits } } #[doc = "Bits 12:15 - uDMA Channel 11 Source Select"] #[inline(always)] pub fn udma_chmap1_ch11sel(&self) -> UDMA_CHMAP1_CH11SELR { let bits = ((self.bits >> 12) & 15) as u8; UDMA_CHMAP1_CH11SELR { bits } } #[doc = "Bits 16:19 - uDMA Channel 12 Source Select"] #[inline(always)] pub fn udma_chmap1_ch12sel(&self) -> UDMA_CHMAP1_CH12SELR { let bits = ((self.bits >> 16) & 15) as u8; UDMA_CHMAP1_CH12SELR { bits } } #[doc = "Bits 20:23 - uDMA Channel 13 Source Select"] #[inline(always)] pub fn udma_chmap1_ch13sel(&self) -> UDMA_CHMAP1_CH13SELR { let bits = ((self.bits >> 20) & 15) as u8; UDMA_CHMAP1_CH13SELR { bits } } #[doc = "Bits 24:27 - uDMA Channel 14 Source Select"] #[inline(always)] pub fn udma_chmap1_ch14sel(&self) -> UDMA_CHMAP1_CH14SELR { let bits = ((self.bits >> 24) & 15) as u8; UDMA_CHMAP1_CH14SELR { bits } } #[doc = "Bits 28:31 - uDMA Channel 15 Source Select"] #[inline(always)] pub fn udma_chmap1_ch15sel(&self) -> UDMA_CHMAP1_CH15SELR { let bits = ((self.bits >> 28) & 15) as u8; UDMA_CHMAP1_CH15SELR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:3 - uDMA Channel 8 Source Select"] #[inline(always)] pub fn udma_chmap1_ch8sel(&mut self) -> _UDMA_CHMAP1_CH8SELW { _UDMA_CHMAP1_CH8SELW { w: self } } #[doc = "Bits 4:7 - uDMA Channel 9 Source Select"] #[inline(always)] pub fn udma_chmap1_ch9sel(&mut self) -> _UDMA_CHMAP1_CH9SELW { _UDMA_CHMAP1_CH9SELW { w: self } } #[doc = "Bits 8:11 - uDMA Channel 10 Source Select"] #[inline(always)] pub fn udma_chmap1_ch10sel(&mut self) -> _UDMA_CHMAP1_CH10SELW { _UDMA_CHMAP1_CH10SELW { w: self } } #[doc = "Bits 12:15 - uDMA Channel 11 Source Select"] #[inline(always)] pub fn udma_chmap1_ch11sel(&mut self) -> _UDMA_CHMAP1_CH11SELW { _UDMA_CHMAP1_CH11SELW { w: self } } #[doc = "Bits 16:19 - uDMA Channel 12 Source Select"] #[inline(always)] pub fn udma_chmap1_ch12sel(&mut self) -> _UDMA_CHMAP1_CH12SELW { _UDMA_CHMAP1_CH12SELW { w: self } } #[doc = "Bits 20:23 - uDMA Channel 13 Source Select"] #[inline(always)] pub fn udma_chmap1_ch13sel(&mut self) -> _UDMA_CHMAP1_CH13SELW { _UDMA_CHMAP1_CH13SELW { w: self } } #[doc = "Bits 24:27 - uDMA Channel 14 Source Select"] #[inline(always)] pub fn udma_chmap1_ch14sel(&mut self) -> _UDMA_CHMAP1_CH14SELW { _UDMA_CHMAP1_CH14SELW { w: self } } #[doc = "Bits 28:31 - uDMA Channel 15 Source Select"] #[inline(always)] pub fn udma_chmap1_ch15sel(&mut self) -> _UDMA_CHMAP1_CH15SELW { _UDMA_CHMAP1_CH15SELW { w: self } } }
use std::{ ffi::{c_void, CString}, os::raw::c_char, ptr, }; const PAGE_EXECUTE_READWRITE: u32 = 0x40; #[link(name = "kernel32")] extern "stdcall" { fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *const c_void; fn VirtualProtect(addr: *mut c_void, len: usize, new_prot: u32, old_prot: *mut u32) -> u32; } unsafe fn virtual_protect(addr: *const c_void, len: usize, prot: u32) -> u32 { let mut old_prot: u32 = 0; if VirtualProtect(addr as *mut c_void, len, prot, &mut old_prot) == 0 { panic!("VirtualProtect failed!"); } old_prot } unsafe fn with_writable<F>(addr: *const c_void, len: usize, f: F) where F: Fn(), { let old_prot = virtual_protect(addr, len, PAGE_EXECUTE_READWRITE); f(); virtual_protect(addr, len, old_prot); } pub unsafe fn get_proc_address(name: &str) -> *const c_void { let name = name.split("::").last().unwrap(); let name = CString::new(name).unwrap(); let real = GetProcAddress(ptr::null_mut(), name.as_ptr()); if real.is_null() { panic!("while hooking: could not find function {:?}", name); } real } pub unsafe fn hook(name: &str, thunk: *const c_void) { let real = get_proc_address(name); #[cfg(debug)] println!( "thunk = {:?}, real = {:?}", thunk as *const (), real as *const () ); const FILL: u8 = 0xF1; let offset: usize; #[cfg(target_arch = "x86")] let mut template: [u8; 7] = { offset = 1; [0xb8, FILL, FILL, FILL, FILL, 0xff, 0xe0] }; #[cfg(target_arch = "x86_64")] let mut template: [u8; 12] = { offset = 2; [ 0x48, 0xb8, FILL, FILL, FILL, FILL, FILL, FILL, FILL, FILL, 0xff, 0xe0, ] }; let dest = (real as usize).to_le_bytes(); ptr::copy_nonoverlapping(dest.as_ptr(), &mut template[offset], dest.len()); #[cfg(debug)] { print!("full template ({} bytes):", template.len()); for b in &template { print!(" {:02x}", b); } println!(); } with_writable(thunk, template.len(), || { ptr::copy_nonoverlapping(template.as_ptr(), thunk as *mut u8, template.len()); }); }
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. use block_format::Block; use cid::Cid; use crate::error::Result; use crate::merkledag::NodeGetter; /// Node must support deep copy /// Node is the base interface all IPLD nodes must implement. /// /// Nodes are **Immutable** and all methods defined on the interface are **Thread Safe**. pub trait Node: Block { /// A helper function that calls resolve and asserts the output is a link. fn resolve_link(&self, path: &[&str]) -> Result<(Link, Vec<String>)>; /// A helper function that returns all links within this object. fn links(&self) -> Vec<&Link>; /// A helper function that returns `NodeStat` ref. fn stat(&self) -> Result<&NodeStat>; /// Returns the size in bytes of the serialized object. fn size(&self) -> u64; } /// Resolver is the interface that operate path. pub trait Resolver { /// The found object by resolving a path through this node. type Output; /// Resolves a path through this node, stopping at any link boundary /// and returning the object found as well as the remaining path to traverse. fn resolve(&self, path: &[&str]) -> Result<(Self::Output, Vec<String>)>; /// Lists all paths within the object under 'path', and up to the given depth. /// To list the entire object (similar to `find .`) pass "" and None. fn tree(&self, path: &str, depth: Option<usize>) -> Vec<String>; } /// Link represents an IPFS Merkle DAG Link between Nodes. #[derive(PartialEq, Eq, Clone, Debug)] pub struct Link { /// It should be unique per object. pub name: String, /// The cumulative size of target object. pub size: u64, /// The CID of the target object. pub cid: Cid, } impl Link { /// Create a new `Link` with the given CID. pub fn new_with_cid(cid: Cid) -> Link { Link { name: "".to_string(), size: 0, cid, } } /// Creates a `Link` with the given node. pub fn new_with_node<T: Node>(node: T) -> Link { Link { name: Default::default(), size: node.size(), cid: node.cid().clone(), } } /// Returns the MerkleDAG Node that this link points to. pub fn node<T: Node>(&self, ng: &impl NodeGetter<T>) -> Result<impl Node> { Ok(ng.get(&self.cid)) } } /// NodeStat is a statistics object for a Node. Mostly sizes. pub struct NodeStat { /// The multihash of node. pub hash: multihash::Multihash, /// The number of links in link table. pub num_links: usize, /// The size of the raw, encoded data. pub block_size: usize, /// The size of the links segment. pub links_size: usize, /// The size of the data segment. pub data_size: usize, /// The cumulative size of object and its references. pub cumulative_size: usize, } impl std::fmt::Debug for NodeStat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("NodeStat") .field("NumLinks", &self.num_links) .field("BlockSize", &self.block_size) .field("LinksSize", &self.links_size) .field("DataSize", &self.data_size) .field("CumulativeSize", &self.cumulative_size) .finish() } }
#[macro_use] extern crate log; mod lint; pub use self::lint::{ default_filter, AllRulesValidator, Filter, NodeIterator, Rule, RuleCode, SourceCode, ValidationError, Validator, RULES, };
// SPDX-License-Identifier: Apache-2.0 use super::{Command, Error}; use ciborium::de::from_reader; use koine::Contract; use reqwest::header::CONTENT_TYPE; use structopt::StructOpt; use uuid::Uuid; #[derive(StructOpt)] pub struct List { /// The server base URL #[structopt(short, long, env = "ENARX_SERVER")] url: reqwest::Url, } #[async_trait::async_trait] impl Command for List { async fn run(self) -> Result<(), Error> { let url = self.url.join("contracts")?; let response = reqwest::get(url).await?; let response = response.error_for_status()?; let response = Error::check_header(response, CONTENT_TYPE, "application/cbor")?; let contracts: Vec<Contract> = response.decode(|bytes| from_reader(bytes)).await?; for contract in contracts { println!("{} ({})", contract.uuid, contract.backend.as_str()); } Ok(()) } } #[derive(StructOpt)] pub struct Show { /// The server base URL #[structopt(short, long, env = "ENARX_SERVER")] url: reqwest::Url, /// The contract UUID uuid: Uuid, } #[async_trait::async_trait] impl Command for Show { async fn run(self) -> Result<(), Error> { let uuid = self.uuid.to_hyphenated().to_string(); let url = self.url.join("contracts/")?.join(&uuid)?; let response = reqwest::get(url).await?; let response = response.error_for_status()?; let response = Error::check_header(response, CONTENT_TYPE, "application/cbor")?; let contract: Contract = response.decode(|bytes| from_reader(bytes)).await?; println!("{:#?}", contract); Ok(()) } } #[derive(StructOpt)] pub enum Contracts { List(List), Show(Show), } #[async_trait::async_trait] impl Command for Contracts { async fn run(self) -> Result<(), Error> { match self { Self::List(cmd) => cmd.run().await, Self::Show(cmd) => cmd.run().await, } } }
use self::generated_types::{schema_service_client::SchemaServiceClient, *}; use ::generated_types::google::OptionalField; use client_util::connection::GrpcConnection; use crate::connection::Connection; use crate::error::Error; /// Re-export generated_types pub mod generated_types { pub use generated_types::influxdata::iox::schema::v1::*; } /// A basic client for fetching the Schema for a Namespace. #[derive(Debug, Clone)] pub struct Client { inner: SchemaServiceClient<GrpcConnection>, } impl Client { /// Creates a new client with the provided connection pub fn new(connection: Connection) -> Self { Self { inner: SchemaServiceClient::new(connection.into_grpc_connection()), } } /// Get the schema for a namespace. pub async fn get_schema(&mut self, namespace: &str) -> Result<NamespaceSchema, Error> { let response = self .inner .get_schema(GetSchemaRequest { namespace: namespace.to_string(), }) .await?; Ok(response.into_inner().schema.unwrap_field("schema")?) } }
use assert_fs::prelude::*; use predicates::str::ends_with; mod retry_test; use retry_test::*; #[test] fn test_default() -> TestResult { RetryCommand::new()? .command(&["echo", "-n", "test"]) .assert() .success() .stdout(ends_with("test")); Ok(()) } #[test] fn test_retry_on_success() -> TestResult { RetryCommand::new()? .arg("--retry-on-success") .command(&["/bin/sh", "-c", "test \"$RETRY_TRY\" = \"1\""]) .assert() .success(); Ok(()) } #[test] fn test_max_tries() -> TestResult { let temp = assert_fs::TempDir::new()?; RetryCommand::new()? .arg("--max-tries=3") .arg("--sleep=1") .with_mock_cmd(|mock| mock.state_dir(temp.path()).exit_code(1)) .assert() .failure() .stdout(ends_with("3\n")); temp.child("run_count").assert("3"); Ok(()) } #[test] fn test_env_defaults() -> TestResult { let temp = assert_fs::TempDir::new()?; RetryCommand::new()? .with_mock_cmd(|mock| mock.state_dir(temp.path())) .assert() .success(); temp.child("RETRY_TRY").assert("1"); temp.child("RETRY_MAX").assert("10"); temp.child("RETRY_PREV_SLEEP").assert("None"); temp.child("RETRY_NEXT_SLEEP").assert("5"); temp.child("RETRY_PREV_EXIT_CODE").assert("None"); Ok(()) } #[test] fn test_backoff() -> TestResult { let temp = assert_fs::TempDir::new()?; RetryCommand::new()? .arg("--backoff") .arg("--max-tries=3") .with_mock_cmd(|mock| mock.state_dir(temp.path()).exit_code(1)) .assert() .failure(); temp.child("RETRY_TRY").assert("3"); temp.child("RETRY_MAX").assert("3"); temp.child("RETRY_PREV_SLEEP").assert("4"); temp.child("RETRY_NEXT_SLEEP").assert("8"); Ok(()) } #[test] fn test_max_backoff() -> TestResult { let temp = assert_fs::TempDir::new()?; RetryCommand::new()? .arg("--backoff") .arg("--max-tries=2") .arg("--max-backoff=3") .with_mock_cmd(|mock| mock.state_dir(temp.path()).exit_code(1)) .assert() .failure(); temp.child("RETRY_TRY").assert("2"); temp.child("RETRY_MAX").assert("2"); temp.child("RETRY_PREV_SLEEP").assert("2"); temp.child("RETRY_NEXT_SLEEP").assert("3"); Ok(()) } #[test] fn test_quiet() -> TestResult { RetryCommand::new()? .arg("--quiet") .command(&["echo", "-n", "shhh"]) .assert() .success() .stdout("shhh"); Ok(()) }
#![crate_type = "staticlib"] #![no_std] #![feature(core,core_intrinsics, lang_items, compiler_builtins_lib)] #[macro_use] extern crate fixedvec; extern crate rlibc; extern crate compiler_builtins; pub mod hal; use core::intrinsics::abort; use core::str::from_utf8; use fixedvec::FixedVec; enum CharType { Control, Printable } const BUFFERLEN: usize = 0x00000400; fn get_char_type(ch: u8) -> CharType { if ch < 0x20 { // Consider TAB, RET etc control characters CharType::Control } else { if ch < 0x7F { CharType::Printable } else { CharType::Control } } } fn repl(hw: &hal::Hardware, buffer: &fixedvec::FixedVec<u8>) { match from_utf8(buffer.as_slice()) { Ok(val) => { if val == "xyzzy" { hw.send_string("Nothing happens.") } else { hw.send_string(val) } }, Err(_doh) => hw.send_string("PANIC: Decode Error!") } } #[no_mangle] pub extern fn notmain() { let hw = hal::get_hw(); hw.uart_init(); let pc: u32 = hw.get_pc(); hw.hexstring(pc); let id: u32 = hw.get_id(); hw.hexstring(id); hw.send_hwstr(); hw.uart_send(0x3E); hw.uart_send(0x20); let mut input_memory = alloc_stack!([u8; BUFFERLEN]); let mut input_buffer = FixedVec::new(&mut input_memory); let mut c: u32; loop { c = hw.uart_recv(); match get_char_type(c as u8) { CharType::Control => { match c { 0x0000000D => { // Do some stuff hw.uart_send(0x0A); hw.uart_send(0x0D); repl(&hw,&input_buffer); input_buffer.clear(); hw.uart_send(0x0A); hw.uart_send(0x0D); hw.uart_send(0x3E); hw.uart_send(0x20); }, 0x0000007F => { // backspace if input_buffer.len() > 0 { input_buffer.pop(); hw.uart_send(0x00000008); } } _ => { hw.send_string("\r\n\nControl: 0x"); hw.hexstring(c); } } } CharType::Printable => { if input_buffer.len() < BUFFERLEN { // Ignore typing past the length of the buffer hw.uart_send(c); match input_buffer.push(c as u8) { Ok(_val) => (), Err(_doh) => () } } } } } } #[lang = "panic_fmt"] #[no_mangle] pub fn panic_fmt() -> ! { unsafe { abort() } }
/* * hurl (https://hurl.dev) * Copyright (C) 2020 Orange * * 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 crate::core::ast::Expr; use crate::core::common::Value; use super::core::{RunnerError, Error}; impl Expr { pub fn eval(self, variables: &HashMap<String, Value>) -> Result<Value, Error> { if let Some(value) = variables.get(self.variable.name.as_str()) { Ok(value.clone()) } else { Err(Error { source_info: self.variable.source_info, inner: RunnerError::TemplateVariableNotDefined { name: self.variable.name }, assert: false }) } } }
#![allow(unused_variables)] extern crate actix; extern crate actix_web; extern crate env_logger; extern crate futures; extern crate regex; extern crate serde_json; extern crate maxminddb; #[macro_use] extern crate tera; use std::env; use std::net::IpAddr; use std::str::FromStr; use std::collections::{HashMap, BTreeMap}; use regex::Regex; use maxminddb::geoip2::Country; use actix_web::http::{Method}; use actix_web::{ fs, error, middleware, server, App, Error, Query, State, HttpRequest, HttpResponse, Result }; struct AppState { template: tera::Tera, } fn is_cli(req: &HttpRequest<AppState>) -> bool { let user_agent = format!("{:?}", req.headers().get("user-agent").unwrap()); let re = Regex::new(r"(curl|wget|Wget|fetch slibfetch)/.*$").unwrap(); return re.is_match(&user_agent) } fn lookup_ip(req: &HttpRequest<AppState>) -> String { return format!("{}", req.connection_info() .remote() .unwrap() .splitn(2, ":") .next() .unwrap() ) } fn lookup_cmd(cmd: &str) -> &str { let s = match cmd { "curl" => "curl", "wget" => "wget -qO -", "fetch" => "fetch -qo -", _ => "" }; return s } fn lookup_country(ip_address: &String) -> Option<BTreeMap<String, String>> { // Lookup Country from user's public ip address. The GeoLite2-Country.mmdb // can be downloaded from https://dev.maxmind.com/geoip/geoip2/geolite2 let reader = maxminddb::Reader::open("GeoLite2-Country.mmdb").unwrap(); let ip: IpAddr = FromStr::from_str(ip_address).unwrap(); match reader.lookup(ip) { Ok(db) => { let db : Country = db; return db.country.and_then(|n| n.names) } Err(error) => { println!("Error during looking up ip {:?} the DB: {:?}", ip_address, error); let mut default_country = BTreeMap::new(); default_country.insert(String::from("en"), String::from("Unknown")); return Some(default_country) } }; } fn render_template(state: State<AppState>, template: &str) -> Result<HttpResponse, Error> { let s = state .template .render(template, &tera::Context::new()) .map_err(|_| error::ErrorInternalServerError("Template error"))?; Ok(HttpResponse::Ok().content_type("text/html").body(s)) } fn favicon(state: State<AppState>) -> Result<fs::NamedFile> { Ok(fs::NamedFile::open("static/favicon.ico")?) } fn p404(state: State<AppState>) -> Result<HttpResponse, Error> { render_template(state, "404.html") } fn index(req: HttpRequest<AppState>, query: Query<HashMap<String, String>>) -> Result<HttpResponse, Error> { let ip_address = lookup_ip(&req); // If user browses the index page by using command line, // return the public ip address instead of whole html page. if is_cli(&req) { return Ok(HttpResponse::Ok().content_type("text/plain").body(ip_address + "\n")) } let default_cmd = String::from("curl"); let cmd = query.get("cmd").unwrap_or(&default_cmd); let country = lookup_country(&ip_address); let country_name = match &country { None => "Unknown", Some (n) => n.get("en").unwrap() }; // Create a HashMap from request's header // for later using with json. let mut headers = HashMap::new(); for (key, value) in req.headers().iter() { let k = format!("{:}", key); let mut v = format!("{:?}", value); v = v.replace('"', ""); headers.insert(k, v); } // Remove Host header headers.remove("host"); // Add country and ip address into above HashMap headers.insert(String::from("country"), format!("{:}", country_name)); headers.insert(String::from("ip-address"), format!("{:}", ip_address)); // Create a Context for template variable rendering let mut context = tera::Context::new(); context.insert("cmd", &cmd); context.insert("cmd_with_options", lookup_cmd(&cmd)); context.insert("ip_address", &ip_address); context.insert("headers", &headers); context.insert("country", country_name); let rendered = req.state() .template .render("index.html", &context).map_err(|e| { error::ErrorInternalServerError(e.description().to_owned()) })?; Ok(HttpResponse::Ok().content_type("text/html").body(rendered)) } fn custom_query(req: HttpRequest<AppState>, state: State<AppState>, query: Query<HashMap<String, String>>) -> Result<HttpResponse, Error> { let param = req.match_info().get("param").unwrap(); match param { "country" => { let ip_address = lookup_ip(&req); let country = lookup_country(&ip_address); match country { Some (n) => return Ok(HttpResponse::Ok() .content_type("text/plain") .body(n.get("en").unwrap()) ), _ => return Ok(HttpResponse::Ok() .content_type("text/plain") .body("Unknown")) } } "all.json" => { let mut headers = HashMap::new(); for (key, value) in req.headers().iter() { let k = format!("{:}", key); let mut v = format!("{:?}", value); v = v.replace('"', ""); headers.insert(k, v); } let ip_address = lookup_ip(&req); let country = lookup_country(&ip_address); let country_name = match &country { None => "Unknown", Some (n) => n.get("en").unwrap() }; headers.remove("host"); headers.insert(String::from("country"), format!("{:}", country_name)); headers.insert(String::from("ip-address"), format!("{:}", ip_address)); let result = serde_json::to_string_pretty(&headers).unwrap(); return Ok(HttpResponse::Ok().content_type("application/json").body(result)) } _ => { if req.headers().contains_key(param) { let output = format!("{:?}", req.headers().get(param).unwrap()); return Ok(HttpResponse::Ok().content_type("text/plain").body(output)) } else { if is_cli(&req) { return Ok(HttpResponse::Ok().content_type("text/html").body("")) } render_template(state, "404.html") } } } } fn main() { env::set_var("RUST_LOG", "actix_web=debug"); env::set_var("RUST_BACKTRACE", "1"); env_logger::init(); let sys = actix::System::new("ifconfig.top"); let addr = server::new(|| { let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")); App::with_state(AppState{template: tera}) // enable logger .middleware(middleware::Logger::default()) // register favicon .resource("/favicon.ico", |r| r.method(Method::GET).with(favicon)) // register home page .resource("/", |r| r.method(Method::GET).with(index)) // register custom queries .resource("/{param}", |r| r.method(Method::GET).with(custom_query)) // default page .default_resource(|r| r.method(Method::GET).with(p404)) }) .bind("0.0.0.0:9292").expect("Can not bind to 0.0.0.0:9292") .shutdown_timeout(0) .start(); println!("Starting web server: 0.0.0.0:9292"); let _ = sys.run(); }
// 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 { bt_avctp::Error as AvctpError, failure::{Error, Fail}, futures::{sink::Sink, stream::FusedStream, task::Context, Poll, Stream}, pin_utils::unsafe_pinned, std::pin::Pin, }; use crate::packets::Error as PacketError; // TODO(BT-2197): change to the BT shared peer id type when the BrEdr protocol changes over. pub type PeerId = String; /// The error types for peer management. #[derive(Fail, Debug)] pub enum PeerError { /// Error encoding/decoding packet #[fail(display = "Packet encoding/decoding error: {:?}", _0)] PacketError(PacketError), /// Error in protocol layer #[fail(display = "Protocol layer error: {:?}", _0)] #[allow(dead_code)] AvctpError(AvctpError), #[fail(display = "Remote device was not connected")] RemoteNotFound, #[fail(display = "Remote command is unsupported")] CommandNotSupported, #[fail(display = "Remote command rejected")] CommandFailed, #[fail(display = "Unable to connect")] ConnectionFailure(#[cause] Error), #[fail(display = "Unexpected response to command")] UnexpectedResponse, #[fail(display = "Generic errors")] GenericError(#[cause] Error), #[doc(hidden)] #[fail(display = "__Nonexhaustive error should never be created.")] __Nonexhaustive, } impl From<AvctpError> for PeerError { fn from(error: AvctpError) -> Self { PeerError::AvctpError(error) } } impl From<PacketError> for PeerError { fn from(error: PacketError) -> Self { PeerError::PacketError(error) } } impl From<Error> for PeerError { fn from(error: Error) -> Self { PeerError::GenericError(error) } } /// A specialized stream combinator similar to Map. PeerIdStreamMap encapsulates another stream and /// wraps each item returned by the stream in a tuple that also returns the a specified PeerId as /// the first field and the wrapped item response as the second field. #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct PeerIdStreamMap<St> { stream: St, peer_id: PeerId, } impl<St: Unpin> Unpin for PeerIdStreamMap<St> {} // Conditional Unpin impl to make unsafe_pinned safe. impl<St> PeerIdStreamMap<St> where St: Stream, { unsafe_pinned!(stream: St); pub fn new(stream: St, peer_id: &PeerId) -> PeerIdStreamMap<St> { Self { stream, peer_id: peer_id.clone() } } } impl<St: FusedStream> FusedStream for PeerIdStreamMap<St> { fn is_terminated(&self) -> bool { self.stream.is_terminated() } } impl<St> Stream for PeerIdStreamMap<St> where St: Stream, { type Item = (PeerId, St::Item); fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.as_mut().stream().poll_next(cx).map(|opt| opt.map(|t| (self.peer_id.clone(), t))) } } // Forwarding impl of Sink to the underlying stream if there is one. impl<St: Stream + Sink<Item>, Item> Sink<Item> for PeerIdStreamMap<St> { type Error = St::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.stream().poll_ready(cx) } fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.stream().start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.stream().poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.stream().poll_close(cx) } }
extern crate arcball; extern crate cgmath; extern crate clock_ticks; extern crate glium; extern crate image; type Mat4 = cgmath::Matrix4<f32>; type CgPoint = cgmath::Point3<f32>; type CgVec = cgmath::Vector3<f32>; type Vector2 = cgmath::Vector2<f32>; type Vector3 = cgmath::Vector3<f32>; type Vector4 = cgmath::Vector4<f32>; pub mod aabb; pub mod camera; pub mod display; pub use aabb::AABB; pub use camera::Camera; pub use display::Display; /// Clamp `x` to be between `min` and `max` pub fn clamp<T: PartialOrd>(x: T, min: T, max: T) -> T { if x < min { min } else if x > max { max } else { x } } fn vec_min(v1: &Vector3, v2: &Vector3) -> Vector3 { Vector3::new(v1.x.min(v2.x), v1.y.min(v2.y), v1.z.min(v2.z)) } fn vec_max(v1: &Vector3, v2: &Vector3) -> Vector3 { Vector3::new(v1.x.max(v2.x), v1.y.max(v2.y), v1.z.max(v2.z)) }
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:two_macros.rs #![feature(use_extern_macros)] extern crate two_macros; // two identity macros `m` and `n` mod foo { pub use two_macros::n as m; } mod m1 { m!(use two_macros::*;); use foo::m; // This shadows the glob import } mod m2 { use two_macros::*; m! { //~ ERROR ambiguous use foo::m; } } mod m3 { use two_macros::m; fn f() { use two_macros::n as m; // This shadows the above import m!(); } fn g() { m! { //~ ERROR ambiguous use two_macros::n as m; } } } mod m4 { macro_rules! m { () => {} } use two_macros::m; m!(); //~ ERROR ambiguous } fn main() {}
use combine::parser::range::{range, take_while1}; use combine::parser::repeat::{sep_by}; use combine::parser::Parser; use combine::stream::{RangeStream, state::State}; use combine::error::ParseError; // Copy the fn header as is, only change ------------╮ // v fn tools<'a, I>() -> impl Parser<Input = I, Output = Vec<&'a str>> where I: RangeStream<Item = char, Range=&'a str>, I::Error: ParseError<I::Item, I::Range, I::Position>, { let tool = take_while1(|c : char| c.is_digit(10)); sep_by(tool, range(", ")) } fn decode(input : &str) -> Result<Vec<&str>, String> { match tools().easy_parse(State::new(input)) { Ok((output, _remaining_input)) => Ok(output), Err(err) => Err(format!("{} in `{}`", err, input)), } } fn main() { let input = "10Hammer, 123, Drill1"; // let input = "Hammer, Saw, Drill"; let output = decode(input).unwrap(); println!("{:?}", output); }
///! GIT REQ! mod git; mod remotes; use clap::{crate_authors, crate_version, App, AppSettings, ArgMatches, YamlLoader}; use colored::*; use git2::ErrorCode; use lazy_static::lazy_static; use log::{debug, error, info, trace}; use std::io::{self, stdin, stdout, Cursor, Write}; use std::{env, include_str, process}; use tabwriter::TabWriter; use yaml_rust::Yaml; lazy_static! { static ref APP_CFG: Yaml = { YamlLoader::load_from_str(include_str!("../cli-flags.yml")) .expect("Failed to load CLI config") .pop() .unwrap() }; } /// Get the remote for the current project fn get_remote(remote_name: &str, fetch_api_key: bool) -> Result<Box<dyn remotes::Remote>, String> { let remote_url = git::get_remote_url(remote_name); remotes::get_remote(remote_name, &remote_url, !fetch_api_key) } /// Get the remote, fail hard otherwise fn get_remote_hard(remote_name: &str, fetch_api_key: bool) -> Box<dyn remotes::Remote> { match get_remote(remote_name, fetch_api_key) { Ok(x) => x, Err(error) => { eprintln!( "{}", format!( "There was a problem finding the remote Git repo: {}", &error ) .red() ); process::exit(1); } } } /// Check out the branch corresponding to the MR ID and the remote's name fn checkout_mr(remote_name: &str, mr_id: i64) { info!("Getting MR: {}", mr_id); let mut remote = get_remote_hard(remote_name, true); debug!("Found remote: {}", remote); let remote_branch_name = match remote.get_remote_req_branch(mr_id) { Ok(name) => name, Err(error) => { eprintln!( "{}", format!( "There was a problem ascertaining the branch name: {}", &error ) .red() ); process::exit(1); } }; debug!("Got remote branch name: {}", remote_branch_name); match git::checkout_branch( remote_name, &remote_branch_name, &remote.get_local_req_branch(mr_id).unwrap(), remote.has_virtual_remote_branch_names(), ) { Ok(_) => { info!("Done!"); } Err(error) => { eprintln!( "{}", format!("There was an error checking out the branch: {}", &error).red() ); process::exit(1) } }; } /// Clear the API key for the current domain fn clear_domain_key(remote_name: &str) { trace!("Deleting domain key"); let mut remote = get_remote_hard(remote_name, false); let deleted = match git::delete_req_config(&remote.get_domain(), "apikey") { Ok(_) => Ok(true), Err(e) => match e.code() { ErrorCode::NotFound => Ok(false), _ => Err(e), }, }; match deleted { Ok(_) => eprintln!("{}", "Domain key deleted!".green()), Err(e) => { error!("Git Config error: {}", e); eprintln!( "{}", format!( "There was an error deleting the domain key: {}", e.message() ) .red() ); process::exit(1) } } } /// Set the API key for the current domain fn set_domain_key(remote_name: &str, new_key: &str) { trace!("Setting domain key: {}", new_key); let mut remote = get_remote_hard(remote_name, false); git::set_req_config(&remote.get_domain(), "apikey", new_key); eprintln!("{}", "Domain key changed!".green()); } /// Delete the project ID entry fn clear_project_id(remote_name: &str) { trace!("Deleting project ID for {}", remote_name); git::delete_config("projectid", remote_name); eprintln!("{}", "Project ID cleared!".green()); } /// Set the project ID fn set_project_id(remote_name: &str, new_id: &str) { trace!("Setting project ID: {} for remote: {}", new_id, remote_name); git::set_config("projectid", remote_name, new_id); eprintln!("{}", "New project ID set!".green()); } /// Set the default remote for the repository fn set_default_remote(remote_name: &str) { trace!("Setting default remote {}", remote_name); git::set_project_config("defaultremote", remote_name); eprintln!("{}", "New default remote set!".green()); } /// Print the open requests fn list_open_requests(remote_name: &str) { info!("Getting open requests"); let mut remote = get_remote_hard(remote_name, true); debug!("Found remote: {}", remote); let mrs = remote.get_req_names().unwrap(); let mut tw = TabWriter::new(io::stdout()).padding(4); for mr in &mrs { if remote.has_useful_branch_names() { writeln!( &mut tw, "{}\t{}\t{}", mr.id.to_string().green(), mr.source_branch.green().dimmed(), mr.title ) .unwrap(); } else { writeln!(&mut tw, "{}\t{}", mr.id.to_string().green(), mr.title).unwrap(); } } tw.flush().unwrap(); } /// Print a shell completion script fn generate_completion(app: &mut App, shell_name: &str) { let mut buffer = Cursor::new(Vec::new()); app.gen_completions_to("git-req", shell_name.parse().unwrap(), &mut buffer); let mut output = String::from_utf8(buffer.into_inner()).unwrap_or_else(|_| String::from("")); if shell_name == "zsh" { // Clap assigns the _files completor to the REQUEST_ID. This is undesirable. output = output.replace(":_files", ":"); } print!("{}", &output); } /// Get the name of the remote to use for the operation fn get_remote_name(matches: &ArgMatches) -> String { let default_remote_name = match git::get_project_config("defaultremote") { Some(remote_name) => remote_name, None => { let new_remote_name = match git::guess_default_remote_name() { Ok(guessed) => guessed, Err(_) => { let mut new_remote_name = String::new(); println!("Multiple remotes detected. Enter the name of the default one."); for remote in git::get_remotes() { println!(" * {}", remote); } print!("Remote name: "); let _ = stdout().flush(); stdin() .read_line(&mut new_remote_name) .expect("Did not input a name"); trace!("New remote: {}", &new_remote_name); if !git::get_remotes().contains(new_remote_name.trim()) { panic!("Invalid remote name provided") } new_remote_name } }; git::set_project_config("defaultremote", &new_remote_name); new_remote_name } }; // Not using Clap's default_value because of https://github.com/clap-rs/clap/issues/1140 String::from( matches .value_of("REMOTE_NAME") .unwrap_or(&default_remote_name), ) } /// Get the Clap app for CLI matching et al. fn build_cli<'a>() -> App<'a, 'a> { App::from_yaml(&APP_CFG) .version(crate_version!()) .author(crate_authors!("\n")) .setting(AppSettings::ArgsNegateSubcommands) .usage("git req [OPTIONS] [REQUEST_ID]") } /// Do the thing fn main() { color_backtrace::install(); let _ = env_logger::Builder::new() .parse_filters(&env::var("REQ_LOG").unwrap_or_default()) .try_init(); let mut app = build_cli(); let matches = app.get_matches(); if let Some(project_id) = matches.value_of("NEW_PROJECT_ID") { set_project_id(&get_remote_name(&matches), project_id); } else if matches.is_present("CLEAR_PROJECT_ID") { clear_project_id(&get_remote_name(&matches)); } else if matches.is_present("LIST_MR") { list_open_requests(&get_remote_name(&matches)); } else if matches.is_present("CLEAR_DOMAIN_KEY") { clear_domain_key(&get_remote_name(&matches)); } else if let Some(domain_key) = matches.value_of("NEW_DOMAIN_KEY") { set_domain_key(&get_remote_name(&matches), domain_key); } else if let Some(remote_name) = matches.value_of("NEW_DEFAULT_REMOTE") { set_default_remote(remote_name); } else if let Some(shell_name) = matches.value_of("GENERATE_COMPLETIONS") { app = build_cli(); generate_completion(&mut app, &shell_name); } else { checkout_mr( &get_remote_name(&matches), matches.value_of("REQUEST_ID").unwrap().parse().unwrap(), ); } }
use clap::{Clap, ValueHint}; use futures::future; use log::error; use rsplay::{data, scenario, Scenario}; use std::path::PathBuf; use std::process; #[derive(Clap, Debug)] #[clap(author, about, version)] struct Opts { #[clap(long, value_hint=ValueHint::FilePath, about = "scenario file path")] scenario: PathBuf, } async fn do_main(scenarios: Vec<Scenario>) { let tasks = scenarios.into_iter().map(scenario::run).collect::<Vec<_>>(); future::join_all(tasks).await; } #[tokio::main] async fn main() { env_logger::init(); let opt: Opts = Opts::parse(); let scenarios = data::load(opt.scenario).unwrap_or_else(|err| { error!("load scenario error: {:?}", err); process::exit(1); }); do_main(scenarios).await; }
use crate::enums::{Keyword, Symbol, TokenValue}; use std::iter::Peekable; use std::str::Chars; pub type Token = TokenValue; type LexResult = Result<Token, String>; pub struct Lexer<'a> { input: Peekable<Chars<'a>>, } /// Implementation of a DFA. impl<'a> Lexer<'a> { pub fn new(source: &'a str) -> Self { Self { input: source.chars().peekable(), } } fn try_convert_to_symbol(&mut self, token: Token) -> Token { let v = token.ident(); let symbol = Symbol::get(v.as_str()); if let Ok(sym) = symbol { return Token::Symbol(sym); } else { return token; } } fn try_convert_to_keyword(&mut self, token: Token) -> Token { let v = token.ident(); if v.len() > 0 && v.chars().nth(0).unwrap().is_alphanumeric() { let keyword = Keyword::get(&v); if let Ok(keyw) = keyword { return Token::Keyword(keyw); } else { return token; } } token } fn get_next(&mut self) -> Result<char, String> { if let Some(x) = self.input.next() { Ok(x) } else { Err("eof reached".to_string()) } } fn peek_next(&mut self) -> Result<&char, String> { if let Some(x) = self.input.peek() { Ok(x) } else { Err("eof reached".to_string()) } } fn lex_identifier(&mut self, c: char) -> LexResult { let mut ident = String::new(); ident.push(c); loop { if let Ok(&c) = self.peek_next() { if c.is_alphanumeric() || c == '_' { ident.push(self.get_next()?); } else { break Ok(Token::Ident(ident)); } } } } fn lex_number_literal(&mut self, c: char) -> LexResult { let mut num = "".to_string(); num.push(c); let mut is_float = false; loop { let c = *self.peek_next()?; if !c.is_alphanumeric() && c != '.' { break; } else { is_float = is_float || c == '.'; num.push(self.get_next()?); } } if is_float { num = num .trim_end_matches(|c| match c { 'a'..='z' | 'A'..='Z' | '+' | '-' => true, _ => false, }) .to_string(); let f: f64 = num.parse().unwrap(); return Ok(Token::NumFloat(f)); } let num = if num.len() > 2 && num.chars().nth(1).unwrap() == 'x' { parse_hex_num(&num[2..]).0 // .1 of pair is the suffix } else if num.chars().nth(0) == Some('0') { parse_oct_num(&num[1..]).0 } else { parse_dec_num(num.as_str()).0 }; Ok(Token::NumInt(num)) } fn lex_symbol(&mut self, c: char) -> LexResult { let mut symbol = String::new(); symbol.push(c); if let Ok(&next_c) = self.peek_next() { match c { '+' => { if next_c == '=' || next_c == c { symbol.push(self.get_next()?); } } '-' => { if next_c == '=' || next_c == '>' || next_c == c { symbol.push(self.get_next()?); } } '*' | '/' | '%' | '=' | '^' | '!' => { if next_c == '=' { symbol.push(self.get_next()?); } } '<' | '>' | '&' | '|' => { if next_c == c || next_c == '=' { symbol.push(self.get_next()?); } } '.' => { if self.peek_next()? == &'.' { symbol.push(self.get_next()?); symbol.push(self.get_next()?); } } _ => (), } } Ok(Token::Symbol(Symbol::get(&symbol).unwrap())) } fn lex_escaped_char(&mut self) -> Result<char, String> { let c = self.get_next()?; match c { '\'' | '"' | '?' | '\\' => Ok(c), 'a' => Ok('\x07'), 'b' => Ok('\x08'), 'f' => Ok('\x0c'), 'n' => Ok('\x0a'), 'r' => Ok('\x0d'), 't' => Ok('\x09'), 'v' => Ok('\x0b'), 'x' => { let mut hex = "".to_string(); loop { let c = self.get_next()?; if c.is_alphanumeric() { hex.push(c); } else { break; } self.get_next()?; } Ok(parse_hex_num(hex.as_str()).0 as i32 as u8 as char) } '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' => { // if '0', check whether octal number \nnn or null \0 if self.get_next()?.is_numeric() { let mut oct = "".to_string(); oct.push(c); loop { let c = self.get_next()?; oct.push(c); if !c.is_numeric() { oct.pop(); break; } } Ok(parse_oct_num(oct.as_str()).0 as i32 as u8 as char) } else { Ok('\x00') } } _ => Ok(c), } } fn lex_string(&mut self) -> LexResult { let mut string = String::new(); loop { match self.get_next()? { '"' => break Ok(Token::String(string)), '\\' => string.push(self.lex_escaped_char()?), c => string.push(c), } } } fn lex_char(&mut self) -> LexResult { let c = { let v = self.get_next()?; if v == '\\' { self.lex_escaped_char()? } else { v } }; if self.get_next()? != '\'' { panic!("missing terminating \' char"); } Ok(Token::Char(c)) } fn lex_primary(&mut self) -> LexResult { let c = self.get_next()?; match c { 'a'..='z' | 'A'..='Z' | '_' => self.lex_identifier(c), // TODO: set leading space ' ' | '\t' => self.lex_primary(), '0'..='9' => self.lex_number_literal(c), '\"' => self.lex_string(), '\'' => self.lex_char(), '\n' => Ok(Token::Newline), '\\' => { while self.get_next()? != '\n' {} self.lex_primary() } '/' => { // Handle multiline comments if self.peek_next()? == &'*' { self.get_next()?; // eat '*' let mut last = ' '; while !(last == '*' && self.peek_next()? == &'/') { last = self.get_next()?; } self.get_next()?; // eat '/' self.lex_primary() } // Handle singleline comments else if self.peek_next()? == &'/' { self.get_next()?; while self.peek_next()? != &'\n' { self.get_next()?; } self.lex_primary() } else { self.lex_symbol(c) } } '(' | ')' | '{' | '}' | '[' | ']' | ',' | ';' | ':' | '.' | '+' | '-' | '*' | '%' | '!' | '~' | '<' | '>' | '^' | '|' | '&' | '=' | '#' | '?' => self.lex_symbol(c), _ => { // TODO: should handle next file if let Err(x) = self.peek_next() { Err(x) } else { self.lex_primary() } } } } pub fn read_token(&mut self) -> LexResult { let token = self.lex_primary(); token.and_then(|tok| match tok { Token::Newline => self.read_token(), Token::Ident(_) => match self.try_convert_to_keyword(tok.clone()) { Token::Keyword(token) => Ok(Token::Keyword(token)), Token::Ident(_) => Ok(self.try_convert_to_symbol(tok)), _ => Ok(tok), }, // Token::Ident(_) => Ok(self.try_convert_to_symbol(tok)), _ => Ok(tok), }) } fn lex_single_arg(&mut self, end: &mut bool) -> Result<Vec<Token>, String> { let mut nest = 0; let mut arg = Vec::new(); loop { let tok = self.lex_primary()?; let val = tok.ident(); if nest == 0 { match val.as_str() { ")" => { *end = true; break; } "," => break, _ => {} } } match val.as_str() { "(" => nest += 1, ")" => nest -= 1, _ => {} } arg.push(tok); } Ok(arg) } } fn parse_hex_num(v: &str) -> (i64, String) { let mut suffix = String::new(); let n = v.chars().fold(0, |n, c| match c { '0'..='9' | 'A'..='F' | 'a'..='f' => n * 16 + c.to_digit(16).unwrap() as u64, _ => { suffix.push(c); n } }); (n as i64, suffix) } fn parse_dec_num(v: &str) -> (i64, String) { let mut suffix = "".to_string(); let n = v.chars().fold(0, |n, c| match c { '0'..='9' => n * 10 + c.to_digit(10).unwrap() as u64, _ => { suffix.push(c); n } }); (n as i64, suffix) } fn parse_oct_num(v: &str) -> (i64, String) { let mut suffix = "".to_string(); let n = v.chars().fold(0, |n, c| match c { '0'..='7' => n * 8 + c.to_digit(8).unwrap() as u64, _ => { suffix.push(c); n } }); (n as i64, suffix) } #[test] fn assign_number() { let test_str = "int x=0xA ;"; let mut l = Lexer::new(test_str); assert_eq!(l.read_token(), Ok(Token::Keyword(Keyword::Int))); assert_eq!(l.read_token(), Ok(Token::Ident("x".to_string()))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Assign))); assert_eq!(l.read_token(), Ok(Token::NumInt(10))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Semicolon))); assert_eq!(l.read_token(), Err("eof reached".to_string())); } #[test] fn if_else() { let test_str = "if (x == 3) { y; } else { z; }"; let mut l = Lexer::new(test_str); assert_eq!(l.read_token(), Ok(Token::Keyword(Keyword::If))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::OpeningParen))); assert_eq!(l.read_token(), Ok(Token::Ident("x".to_string()))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Eq))); assert_eq!(l.read_token(), Ok(Token::NumInt(3))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::ClosingParen))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::OpeningCurlyBrac))); assert_eq!(l.read_token(), Ok(Token::Ident("y".to_string()))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Semicolon))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::ClosingCurlyBrac))); assert_eq!(l.read_token(), Ok(Token::Keyword(Keyword::Else))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::OpeningCurlyBrac))); assert_eq!(l.read_token(), Ok(Token::Ident("z".to_string()))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Semicolon))); assert_eq!( l.read_token().unwrap(), Token::Symbol(Symbol::ClosingCurlyBrac) ); assert_eq!(l.read_token(), Err("eof reached".to_string())); } #[test] fn string_and_char() { let test_str = "char abc = 'a'; \"oie\""; let mut l = Lexer::new(test_str); assert_eq!(l.read_token(), Ok(Token::Keyword(Keyword::Char))); assert_eq!(l.read_token(), Ok(Token::Ident("abc".to_string()))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Assign))); assert_eq!(l.read_token(), Ok(Token::Char('a'))); assert_eq!(l.read_token(), Ok(Token::Symbol(Symbol::Semicolon))); assert_eq!(l.read_token(), Ok(Token::String("oie".to_string()))); assert_eq!(l.read_token(), Err("eof reached".to_string())); } #[test] fn comment() { let test_str = "// dsadsadsadas\nx // aa \n/*dsada\n\n*/"; let mut l = Lexer::new(test_str); assert_eq!(l.read_token(), Ok(Token::Ident("x".to_string()))); assert_eq!(l.read_token(), Err("eof reached".to_string())); }
//! Create graphene and other substrates for use in molecular dynamics simulations. extern crate colored; extern crate dialoguer; extern crate serde; extern crate serde_json; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate grafen; extern crate mdio; mod error; mod output; mod ui; use error::{GrafenCliError, Result}; use ui::read_configuration; use grafen::database::{read_database, ComponentEntry, DataBase}; use grafen::read_conf::ReadConf; use colored::*; use std::env::{current_dir, home_dir, var, var_os}; use std::fs::DirBuilder; use std::process; use std::path::PathBuf; use structopt::StructOpt; const DEFAULT_DBNAME: &str = "database.json"; /// The program run configuration. pub struct Config { /// Title of output system. pub title: String, /// Path to output file. pub output_path: PathBuf, /// Input components that were read from the command line. pub components: Vec<ComponentEntry>, /// Database of residue and substrate definitions. pub database: DataBase, } impl Config { /// Parse the input command line arguments and read the `DataBase`. /// /// # Errors /// Returns an error if the `DataBase` (if given as an input) could not be read. fn new() -> Result<Config> { eprintln!("{} {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); let options = CliOptions::from_args(); let output_path = options.output; let title = options.title.unwrap_or("System created by grafen".into()); let mut database = match options.database { Some(path) => read_database(&path).map_err(|err| GrafenCliError::from(err)), None => read_or_create_default_database(), }?; let (components, mut entries) = read_input_configurations(options.input_confs); database.component_defs.append(&mut entries); Ok(Config { title, output_path, components, database }) } } #[derive(StructOpt, Debug)] #[structopt(raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Command line options struct CliOptions { #[structopt(short = "t", long = "title")] /// Title of output system title: Option<String>, #[structopt(short = "o", long = "output", default_value = "conf.gro", parse(from_os_str))] /// Output configuration file output: PathBuf, #[structopt(short = "d", long = "database", parse(from_os_str))] /// Path to residue and component database database: Option<PathBuf>, #[structopt(short = "c", long = "conf", parse(from_os_str))] /// Path to input configuration files to add as components input_confs: Vec<PathBuf>, } fn main() { if let Err(err) = Config::new().and_then(|conf| ui::user_menu(conf)) { eprintln!("{}", err); process::exit(1); } } fn read_input_configurations(confs: Vec<PathBuf>) -> (Vec<ComponentEntry>, Vec<ComponentEntry>) { let mut configurations = Vec::new(); for path in confs { match read_configuration(&path) { Ok(conf) => configurations.push(conf), Err(err) => eprintln!("{}", err), } } eprint!("\n"); let current_dir = current_dir().unwrap_or(PathBuf::new()); let entries = configurations .iter() .map(|conf| ReadConf { conf: None, path: current_dir.join(&conf.path), backup_conf: None, description: conf.description.clone(), volume_type: conf.volume_type.clone(), }) .map(|conf| ComponentEntry::ConfigurationFile(conf)) .collect::<Vec<_>>(); let components = configurations .into_iter() .map(|conf| ComponentEntry::ConfigurationFile(conf)) .collect::<Vec<_>>(); (components, entries) } fn read_or_create_default_database() -> Result<DataBase> { let default_database_paths = get_default_database_paths(); if default_database_paths.is_empty() { eprintln!("{}", format!( "Could not find a location for the default database. \ Opening a database which cannot be saved.", ).color("yellow")); return Ok(DataBase::new()); } // See if a default database can be found at any path before creating a new one. for path in &default_database_paths { if path.is_file() { return read_database(&path).map_err(|err| GrafenCliError::from(err)) } } let mut default_database = DataBase::new(); let default_path = &default_database_paths[0]; if let Some(parent_dir) = default_path.parent() { match DirBuilder::new().recursive(true).create(&parent_dir) { Ok(_) => default_database.set_path(&default_path).unwrap(), Err(err) => { eprintln!("{}", format!( "Warning: Could not create a folder for a default database at '{}' ({}). \ Opening a database which cannot be saved.", default_path.display(), err ).color("yellow")); }, } } Ok(default_database) } fn get_default_database_paths() -> Vec<PathBuf> { get_platform_dependent_data_dirs() .into_iter() .map(|dir| dir.join("grafen").join(DEFAULT_DBNAME)) .collect() } fn get_platform_dependent_data_dirs() -> Vec<PathBuf> { let xdg_data_dirs_variable = var("XDG_DATA_DIRS") .unwrap_or(String::from("/usr/local/share:/usr/local")); let xdg_dirs_iter = xdg_data_dirs_variable.split(':').map(|s| Some(PathBuf::from(s))); let dirs = if cfg!(target_os = "macos") { vec![ var_os("XDG_DATA_HOME").map(|dir| PathBuf::from(dir)), home_dir().map(|dir| dir.join("Library").join("Application Support")) ].into_iter() .chain(xdg_dirs_iter) .chain(vec![Some(PathBuf::from("/").join("Library").join("Application Support"))]) .collect() } else if cfg!(target_os = "linux") { vec![ var_os("XDG_DATA_HOME").map(|dir| PathBuf::from(dir)), home_dir().map(|dir| dir.join(".local").join("share")) ].into_iter() .chain(xdg_dirs_iter) .collect() } else if cfg!(target_os = "windows") { vec![var_os("APPDATA").map(|dir| PathBuf::from(dir))] } else { Vec::new() }; dirs.into_iter().filter_map(|dir| dir).collect() } #[cfg(test)] pub mod tests { use super::*; use std::env::set_var; use std::path::Component; #[test] #[cfg(target_os = "macos")] fn default_database_dirs_on_macos_lead_with_xdg_dirs_then_application_support() { let xdg_data_home = "data_home"; set_var("XDG_DATA_HOME", xdg_data_home); let xdg_data_directories = vec!["data_dir1", "data_dir2"]; let xdg_data_dirs = format!("{}:{}", xdg_data_directories[0], xdg_data_directories[1]); set_var("XDG_DATA_DIRS", xdg_data_dirs); let user_appsupport = home_dir().unwrap().join("Library").join("Application Support"); let root_appsupport = PathBuf::from("/").join("Library").join("Application Support"); let result = get_platform_dependent_data_dirs(); let priority_list = vec![ PathBuf::from(xdg_data_home), user_appsupport, PathBuf::from(xdg_data_directories[0]), PathBuf::from(xdg_data_directories[1]), root_appsupport ]; assert_eq!(result, priority_list); } #[test] #[cfg(target_os = "linux")] fn default_database_dirs_on_linux_lead_with_xdg_dirs_then_local_share() { let xdg_data_home = "data_home"; set_var("XDG_DATA_HOME", xdg_data_home); let xdg_data_directories = vec!["data_dir1", "data_dir2"]; let xdg_data_dirs = format!("{}:{}", xdg_data_directories[0], xdg_data_directories[1]); set_var("XDG_DATA_DIRS", xdg_data_dirs); let user_local_share = home_dir().unwrap().join(".local").join("share"); let result = get_platform_dependent_data_dirs(); let priority_list = vec![ PathBuf::from(xdg_data_home), user_local_share, PathBuf::from(xdg_data_directories[0]), PathBuf::from(xdg_data_directories[1]) ]; assert_eq!(result, priority_list); } #[test] #[cfg(any(unix, windows))] fn default_database_path_adds_grafen_directory_and_database_path() { let dirs = get_default_database_paths(); assert!(!dirs.is_empty()); for path in dirs { let mut iter = path.components().rev(); assert_eq!(iter.next().unwrap(), Component::Normal(DEFAULT_DBNAME.as_ref())); assert_eq!(iter.next().unwrap(), Component::Normal("grafen".as_ref())); } } }
mod with_function; use proptest::prop_assert_eq; use proptest::strategy::Strategy; use crate::erlang::is_function_2::result; use crate::test::strategy; #[test] fn without_function_returns_false() { run!( |arc_process| { ( strategy::term::is_not_function(arc_process.clone()), strategy::term::function::arity(arc_process.clone()), ) }, |(function, arity)| { prop_assert_eq!(result(function, arity), Ok(false.into())); Ok(()) }, ); }
use serde::{Deserialize, Serialize}; use serde_json::Result; use crate::api::message::amount::{Amount, string_or_struct}; use crate::api::message::meta::*; use std::error::Error; use std::fmt; /* @4.12获得账号交易列表 RequestAccountTxCommand 请求格式 id: u64, //(固定值): 1 command: String, //(固定值): account_tx account: String, //需要用户传递的参数,钱包的地址 ledger_index_min: i32 //(固定值): 0 ledger_index_max: i32 //(固定值): -1 limit: Option<u64> //需要用户传递的参数,限定返回多少条记录,默认200 */ #[derive(Serialize, Deserialize, Debug)] pub struct RequestAccountTxCommand { #[serde(rename="id")] id: u64, #[serde(rename="command")] command: String, #[serde(rename="account")] account: String, #[serde(rename="ledger_index_min")] ledger_index_min: i32, #[serde(rename="ledger_index_max")] ledger_index_max: i32, #[serde(rename="limit")] limit: Option<u64>, } impl RequestAccountTxCommand { pub fn with_params(account: String, limit: Option<u64>) -> Box<Self> { let mut n = Some(200); if limit.is_some() { n = limit; } Box::new( RequestAccountTxCommand { id: 1, command: "account_tx".to_string(), account: account, ledger_index_min: 0, ledger_index_max: -1, limit: n, } ) } pub fn to_string(&self) -> Result<String> { let j = serde_json::to_string(&self)?; Ok(j) } } ///////////////////////// /* RequestAccountTxResponse 数据返回格式 */ #[derive(Serialize, Deserialize, Debug)] pub struct Marker { #[serde(rename="ledger")] pub ledger: u64, #[serde(rename="seq")] pub seq: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct Tx { #[serde(rename="Account")] pub account: String, #[serde(rename="Fee")] pub fee: String, #[serde(rename="Flags")] pub flags: u64, //#[serde(rename="OfferSequence")] //pub offer_sequence: u64, #[serde(rename="Sequence")] pub sequence: u64, #[serde(rename="SigningPubKey")] pub signing_pub_key: String, #[serde(rename="TakerGets")] #[serde(deserialize_with = "string_or_struct")] pub taker_gets: Amount, #[serde(rename="TakerPays")] #[serde(deserialize_with = "string_or_struct")] pub taker_pays: Amount, #[serde(rename="Timestamp")] pub timestamp: u64, #[serde(rename="TransactionType")] pub transaction_type: String, #[serde(rename="TxnSignature")] pub txn_signature: String, #[serde(rename="date")] pub date: u64, #[serde(rename="hash")] pub hash: String, #[serde(rename="inLedger")] pub in_ledger: u64, #[serde(rename="ledger_index")] pub ledger_index: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct Transaction { #[serde(rename="meta")] pub meta: Meta, #[serde(rename="tx")] pub tx: Tx, #[serde(rename="validated")] pub validated: bool, } #[derive(Serialize, Deserialize, Debug)] pub struct RequestAccountTxResponse { #[serde(rename="account")] pub account: String, #[serde(rename="ledger_index_max")] pub ledger_index_max: u64, #[serde(rename="ledger_index_min")] pub ledger_index_min: u64, #[serde(rename="marker")] pub marker: Option<Marker>, #[serde(rename="limit")] pub limit: u64, #[serde(rename="transactions")] pub transactions: Vec<Transaction>, } //AccounTx #[derive(Debug, Serialize, Deserialize)] pub struct AccounTxSideKick { pub error : String, pub error_code : i32, pub error_message : String, pub id : u32, pub request : RequestAccountTxCommand, pub status : String, #[serde(rename="type")] pub rtype : String, } impl fmt::Display for AccounTxSideKick { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "AccounTxSideKick is here!") } } impl Error for AccounTxSideKick { fn description(&self) -> &str { "I'm AccounTxSideKick side kick" } }
/// 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。 /// /// 示例 1: /// /// 输入: [10,2] /// 输出: 210 /// /// 示例 2: /// /// 输入: [3,30,34,5,9] /// 输出: 9534330 /// /// 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。 use std::cmp::Ordering; pub fn largest_number(nums: Vec<i32>) -> String { let mut v: Vec<String> = nums.into_iter().map(|x| x.to_string()).collect(); v.sort_by(|a, b| { let ord = (String::from("") + a + b).cmp(&(String::from("") + b + a)); match ord { Ordering::Equal => Ordering::Equal, Ordering::Less => Ordering::Greater, Ordering::Greater => Ordering::Less, } }); println!("v = {:?}", v); let vv: String = v.into_iter().collect::<String>().trim_start_matches('0').to_string(); println!("vv = {:?}", vv); if vv.len() > 0 { vv } else { "0".to_string() } } #[cfg(test)] mod test { use super::largest_number; #[test] fn test_largest_number() { assert_eq!(largest_number(vec![0, 0]), "0"); assert_eq!(largest_number(vec![10, 2]), "210"); assert_eq!(largest_number(vec![3, 30, 34, 5, 9]), "9534330"); assert_eq!(largest_number(vec![9051,5526,2264,5041,1630,5906,6787,8382,4662,4532,6804,4710,4542,2116,7219,8701,8308,957,8775,4822,396,8995,8597,2304,8902,830,8591,5828,9642,7100,3976,5565,5490,1613,5731,8052,8985,2623,6325,3723,5224,8274,4787,6310,3393,78,3288,7584,7440,5752,351,4555,7265,9959,3866,9854,2709,5817,7272,43,1014,7527,3946,4289,1272,5213,710,1603,2436,8823,5228,2581,771,3700,2109,5638,3402,3910,871,5441,6861,9556,1089,4088,2788,9632,6822,6145,5137,236,683,2869,9525,8161,8374,2439,6028,7813,6406,7519] ), "995998549642963295795569525905189958985890288238775871870185978591838283748308830827481618052787813771758475277519744072727265721971071006861683682268046787640663256310614560285906582858175752573156385565552654905441522852245213513750414822478747104662455545424532434289408839763963946391038663723370035134023393328828692788270926232581243924362362304226421162109163016131603127210891014" ); } }
use crate::process::DrawProcess; #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] /// This is a frame. It stores the terminal's size in a convenient place. /// It isn't stored in a grid, as grids are altered when they're split. /// For examples, see the frame's methods. pub struct Frame { grid: Grid, } impl Frame { /** Creates a new frame. # Example ``` rust # use grid_ui::grid::Frame; # fn main() { let ten_by_ten: Frame = Frame::new(0, 0, 10, 10); # } ``` */ pub fn new(x_min: usize, y_min: usize, x_max: usize, y_max: usize) -> Frame { Frame { grid: Grid { start_x: x_min, start_y: y_min, end_x: x_max, end_y: y_max, }, } } /** Produces a fresh grid, which contains the entire frame. # Example ``` rust # use grid_ui::grid::Frame; # use grid_ui::grid::Grid; # fn main() { let ten_by_ten: Frame = Frame::new(0, 0, 10, 10); let ten_by_ten_grid: Grid = ten_by_ten.next_frame(); assert_eq!(ten_by_ten_grid, Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 10}); # } ``` */ pub fn next_frame(&self) -> Grid { self.grid.clone() } /** Resizes the grid, changing its size. # Example ``` rust # use grid_ui::grid::Frame; # use grid_ui::grid::Grid; # fn main() { let mut ten_by_ten: Frame = Frame::new(0, 0, 10, 10); let ten_by_ten_grid: Grid = ten_by_ten.next_frame(); assert_eq!(ten_by_ten_grid, Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 10}); ten_by_ten.resize(5, 5, 10, 10); let five_by_five_grid: Grid = ten_by_ten.next_frame(); assert_eq!(five_by_five_grid, Grid {start_x: 5, start_y: 5, end_x: 10, end_y: 10}); # } ``` */ pub fn resize(&mut self, x_min: usize, y_min: usize, x_max: usize, y_max: usize) { self.grid = Grid { start_x: x_min, start_y: y_min, end_x: x_max, end_y: y_max, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] /// Whether the alignment is in the negative direction [up/left] or in the positive direction [down/right]. /// Alignments will have different behaviors depending on where they're used. pub enum Alignment { Minus, Plus, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] enum Maximum { None, X(usize, Alignment), Y(usize, Alignment), } impl Default for Maximum { fn default() -> Self { Maximum::None } } #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Default, Hash)] /** Inputting this to a grid will give a GridData based on the specifications used in the function. # Examples Creating a grid ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let chunk = grid.split(&SplitStrategy::new()); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 10})); # Ok(()) # } ``` */ pub struct SplitStrategy { min_size_x: Option<usize>, min_size_y: Option<usize>, max_size: Maximum, } impl SplitStrategy { /** Creates an empty split strategy. Empty strategies will simply take up the entire grid when used. # Examples The default grid: ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let chunk = grid.split(&SplitStrategy::new()); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 10})); # Ok(()) # } ``` */ pub fn new() -> SplitStrategy { SplitStrategy { min_size_x: None, min_size_y: None, max_size: Maximum::None, } } /** Sets a maximum X value. The resulting grid will only be at most of length v. It'll be either on the left or the right, depending on the alignment (left = minus). # Panics Only one maximum direction can be set. Otherwise, this function will panic. This is intended. # Examples Applying a grid with a maximum x value ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let chunk = grid.split(&SplitStrategy::new().max_x(5, Alignment::Minus)); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 0, end_x: 5, end_y: 10})); let chunk = grid.split(&SplitStrategy::new().max_x(2, Alignment::Plus)); assert_eq!(chunk, Some(Grid {start_x: 8, start_y: 0, end_x: 10, end_y: 10})); # Ok(()) # } ``` This function will panic - you can't set two maximums. ```should_panic # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let cannot_set_both_x_and_y = SplitStrategy::new().max_x(2, Alignment::Minus).max_y(1, Alignment::Plus); # Ok(()) # } ``` */ pub fn max_x(mut self, v: usize, a: Alignment) -> Self { if matches!(self.max_size, Maximum::None) { self.max_size = Maximum::X(v, a); self } else { panic!("A maximum already exists!") } } /** Sets a maximum Y value. The resulting grid data will only be of height v. It'll be either on the top or the bottom, depending on the alignment (top = minus). # Panics Only one maximum direction can be set. Otherwise, this function will panic. This is intended. # Examples Applying a grid with a maximum x value ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let chunk = grid.split(&SplitStrategy::new().max_y(5, Alignment::Minus)); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 5})); let chunk = grid.split(&SplitStrategy::new().max_y(2, Alignment::Plus)); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 8, end_x: 10, end_y: 10})); # Ok(()) # } ``` This function will panic - you can't set two maximums. ```should_panic # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let cannot_set_both_x_and_y = SplitStrategy::new().max_x(2, Alignment::Minus).max_y(1, Alignment::Plus); # Ok(()) # } ``` */ pub fn max_y(mut self, v: usize, a: Alignment) -> Self { if matches!(self.max_size, Maximum::None) { self.max_size = Maximum::Y(v, a); self } else { panic!("A maximum already exists!") } } /** Sets a minimum X value. If the grid cannot give the grid data this amount of length, no strategy will be returned. # Examples ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let chunk = grid.split(&SplitStrategy::new().min_x(15)); assert_eq!(chunk, None); let chunk = grid.split(&SplitStrategy::new().min_x(5)); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 10})); # Ok(()) # } ``` */ pub fn min_x(mut self, v: usize) -> Self { self.min_size_x = Some(v); self } /** Sets a minimum Y value. If the grid cannot give the grid data this amount of height, no strategy will be returned. # Examples ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let chunk = grid.split(&SplitStrategy::new().min_y(15)); assert_eq!(chunk, None); let chunk = grid.split(&SplitStrategy::new().min_y(5)); assert_eq!(chunk, Some(Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 10})); # Ok(()) # } ``` */ pub fn min_y(mut self, v: usize) -> Self { self.min_size_y = Some(v); self } #[doc(hidden)] /// Applies a split strategy. This is meant to be indirectly called. fn apply(&self, grid: &mut Grid) -> Option<Grid> { if grid.start_x == grid.end_x || grid.start_y == grid.end_y { // no space left return None; } if let Some(val) = self.min_size_y { // below minimum size if grid.end_y <= grid.start_y + val { return None; } } if let Some(val) = self.min_size_x { // below minimum size if grid.end_x <= grid.start_x + val { return None; } } match &self.max_size { Maximum::None => { // Takes up the entire grid let return_value = Some(Grid::new(grid.start_x, grid.start_y, grid.end_x, grid.end_y)); grid.start_x = grid.end_x; grid.start_y = grid.end_y; return_value } Maximum::X(size, alignment) => { let size = *size; let size = size.min(grid.end_x - grid.start_x); if matches!(alignment, Alignment::Minus) { // Takes up the entire grid, up to the maximum size from the left. let return_value = Some(Grid::new(grid.start_x, grid.start_y, grid.start_x + size, grid.end_y)); grid.start_x += size; return_value } else { // Takes up the entire grid, up to the maximum size from the right. let return_value = Some(Grid::new(grid.end_x - size, grid.start_y, grid.end_x, grid.end_y)); grid.end_x -= size; return_value } } Maximum::Y(size, alignment) => { let size = *size; let size = size.min(grid.end_y - grid.start_y); if matches!(alignment, Alignment::Minus) { // Takes up the entire grid, up to the maximum size from the top. let return_value = Some(Grid::new(grid.start_x, grid.start_y, grid.end_x, grid.start_y + size)); grid.start_y += size; return_value } else { // Takes up the entire grid, up to the maximum size from the bottom. let return_value = Some(Grid::new(grid.start_x, grid.end_y - size, grid.end_x, grid.end_y)); grid.end_y -= size; return_value } } } } } #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] /// A grid - basically, a square meant to resemble a portion of a terminal. Can be split up into other grids. /// Cloning a grid is bad practice! Use it only if you must. pub struct Grid { pub start_x: usize, pub start_y: usize, pub end_x: usize, pub end_y: usize, } impl Grid { fn new(start_x: usize, start_y: usize, end_x: usize, end_y: usize) -> Grid { Grid { start_x, start_y, end_x, end_y, } } /** Splits the grid into two others based on a SplitStrategy. With the default split strategy, the entire grid will go into the returned grid, leaving the first one empty. Expect to use this function a lot. # Return value Returns None if no new grid can be created - either because the grid is already empty or because it's below the minimum size. # Examples ``` rust # use grid_ui::out; # use grid_ui::trim::Ignore; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let second = grid.split(&SplitStrategy::new().max_y(5, Alignment::Minus)); assert_eq!(second, Some(Grid {start_x: 0, start_y: 0, end_x: 10, end_y: 5})); assert_eq!(grid, Grid {start_x: 0, start_y: 5, end_x: 10, end_y: 10}); let cant_be_made = grid.split(&SplitStrategy::new().min_y(6)); assert_eq!(cant_be_made, None); let takes_up_all = grid.split(&SplitStrategy::new()); assert_eq!(takes_up_all, Some(Grid {start_x: 0, start_y: 5, end_x: 10, end_y: 10})); assert_eq!(grid, Grid {start_x: 10, start_y: 10, end_x: 10, end_y: 10}); let cant_be_made = grid.split(&SplitStrategy::new()); assert_eq!(cant_be_made, None); # Ok(()) # } ``` */ pub fn split(&mut self, strategy: &SplitStrategy) -> Option<Grid> { strategy.apply(self) } /** Extends the grid in the either direction, either positive or negative, if the input is compatible (ie grids are next to each other and of similar dimensions) If the two grids are incompatible, it returns an error and gives the grid back. # Example ``` rust # use grid_ui::grid; # use grid_ui::out; # use grid_ui::trim::Ignore; # fn main() -> Result<(), ()>{ let mut grid = grid::Frame::new(0, 0, 10, 10).next_frame(); let mut second_grid = grid.split(&grid::SplitStrategy::new().max_y(5, grid::Alignment::Plus)).ok_or(())?; assert_eq!(grid.end_y, 5); assert!(grid.extend(second_grid).is_ok()); assert_eq!(grid.end_y, 10); let incompatible_grid = grid::Frame::new(4, 4, 8, 8).next_frame(); assert!(grid.extend(incompatible_grid).is_err()); # Ok(()) # } ``` */ pub fn extend(&mut self, grid: Grid) -> Result<(), Grid> { if self.start_x == grid.start_x && self.end_x == grid.end_x { if self.end_y == grid.start_y { self.end_y = grid.end_y; return Ok(()) } if self.start_y == grid.end_y { self.start_y = grid.start_y; return Ok(()) } } if self.start_y == grid.start_y && self.end_y == grid.end_y { if self.end_x == grid.start_x { self.end_x = grid.end_x; return Ok(()) } if self.start_x == grid.end_x { self.start_x = grid.start_x; return Ok(()) } } Err(grid) } /** Converts the grid into a DrawProcess. The draw process can then be used to draw onto the terminal. # Examples ``` rust # use grid_ui::out; # use grid_ui::trim::Truncate; # use grid_ui::grid::*; # fn main() -> Result<(), ()>{ let mut grid = Frame::new(0, 0, 10, 10).next_frame(); let mut process = grid.into_process(DividerStrategy::End); process.add_to_section("Some text".to_string(), &mut Truncate, Alignment::Minus); # Ok(()) # } ``` */ pub fn into_process(self, strategy: DividerStrategy) -> DrawProcess { DrawProcess::new(self, strategy) } } #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] /// Where the divider will be placed. The divider is between two sides: A plus side and a minus side. /// Content can be added on the plus or minus side if there's space available. /// For examples of divider behavior, see docs for DrawProcess. pub enum DividerStrategy { Beginning, End, Halfway, Pos(usize), }
extern crate echo_rust_grpc_proto; extern crate grpc; extern crate server; extern crate tls_api_stub; fn main() { let mut server = grpc::ServerBuilder::<tls_api_stub::TlsAcceptor>::new(); server.http.set_port(50051); server.add_service(echo_rust_grpc_proto::EchoServer::new_service_def( server::EchoImpl, )); server.http.set_cpu_pool_threads(4); let server = server.build().expect("server"); let port = server.local_addr().port().unwrap(); println!("Echo server started on port {}", port); loop { std::thread::park(); } }
use proconio::{input, marker::Usize1}; fn main() { input! { n: usize, positions: [(Usize1, Usize1); n - 1], }; let mut bad = vec![vec![false; n]; n]; for (r, c) in positions { bad[r][c] = true; for i in 0..n { bad[i][c] = true; } for j in 0..n { bad[r][j] = true; } // ななめ方向を bad[*][*] = true にする for (i, j) in (0..r).rev().zip((0..c).rev()) { bad[i][j] = true; } for (i, j) in ((r + 1)..n).zip(c + 1..n) { bad[i][j] = true; } for (i, j) in (0..r).rev().zip((c + 1)..n) { bad[i][j] = true; } for (i, j) in ((r + 1)..n).zip((0..c).rev()) { bad[i][j] = true; } } for i in 0..n { for j in 0..n { if bad[i][j] == false { println!("{} {}", i + 1, j + 1); return; } } } println!("-1"); }
use test_winrt_method_names::*; use windows as Windows; use windows::core::*; use windows::Foundation::*; use Component::MethodNames::*; #[implement(Component::MethodNames::IMethodNames)] struct MethodNames(i64); #[allow(non_snake_case)] impl MethodNames { fn Method(&self) -> Result<()> { Ok(()) } fn Property(&self) -> Result<i64> { Ok(self.0) } fn SetProperty(&mut self, value: i64) -> Result<()> { self.0 = value; Ok(()) } fn Event(&self, _handler: &Option<EventHandler<i64>>) -> Result<EventRegistrationToken> { Ok(EventRegistrationToken { Value: self.0 }) } fn RemoveEvent(&mut self, token: &EventRegistrationToken) -> Result<()> { self.0 = token.Value; Ok(()) } } #[test] fn test() -> Result<()> { let names: IMethodNames = MethodNames(0).into(); names.Method()?; assert!(names.Property()? == 0); names.SetProperty(123)?; assert!(names.Property()? == 123); assert!(names.Event(None)? == EventRegistrationToken { Value: 123 }); names.RemoveEvent(EventRegistrationToken { Value: 456 })?; assert!(names.Property()? == 456); Ok(()) }
use serde::Serialize; use serde_json::Result; #[derive(Serialize)] pub struct Service { pub id: String, pub title: String, pub subtitle: String, } impl Service { pub fn serialize_to_json(self) -> Result<String> { serde_json::to_string(&self) } }
#![crate_name="albino-run"] #![crate_type="bin"] #![feature(phase)] #![unstable] #[phase(plugin, link)] extern crate log; extern crate getopts; extern crate whitebase; extern crate albino; use getopts::Matches; use std::os; use std::io::{IoError, MemReader, MemWriter}; use whitebase::machine; use whitebase::syntax::{Compiler, Assembly, Brainfuck, DT, Ook, Whitespace}; use albino::command::{RunCommand, RunExecutable}; use albino::util; use albino::util::Target; fn run<B: Buffer, C: Compiler>(buffer: &mut B, syntax: C) { let mut writer = MemWriter::new(); match syntax.compile(buffer, &mut writer) { Err(e) => { println!("{}", e); os::set_exit_status(1); } _ => { let mut reader = MemReader::new(writer.unwrap()); let mut machine = machine::with_stdio(); match machine.run(&mut reader) { Err(e) => { println!("{}", e); os::set_exit_status(2); } _ => (), } }, } } struct CommandBody; impl RunExecutable for CommandBody { fn handle_error(&self, e: IoError) { println!("{}", e); os::set_exit_status(1); } fn exec<B: Buffer>(&self, _: &Matches, buffer: &mut B, target: Option<Target>) { match target { Some(util::Assembly) => run(buffer, Assembly::new()), Some(util::Brainfuck) => run(buffer, Brainfuck::new()), Some(util::DT) => run(buffer, DT::new()), Some(util::Ook) => run(buffer, Ook::new()), Some(util::Whitespace) => run(buffer, Whitespace::new()), None => { println!("syntax should be \"asm\", \"bf\", \"dt\", \"ook\" or \"ws\" (default: ws)"); os::set_exit_status(1); }, } } } fn main() { debug!("executing; cmd=albino-run; args={}", os::args()); let mut opts = vec!(); let cmd = RunCommand::new("run", "[-s syntax] [file]", &mut opts, CommandBody); cmd.exec(); }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qplaintextedit.h // dst-file: /src/widgets/qplaintextedit.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::super::gui::qabstracttextdocumentlayout::*; // 771 use std::ops::Deref; use super::super::gui::qpainter::*; // 771 use super::super::core::qpoint::*; // 771 use super::super::gui::qtextobject::*; // 771 use super::super::core::qrect::*; // 771 use super::super::core::qobjectdefs::*; // 771 use super::super::gui::qtextdocument::*; // 771 use super::super::core::qsize::*; // 771 use super::qabstractscrollarea::*; // 773 use super::qmenu::*; // 773 use super::super::core::qstring::*; // 771 use super::super::core::qurl::*; // 771 use super::super::core::qvariant::*; // 771 use super::super::gui::qtextcursor::*; // 771 use super::super::gui::qtextformat::*; // 771 use super::super::gui::qpagedpaintdevice::*; // 771 use super::qwidget::*; // 773 use super::super::core::qregexp::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QPlainTextDocumentLayout_Class_Size() -> c_int; // proto: void QPlainTextDocumentLayout::requestUpdate(); fn C_ZN24QPlainTextDocumentLayout13requestUpdateEv(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextDocumentLayout::setCursorWidth(int width); fn C_ZN24QPlainTextDocumentLayout14setCursorWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: QRectF QPlainTextDocumentLayout::frameBoundingRect(QTextFrame * ); fn C_ZNK24QPlainTextDocumentLayout17frameBoundingRectEP10QTextFrame(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: int QPlainTextDocumentLayout::pageCount(); fn C_ZNK24QPlainTextDocumentLayout9pageCountEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: const QMetaObject * QPlainTextDocumentLayout::metaObject(); fn C_ZNK24QPlainTextDocumentLayout10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPlainTextDocumentLayout::ensureBlockLayout(const QTextBlock & block); fn C_ZNK24QPlainTextDocumentLayout17ensureBlockLayoutERK10QTextBlock(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextDocumentLayout::~QPlainTextDocumentLayout(); fn C_ZN24QPlainTextDocumentLayoutD2Ev(qthis: u64 /* *mut c_void*/); // proto: QRectF QPlainTextDocumentLayout::blockBoundingRect(const QTextBlock & block); fn C_ZNK24QPlainTextDocumentLayout17blockBoundingRectERK10QTextBlock(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: int QPlainTextDocumentLayout::cursorWidth(); fn C_ZNK24QPlainTextDocumentLayout11cursorWidthEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QPlainTextDocumentLayout::QPlainTextDocumentLayout(QTextDocument * document); fn C_ZN24QPlainTextDocumentLayoutC2EP13QTextDocument(arg0: *mut c_void) -> u64; // proto: QSizeF QPlainTextDocumentLayout::documentSize(); fn C_ZNK24QPlainTextDocumentLayout12documentSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; fn QPlainTextEdit_Class_Size() -> c_int; // proto: QMenu * QPlainTextEdit::createStandardContextMenu(const QPoint & position); fn C_ZN14QPlainTextEdit25createStandardContextMenuERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QPlainTextEdit::ensureCursorVisible(); fn C_ZN14QPlainTextEdit19ensureCursorVisibleEv(qthis: u64 /* *mut c_void*/); // proto: QTextDocument * QPlainTextEdit::document(); fn C_ZNK14QPlainTextEdit8documentEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QRect QPlainTextEdit::cursorRect(); fn C_ZNK14QPlainTextEdit10cursorRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPlainTextEdit::setTabChangesFocus(bool b); fn C_ZN14QPlainTextEdit18setTabChangesFocusEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QString QPlainTextEdit::toPlainText(); fn C_ZNK14QPlainTextEdit11toPlainTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QVariant QPlainTextEdit::loadResource(int type, const QUrl & name); fn C_ZN14QPlainTextEdit12loadResourceEiRK4QUrl(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void) -> *mut c_void; // proto: int QPlainTextEdit::tabStopWidth(); fn C_ZNK14QPlainTextEdit12tabStopWidthEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: bool QPlainTextEdit::isReadOnly(); fn C_ZNK14QPlainTextEdit10isReadOnlyEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::setReadOnly(bool ro); fn C_ZN14QPlainTextEdit11setReadOnlyEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QTextCursor QPlainTextEdit::textCursor(); fn C_ZNK14QPlainTextEdit10textCursorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPlainTextEdit::setCenterOnScroll(bool enabled); fn C_ZN14QPlainTextEdit17setCenterOnScrollEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QString QPlainTextEdit::placeholderText(); fn C_ZNK14QPlainTextEdit15placeholderTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QPlainTextEdit::blockCount(); fn C_ZNK14QPlainTextEdit10blockCountEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QPlainTextEdit::setCurrentCharFormat(const QTextCharFormat & format); fn C_ZN14QPlainTextEdit20setCurrentCharFormatERK15QTextCharFormat(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::setDocument(QTextDocument * document); fn C_ZN14QPlainTextEdit11setDocumentEP13QTextDocument(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::print(QPagedPaintDevice * printer); fn C_ZNK14QPlainTextEdit5printEP17QPagedPaintDevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::setTabStopWidth(int width); fn C_ZN14QPlainTextEdit15setTabStopWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: bool QPlainTextEdit::backgroundVisible(); fn C_ZNK14QPlainTextEdit17backgroundVisibleEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::redo(); fn C_ZN14QPlainTextEdit4redoEv(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextEdit::QPlainTextEdit(const QString & text, QWidget * parent); fn C_ZN14QPlainTextEditC2ERK7QStringP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64; // proto: void QPlainTextEdit::setOverwriteMode(bool overwrite); fn C_ZN14QPlainTextEdit16setOverwriteModeEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QPlainTextEdit::tabChangesFocus(); fn C_ZNK14QPlainTextEdit15tabChangesFocusEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::copy(); fn C_ZN14QPlainTextEdit4copyEv(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextEdit::mergeCurrentCharFormat(const QTextCharFormat & modifier); fn C_ZN14QPlainTextEdit22mergeCurrentCharFormatERK15QTextCharFormat(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: int QPlainTextEdit::maximumBlockCount(); fn C_ZNK14QPlainTextEdit17maximumBlockCountEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QPlainTextEdit::insertPlainText(const QString & text); fn C_ZN14QPlainTextEdit15insertPlainTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::setTextCursor(const QTextCursor & cursor); fn C_ZN14QPlainTextEdit13setTextCursorERK11QTextCursor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::paste(); fn C_ZN14QPlainTextEdit5pasteEv(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextEdit::zoomIn(int range); fn C_ZN14QPlainTextEdit6zoomInEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QPlainTextEdit::setMaximumBlockCount(int maximum); fn C_ZN14QPlainTextEdit20setMaximumBlockCountEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: QTextCharFormat QPlainTextEdit::currentCharFormat(); fn C_ZNK14QPlainTextEdit17currentCharFormatEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPlainTextEdit::setCursorWidth(int width); fn C_ZN14QPlainTextEdit14setCursorWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: QString QPlainTextEdit::documentTitle(); fn C_ZNK14QPlainTextEdit13documentTitleEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPlainTextEdit::selectAll(); fn C_ZN14QPlainTextEdit9selectAllEv(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextEdit::setPlainText(const QString & text); fn C_ZN14QPlainTextEdit12setPlainTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::setBackgroundVisible(bool visible); fn C_ZN14QPlainTextEdit20setBackgroundVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QPlainTextEdit::setUndoRedoEnabled(bool enable); fn C_ZN14QPlainTextEdit18setUndoRedoEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QPlainTextEdit::overwriteMode(); fn C_ZNK14QPlainTextEdit13overwriteModeEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::centerCursor(); fn C_ZN14QPlainTextEdit12centerCursorEv(qthis: u64 /* *mut c_void*/); // proto: const QMetaObject * QPlainTextEdit::metaObject(); fn C_ZNK14QPlainTextEdit10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QMenu * QPlainTextEdit::createStandardContextMenu(); fn C_ZN14QPlainTextEdit25createStandardContextMenuEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QPlainTextEdit::setDocumentTitle(const QString & title); fn C_ZN14QPlainTextEdit16setDocumentTitleERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::~QPlainTextEdit(); fn C_ZN14QPlainTextEditD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextEdit::clear(); fn C_ZN14QPlainTextEdit5clearEv(qthis: u64 /* *mut c_void*/); // proto: QString QPlainTextEdit::anchorAt(const QPoint & pos); fn C_ZNK14QPlainTextEdit8anchorAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: bool QPlainTextEdit::canPaste(); fn C_ZNK14QPlainTextEdit8canPasteEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::QPlainTextEdit(QWidget * parent); fn C_ZN14QPlainTextEditC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: void QPlainTextEdit::cut(); fn C_ZN14QPlainTextEdit3cutEv(qthis: u64 /* *mut c_void*/); // proto: void QPlainTextEdit::appendHtml(const QString & html); fn C_ZN14QPlainTextEdit10appendHtmlERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: bool QPlainTextEdit::isUndoRedoEnabled(); fn C_ZNK14QPlainTextEdit17isUndoRedoEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::zoomOut(int range); fn C_ZN14QPlainTextEdit7zoomOutEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QPlainTextEdit::setPlaceholderText(const QString & placeholderText); fn C_ZN14QPlainTextEdit18setPlaceholderTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QPlainTextEdit::undo(); fn C_ZN14QPlainTextEdit4undoEv(qthis: u64 /* *mut c_void*/); // proto: QTextCursor QPlainTextEdit::cursorForPosition(const QPoint & pos); fn C_ZNK14QPlainTextEdit17cursorForPositionERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: bool QPlainTextEdit::centerOnScroll(); fn C_ZNK14QPlainTextEdit14centerOnScrollEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QPlainTextEdit::appendPlainText(const QString & text); fn C_ZN14QPlainTextEdit15appendPlainTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: int QPlainTextEdit::cursorWidth(); fn C_ZNK14QPlainTextEdit11cursorWidthEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: QRect QPlainTextEdit::cursorRect(const QTextCursor & cursor); fn C_ZNK14QPlainTextEdit10cursorRectERK11QTextCursor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit17blockCountChangedEi(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13undoAvailableEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit16selectionChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13redoAvailableEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit19modificationChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13updateRequestERK5QRecti(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit11textChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit21cursorPositionChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13copyAvailableEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QPlainTextDocumentLayout)=1 #[derive(Default)] pub struct QPlainTextDocumentLayout { qbase: QAbstractTextDocumentLayout, pub qclsinst: u64 /* *mut c_void*/, } // class sizeof(QPlainTextEdit)=1 #[derive(Default)] pub struct QPlainTextEdit { qbase: QAbstractScrollArea, pub qclsinst: u64 /* *mut c_void*/, pub _cursorPositionChanged: QPlainTextEdit_cursorPositionChanged_signal, pub _modificationChanged: QPlainTextEdit_modificationChanged_signal, pub _redoAvailable: QPlainTextEdit_redoAvailable_signal, pub _selectionChanged: QPlainTextEdit_selectionChanged_signal, pub _updateRequest: QPlainTextEdit_updateRequest_signal, pub _blockCountChanged: QPlainTextEdit_blockCountChanged_signal, pub _undoAvailable: QPlainTextEdit_undoAvailable_signal, pub _textChanged: QPlainTextEdit_textChanged_signal, pub _copyAvailable: QPlainTextEdit_copyAvailable_signal, } impl /*struct*/ QPlainTextDocumentLayout { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QPlainTextDocumentLayout { return QPlainTextDocumentLayout{qbase: QAbstractTextDocumentLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QPlainTextDocumentLayout { type Target = QAbstractTextDocumentLayout; fn deref(&self) -> &QAbstractTextDocumentLayout { return & self.qbase; } } impl AsRef<QAbstractTextDocumentLayout> for QPlainTextDocumentLayout { fn as_ref(& self) -> & QAbstractTextDocumentLayout { return & self.qbase; } } // proto: void QPlainTextDocumentLayout::requestUpdate(); impl /*struct*/ QPlainTextDocumentLayout { pub fn requestUpdate<RetType, T: QPlainTextDocumentLayout_requestUpdate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.requestUpdate(self); // return 1; } } pub trait QPlainTextDocumentLayout_requestUpdate<RetType> { fn requestUpdate(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: void QPlainTextDocumentLayout::requestUpdate(); impl<'a> /*trait*/ QPlainTextDocumentLayout_requestUpdate<()> for () { fn requestUpdate(self , rsthis: & QPlainTextDocumentLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN24QPlainTextDocumentLayout13requestUpdateEv()}; unsafe {C_ZN24QPlainTextDocumentLayout13requestUpdateEv(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextDocumentLayout::setCursorWidth(int width); impl /*struct*/ QPlainTextDocumentLayout { pub fn setCursorWidth<RetType, T: QPlainTextDocumentLayout_setCursorWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCursorWidth(self); // return 1; } } pub trait QPlainTextDocumentLayout_setCursorWidth<RetType> { fn setCursorWidth(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: void QPlainTextDocumentLayout::setCursorWidth(int width); impl<'a> /*trait*/ QPlainTextDocumentLayout_setCursorWidth<()> for (i32) { fn setCursorWidth(self , rsthis: & QPlainTextDocumentLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN24QPlainTextDocumentLayout14setCursorWidthEi()}; let arg0 = self as c_int; unsafe {C_ZN24QPlainTextDocumentLayout14setCursorWidthEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QRectF QPlainTextDocumentLayout::frameBoundingRect(QTextFrame * ); impl /*struct*/ QPlainTextDocumentLayout { pub fn frameBoundingRect<RetType, T: QPlainTextDocumentLayout_frameBoundingRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.frameBoundingRect(self); // return 1; } } pub trait QPlainTextDocumentLayout_frameBoundingRect<RetType> { fn frameBoundingRect(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: QRectF QPlainTextDocumentLayout::frameBoundingRect(QTextFrame * ); impl<'a> /*trait*/ QPlainTextDocumentLayout_frameBoundingRect<QRectF> for (&'a QTextFrame) { fn frameBoundingRect(self , rsthis: & QPlainTextDocumentLayout) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout17frameBoundingRectEP10QTextFrame()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK24QPlainTextDocumentLayout17frameBoundingRectEP10QTextFrame(rsthis.qclsinst, arg0)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QPlainTextDocumentLayout::pageCount(); impl /*struct*/ QPlainTextDocumentLayout { pub fn pageCount<RetType, T: QPlainTextDocumentLayout_pageCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.pageCount(self); // return 1; } } pub trait QPlainTextDocumentLayout_pageCount<RetType> { fn pageCount(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: int QPlainTextDocumentLayout::pageCount(); impl<'a> /*trait*/ QPlainTextDocumentLayout_pageCount<i32> for () { fn pageCount(self , rsthis: & QPlainTextDocumentLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout9pageCountEv()}; let mut ret = unsafe {C_ZNK24QPlainTextDocumentLayout9pageCountEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: const QMetaObject * QPlainTextDocumentLayout::metaObject(); impl /*struct*/ QPlainTextDocumentLayout { pub fn metaObject<RetType, T: QPlainTextDocumentLayout_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QPlainTextDocumentLayout_metaObject<RetType> { fn metaObject(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: const QMetaObject * QPlainTextDocumentLayout::metaObject(); impl<'a> /*trait*/ QPlainTextDocumentLayout_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QPlainTextDocumentLayout) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout10metaObjectEv()}; let mut ret = unsafe {C_ZNK24QPlainTextDocumentLayout10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextDocumentLayout::ensureBlockLayout(const QTextBlock & block); impl /*struct*/ QPlainTextDocumentLayout { pub fn ensureBlockLayout<RetType, T: QPlainTextDocumentLayout_ensureBlockLayout<RetType>>(& self, overload_args: T) -> RetType { return overload_args.ensureBlockLayout(self); // return 1; } } pub trait QPlainTextDocumentLayout_ensureBlockLayout<RetType> { fn ensureBlockLayout(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: void QPlainTextDocumentLayout::ensureBlockLayout(const QTextBlock & block); impl<'a> /*trait*/ QPlainTextDocumentLayout_ensureBlockLayout<()> for (&'a QTextBlock) { fn ensureBlockLayout(self , rsthis: & QPlainTextDocumentLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout17ensureBlockLayoutERK10QTextBlock()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZNK24QPlainTextDocumentLayout17ensureBlockLayoutERK10QTextBlock(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextDocumentLayout::~QPlainTextDocumentLayout(); impl /*struct*/ QPlainTextDocumentLayout { pub fn free<RetType, T: QPlainTextDocumentLayout_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QPlainTextDocumentLayout_free<RetType> { fn free(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: void QPlainTextDocumentLayout::~QPlainTextDocumentLayout(); impl<'a> /*trait*/ QPlainTextDocumentLayout_free<()> for () { fn free(self , rsthis: & QPlainTextDocumentLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN24QPlainTextDocumentLayoutD2Ev()}; unsafe {C_ZN24QPlainTextDocumentLayoutD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QRectF QPlainTextDocumentLayout::blockBoundingRect(const QTextBlock & block); impl /*struct*/ QPlainTextDocumentLayout { pub fn blockBoundingRect<RetType, T: QPlainTextDocumentLayout_blockBoundingRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.blockBoundingRect(self); // return 1; } } pub trait QPlainTextDocumentLayout_blockBoundingRect<RetType> { fn blockBoundingRect(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: QRectF QPlainTextDocumentLayout::blockBoundingRect(const QTextBlock & block); impl<'a> /*trait*/ QPlainTextDocumentLayout_blockBoundingRect<QRectF> for (&'a QTextBlock) { fn blockBoundingRect(self , rsthis: & QPlainTextDocumentLayout) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout17blockBoundingRectERK10QTextBlock()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK24QPlainTextDocumentLayout17blockBoundingRectERK10QTextBlock(rsthis.qclsinst, arg0)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QPlainTextDocumentLayout::cursorWidth(); impl /*struct*/ QPlainTextDocumentLayout { pub fn cursorWidth<RetType, T: QPlainTextDocumentLayout_cursorWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorWidth(self); // return 1; } } pub trait QPlainTextDocumentLayout_cursorWidth<RetType> { fn cursorWidth(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: int QPlainTextDocumentLayout::cursorWidth(); impl<'a> /*trait*/ QPlainTextDocumentLayout_cursorWidth<i32> for () { fn cursorWidth(self , rsthis: & QPlainTextDocumentLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout11cursorWidthEv()}; let mut ret = unsafe {C_ZNK24QPlainTextDocumentLayout11cursorWidthEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QPlainTextDocumentLayout::QPlainTextDocumentLayout(QTextDocument * document); impl /*struct*/ QPlainTextDocumentLayout { pub fn new<T: QPlainTextDocumentLayout_new>(value: T) -> QPlainTextDocumentLayout { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QPlainTextDocumentLayout_new { fn new(self) -> QPlainTextDocumentLayout; } // proto: void QPlainTextDocumentLayout::QPlainTextDocumentLayout(QTextDocument * document); impl<'a> /*trait*/ QPlainTextDocumentLayout_new for (&'a QTextDocument) { fn new(self) -> QPlainTextDocumentLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN24QPlainTextDocumentLayoutC2EP13QTextDocument()}; let ctysz: c_int = unsafe{QPlainTextDocumentLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN24QPlainTextDocumentLayoutC2EP13QTextDocument(arg0)}; let rsthis = QPlainTextDocumentLayout{qbase: QAbstractTextDocumentLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QSizeF QPlainTextDocumentLayout::documentSize(); impl /*struct*/ QPlainTextDocumentLayout { pub fn documentSize<RetType, T: QPlainTextDocumentLayout_documentSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.documentSize(self); // return 1; } } pub trait QPlainTextDocumentLayout_documentSize<RetType> { fn documentSize(self , rsthis: & QPlainTextDocumentLayout) -> RetType; } // proto: QSizeF QPlainTextDocumentLayout::documentSize(); impl<'a> /*trait*/ QPlainTextDocumentLayout_documentSize<QSizeF> for () { fn documentSize(self , rsthis: & QPlainTextDocumentLayout) -> QSizeF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK24QPlainTextDocumentLayout12documentSizeEv()}; let mut ret = unsafe {C_ZNK24QPlainTextDocumentLayout12documentSizeEv(rsthis.qclsinst)}; let mut ret1 = QSizeF::inheritFrom(ret as u64); return ret1; // return 1; } } impl /*struct*/ QPlainTextEdit { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QPlainTextEdit { return QPlainTextEdit{qbase: QAbstractScrollArea::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QPlainTextEdit { type Target = QAbstractScrollArea; fn deref(&self) -> &QAbstractScrollArea { return & self.qbase; } } impl AsRef<QAbstractScrollArea> for QPlainTextEdit { fn as_ref(& self) -> & QAbstractScrollArea { return & self.qbase; } } // proto: QMenu * QPlainTextEdit::createStandardContextMenu(const QPoint & position); impl /*struct*/ QPlainTextEdit { pub fn createStandardContextMenu<RetType, T: QPlainTextEdit_createStandardContextMenu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.createStandardContextMenu(self); // return 1; } } pub trait QPlainTextEdit_createStandardContextMenu<RetType> { fn createStandardContextMenu(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QMenu * QPlainTextEdit::createStandardContextMenu(const QPoint & position); impl<'a> /*trait*/ QPlainTextEdit_createStandardContextMenu<QMenu> for (&'a QPoint) { fn createStandardContextMenu(self , rsthis: & QPlainTextEdit) -> QMenu { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit25createStandardContextMenuERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN14QPlainTextEdit25createStandardContextMenuERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QMenu::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextEdit::ensureCursorVisible(); impl /*struct*/ QPlainTextEdit { pub fn ensureCursorVisible<RetType, T: QPlainTextEdit_ensureCursorVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.ensureCursorVisible(self); // return 1; } } pub trait QPlainTextEdit_ensureCursorVisible<RetType> { fn ensureCursorVisible(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::ensureCursorVisible(); impl<'a> /*trait*/ QPlainTextEdit_ensureCursorVisible<()> for () { fn ensureCursorVisible(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit19ensureCursorVisibleEv()}; unsafe {C_ZN14QPlainTextEdit19ensureCursorVisibleEv(rsthis.qclsinst)}; // return 1; } } // proto: QTextDocument * QPlainTextEdit::document(); impl /*struct*/ QPlainTextEdit { pub fn document<RetType, T: QPlainTextEdit_document<RetType>>(& self, overload_args: T) -> RetType { return overload_args.document(self); // return 1; } } pub trait QPlainTextEdit_document<RetType> { fn document(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QTextDocument * QPlainTextEdit::document(); impl<'a> /*trait*/ QPlainTextEdit_document<QTextDocument> for () { fn document(self , rsthis: & QPlainTextEdit) -> QTextDocument { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit8documentEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit8documentEv(rsthis.qclsinst)}; let mut ret1 = QTextDocument::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QRect QPlainTextEdit::cursorRect(); impl /*struct*/ QPlainTextEdit { pub fn cursorRect<RetType, T: QPlainTextEdit_cursorRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorRect(self); // return 1; } } pub trait QPlainTextEdit_cursorRect<RetType> { fn cursorRect(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QRect QPlainTextEdit::cursorRect(); impl<'a> /*trait*/ QPlainTextEdit_cursorRect<QRect> for () { fn cursorRect(self , rsthis: & QPlainTextEdit) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit10cursorRectEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit10cursorRectEv(rsthis.qclsinst)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextEdit::setTabChangesFocus(bool b); impl /*struct*/ QPlainTextEdit { pub fn setTabChangesFocus<RetType, T: QPlainTextEdit_setTabChangesFocus<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setTabChangesFocus(self); // return 1; } } pub trait QPlainTextEdit_setTabChangesFocus<RetType> { fn setTabChangesFocus(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setTabChangesFocus(bool b); impl<'a> /*trait*/ QPlainTextEdit_setTabChangesFocus<()> for (i8) { fn setTabChangesFocus(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit18setTabChangesFocusEb()}; let arg0 = self as c_char; unsafe {C_ZN14QPlainTextEdit18setTabChangesFocusEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QPlainTextEdit::toPlainText(); impl /*struct*/ QPlainTextEdit { pub fn toPlainText<RetType, T: QPlainTextEdit_toPlainText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toPlainText(self); // return 1; } } pub trait QPlainTextEdit_toPlainText<RetType> { fn toPlainText(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QString QPlainTextEdit::toPlainText(); impl<'a> /*trait*/ QPlainTextEdit_toPlainText<QString> for () { fn toPlainText(self , rsthis: & QPlainTextEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit11toPlainTextEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit11toPlainTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QVariant QPlainTextEdit::loadResource(int type, const QUrl & name); impl /*struct*/ QPlainTextEdit { pub fn loadResource<RetType, T: QPlainTextEdit_loadResource<RetType>>(& self, overload_args: T) -> RetType { return overload_args.loadResource(self); // return 1; } } pub trait QPlainTextEdit_loadResource<RetType> { fn loadResource(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QVariant QPlainTextEdit::loadResource(int type, const QUrl & name); impl<'a> /*trait*/ QPlainTextEdit_loadResource<QVariant> for (i32, &'a QUrl) { fn loadResource(self , rsthis: & QPlainTextEdit) -> QVariant { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit12loadResourceEiRK4QUrl()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN14QPlainTextEdit12loadResourceEiRK4QUrl(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QVariant::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QPlainTextEdit::tabStopWidth(); impl /*struct*/ QPlainTextEdit { pub fn tabStopWidth<RetType, T: QPlainTextEdit_tabStopWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.tabStopWidth(self); // return 1; } } pub trait QPlainTextEdit_tabStopWidth<RetType> { fn tabStopWidth(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: int QPlainTextEdit::tabStopWidth(); impl<'a> /*trait*/ QPlainTextEdit_tabStopWidth<i32> for () { fn tabStopWidth(self , rsthis: & QPlainTextEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit12tabStopWidthEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit12tabStopWidthEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: bool QPlainTextEdit::isReadOnly(); impl /*struct*/ QPlainTextEdit { pub fn isReadOnly<RetType, T: QPlainTextEdit_isReadOnly<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isReadOnly(self); // return 1; } } pub trait QPlainTextEdit_isReadOnly<RetType> { fn isReadOnly(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::isReadOnly(); impl<'a> /*trait*/ QPlainTextEdit_isReadOnly<i8> for () { fn isReadOnly(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit10isReadOnlyEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit10isReadOnlyEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::setReadOnly(bool ro); impl /*struct*/ QPlainTextEdit { pub fn setReadOnly<RetType, T: QPlainTextEdit_setReadOnly<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setReadOnly(self); // return 1; } } pub trait QPlainTextEdit_setReadOnly<RetType> { fn setReadOnly(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setReadOnly(bool ro); impl<'a> /*trait*/ QPlainTextEdit_setReadOnly<()> for (i8) { fn setReadOnly(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit11setReadOnlyEb()}; let arg0 = self as c_char; unsafe {C_ZN14QPlainTextEdit11setReadOnlyEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QTextCursor QPlainTextEdit::textCursor(); impl /*struct*/ QPlainTextEdit { pub fn textCursor<RetType, T: QPlainTextEdit_textCursor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.textCursor(self); // return 1; } } pub trait QPlainTextEdit_textCursor<RetType> { fn textCursor(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QTextCursor QPlainTextEdit::textCursor(); impl<'a> /*trait*/ QPlainTextEdit_textCursor<QTextCursor> for () { fn textCursor(self , rsthis: & QPlainTextEdit) -> QTextCursor { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit10textCursorEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit10textCursorEv(rsthis.qclsinst)}; let mut ret1 = QTextCursor::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextEdit::setCenterOnScroll(bool enabled); impl /*struct*/ QPlainTextEdit { pub fn setCenterOnScroll<RetType, T: QPlainTextEdit_setCenterOnScroll<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCenterOnScroll(self); // return 1; } } pub trait QPlainTextEdit_setCenterOnScroll<RetType> { fn setCenterOnScroll(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setCenterOnScroll(bool enabled); impl<'a> /*trait*/ QPlainTextEdit_setCenterOnScroll<()> for (i8) { fn setCenterOnScroll(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit17setCenterOnScrollEb()}; let arg0 = self as c_char; unsafe {C_ZN14QPlainTextEdit17setCenterOnScrollEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QPlainTextEdit::placeholderText(); impl /*struct*/ QPlainTextEdit { pub fn placeholderText<RetType, T: QPlainTextEdit_placeholderText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.placeholderText(self); // return 1; } } pub trait QPlainTextEdit_placeholderText<RetType> { fn placeholderText(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QString QPlainTextEdit::placeholderText(); impl<'a> /*trait*/ QPlainTextEdit_placeholderText<QString> for () { fn placeholderText(self , rsthis: & QPlainTextEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit15placeholderTextEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit15placeholderTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QPlainTextEdit::blockCount(); impl /*struct*/ QPlainTextEdit { pub fn blockCount<RetType, T: QPlainTextEdit_blockCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.blockCount(self); // return 1; } } pub trait QPlainTextEdit_blockCount<RetType> { fn blockCount(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: int QPlainTextEdit::blockCount(); impl<'a> /*trait*/ QPlainTextEdit_blockCount<i32> for () { fn blockCount(self , rsthis: & QPlainTextEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit10blockCountEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit10blockCountEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QPlainTextEdit::setCurrentCharFormat(const QTextCharFormat & format); impl /*struct*/ QPlainTextEdit { pub fn setCurrentCharFormat<RetType, T: QPlainTextEdit_setCurrentCharFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCurrentCharFormat(self); // return 1; } } pub trait QPlainTextEdit_setCurrentCharFormat<RetType> { fn setCurrentCharFormat(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setCurrentCharFormat(const QTextCharFormat & format); impl<'a> /*trait*/ QPlainTextEdit_setCurrentCharFormat<()> for (&'a QTextCharFormat) { fn setCurrentCharFormat(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit20setCurrentCharFormatERK15QTextCharFormat()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit20setCurrentCharFormatERK15QTextCharFormat(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setDocument(QTextDocument * document); impl /*struct*/ QPlainTextEdit { pub fn setDocument<RetType, T: QPlainTextEdit_setDocument<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDocument(self); // return 1; } } pub trait QPlainTextEdit_setDocument<RetType> { fn setDocument(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setDocument(QTextDocument * document); impl<'a> /*trait*/ QPlainTextEdit_setDocument<()> for (&'a QTextDocument) { fn setDocument(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit11setDocumentEP13QTextDocument()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit11setDocumentEP13QTextDocument(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::print(QPagedPaintDevice * printer); impl /*struct*/ QPlainTextEdit { pub fn print<RetType, T: QPlainTextEdit_print<RetType>>(& self, overload_args: T) -> RetType { return overload_args.print(self); // return 1; } } pub trait QPlainTextEdit_print<RetType> { fn print(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::print(QPagedPaintDevice * printer); impl<'a> /*trait*/ QPlainTextEdit_print<()> for (&'a QPagedPaintDevice) { fn print(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit5printEP17QPagedPaintDevice()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZNK14QPlainTextEdit5printEP17QPagedPaintDevice(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setTabStopWidth(int width); impl /*struct*/ QPlainTextEdit { pub fn setTabStopWidth<RetType, T: QPlainTextEdit_setTabStopWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setTabStopWidth(self); // return 1; } } pub trait QPlainTextEdit_setTabStopWidth<RetType> { fn setTabStopWidth(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setTabStopWidth(int width); impl<'a> /*trait*/ QPlainTextEdit_setTabStopWidth<()> for (i32) { fn setTabStopWidth(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit15setTabStopWidthEi()}; let arg0 = self as c_int; unsafe {C_ZN14QPlainTextEdit15setTabStopWidthEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QPlainTextEdit::backgroundVisible(); impl /*struct*/ QPlainTextEdit { pub fn backgroundVisible<RetType, T: QPlainTextEdit_backgroundVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.backgroundVisible(self); // return 1; } } pub trait QPlainTextEdit_backgroundVisible<RetType> { fn backgroundVisible(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::backgroundVisible(); impl<'a> /*trait*/ QPlainTextEdit_backgroundVisible<i8> for () { fn backgroundVisible(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit17backgroundVisibleEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit17backgroundVisibleEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::redo(); impl /*struct*/ QPlainTextEdit { pub fn redo<RetType, T: QPlainTextEdit_redo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.redo(self); // return 1; } } pub trait QPlainTextEdit_redo<RetType> { fn redo(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::redo(); impl<'a> /*trait*/ QPlainTextEdit_redo<()> for () { fn redo(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit4redoEv()}; unsafe {C_ZN14QPlainTextEdit4redoEv(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextEdit::QPlainTextEdit(const QString & text, QWidget * parent); impl /*struct*/ QPlainTextEdit { pub fn new<T: QPlainTextEdit_new>(value: T) -> QPlainTextEdit { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QPlainTextEdit_new { fn new(self) -> QPlainTextEdit; } // proto: void QPlainTextEdit::QPlainTextEdit(const QString & text, QWidget * parent); impl<'a> /*trait*/ QPlainTextEdit_new for (&'a QString, Option<&'a QWidget>) { fn new(self) -> QPlainTextEdit { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEditC2ERK7QStringP7QWidget()}; let ctysz: c_int = unsafe{QPlainTextEdit_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN14QPlainTextEditC2ERK7QStringP7QWidget(arg0, arg1)}; let rsthis = QPlainTextEdit{qbase: QAbstractScrollArea::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QPlainTextEdit::setOverwriteMode(bool overwrite); impl /*struct*/ QPlainTextEdit { pub fn setOverwriteMode<RetType, T: QPlainTextEdit_setOverwriteMode<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setOverwriteMode(self); // return 1; } } pub trait QPlainTextEdit_setOverwriteMode<RetType> { fn setOverwriteMode(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setOverwriteMode(bool overwrite); impl<'a> /*trait*/ QPlainTextEdit_setOverwriteMode<()> for (i8) { fn setOverwriteMode(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit16setOverwriteModeEb()}; let arg0 = self as c_char; unsafe {C_ZN14QPlainTextEdit16setOverwriteModeEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QPlainTextEdit::tabChangesFocus(); impl /*struct*/ QPlainTextEdit { pub fn tabChangesFocus<RetType, T: QPlainTextEdit_tabChangesFocus<RetType>>(& self, overload_args: T) -> RetType { return overload_args.tabChangesFocus(self); // return 1; } } pub trait QPlainTextEdit_tabChangesFocus<RetType> { fn tabChangesFocus(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::tabChangesFocus(); impl<'a> /*trait*/ QPlainTextEdit_tabChangesFocus<i8> for () { fn tabChangesFocus(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit15tabChangesFocusEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit15tabChangesFocusEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::copy(); impl /*struct*/ QPlainTextEdit { pub fn copy<RetType, T: QPlainTextEdit_copy<RetType>>(& self, overload_args: T) -> RetType { return overload_args.copy(self); // return 1; } } pub trait QPlainTextEdit_copy<RetType> { fn copy(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::copy(); impl<'a> /*trait*/ QPlainTextEdit_copy<()> for () { fn copy(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit4copyEv()}; unsafe {C_ZN14QPlainTextEdit4copyEv(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextEdit::mergeCurrentCharFormat(const QTextCharFormat & modifier); impl /*struct*/ QPlainTextEdit { pub fn mergeCurrentCharFormat<RetType, T: QPlainTextEdit_mergeCurrentCharFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.mergeCurrentCharFormat(self); // return 1; } } pub trait QPlainTextEdit_mergeCurrentCharFormat<RetType> { fn mergeCurrentCharFormat(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::mergeCurrentCharFormat(const QTextCharFormat & modifier); impl<'a> /*trait*/ QPlainTextEdit_mergeCurrentCharFormat<()> for (&'a QTextCharFormat) { fn mergeCurrentCharFormat(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit22mergeCurrentCharFormatERK15QTextCharFormat()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit22mergeCurrentCharFormatERK15QTextCharFormat(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QPlainTextEdit::maximumBlockCount(); impl /*struct*/ QPlainTextEdit { pub fn maximumBlockCount<RetType, T: QPlainTextEdit_maximumBlockCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.maximumBlockCount(self); // return 1; } } pub trait QPlainTextEdit_maximumBlockCount<RetType> { fn maximumBlockCount(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: int QPlainTextEdit::maximumBlockCount(); impl<'a> /*trait*/ QPlainTextEdit_maximumBlockCount<i32> for () { fn maximumBlockCount(self , rsthis: & QPlainTextEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit17maximumBlockCountEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit17maximumBlockCountEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QPlainTextEdit::insertPlainText(const QString & text); impl /*struct*/ QPlainTextEdit { pub fn insertPlainText<RetType, T: QPlainTextEdit_insertPlainText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertPlainText(self); // return 1; } } pub trait QPlainTextEdit_insertPlainText<RetType> { fn insertPlainText(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::insertPlainText(const QString & text); impl<'a> /*trait*/ QPlainTextEdit_insertPlainText<()> for (&'a QString) { fn insertPlainText(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit15insertPlainTextERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit15insertPlainTextERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setTextCursor(const QTextCursor & cursor); impl /*struct*/ QPlainTextEdit { pub fn setTextCursor<RetType, T: QPlainTextEdit_setTextCursor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setTextCursor(self); // return 1; } } pub trait QPlainTextEdit_setTextCursor<RetType> { fn setTextCursor(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setTextCursor(const QTextCursor & cursor); impl<'a> /*trait*/ QPlainTextEdit_setTextCursor<()> for (&'a QTextCursor) { fn setTextCursor(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit13setTextCursorERK11QTextCursor()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit13setTextCursorERK11QTextCursor(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::paste(); impl /*struct*/ QPlainTextEdit { pub fn paste<RetType, T: QPlainTextEdit_paste<RetType>>(& self, overload_args: T) -> RetType { return overload_args.paste(self); // return 1; } } pub trait QPlainTextEdit_paste<RetType> { fn paste(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::paste(); impl<'a> /*trait*/ QPlainTextEdit_paste<()> for () { fn paste(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit5pasteEv()}; unsafe {C_ZN14QPlainTextEdit5pasteEv(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextEdit::zoomIn(int range); impl /*struct*/ QPlainTextEdit { pub fn zoomIn<RetType, T: QPlainTextEdit_zoomIn<RetType>>(& self, overload_args: T) -> RetType { return overload_args.zoomIn(self); // return 1; } } pub trait QPlainTextEdit_zoomIn<RetType> { fn zoomIn(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::zoomIn(int range); impl<'a> /*trait*/ QPlainTextEdit_zoomIn<()> for (Option<i32>) { fn zoomIn(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit6zoomInEi()}; let arg0 = (if self.is_none() {1} else {self.unwrap()}) as c_int; unsafe {C_ZN14QPlainTextEdit6zoomInEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setMaximumBlockCount(int maximum); impl /*struct*/ QPlainTextEdit { pub fn setMaximumBlockCount<RetType, T: QPlainTextEdit_setMaximumBlockCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMaximumBlockCount(self); // return 1; } } pub trait QPlainTextEdit_setMaximumBlockCount<RetType> { fn setMaximumBlockCount(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setMaximumBlockCount(int maximum); impl<'a> /*trait*/ QPlainTextEdit_setMaximumBlockCount<()> for (i32) { fn setMaximumBlockCount(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit20setMaximumBlockCountEi()}; let arg0 = self as c_int; unsafe {C_ZN14QPlainTextEdit20setMaximumBlockCountEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QTextCharFormat QPlainTextEdit::currentCharFormat(); impl /*struct*/ QPlainTextEdit { pub fn currentCharFormat<RetType, T: QPlainTextEdit_currentCharFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.currentCharFormat(self); // return 1; } } pub trait QPlainTextEdit_currentCharFormat<RetType> { fn currentCharFormat(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QTextCharFormat QPlainTextEdit::currentCharFormat(); impl<'a> /*trait*/ QPlainTextEdit_currentCharFormat<QTextCharFormat> for () { fn currentCharFormat(self , rsthis: & QPlainTextEdit) -> QTextCharFormat { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit17currentCharFormatEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit17currentCharFormatEv(rsthis.qclsinst)}; let mut ret1 = QTextCharFormat::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextEdit::setCursorWidth(int width); impl /*struct*/ QPlainTextEdit { pub fn setCursorWidth<RetType, T: QPlainTextEdit_setCursorWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCursorWidth(self); // return 1; } } pub trait QPlainTextEdit_setCursorWidth<RetType> { fn setCursorWidth(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setCursorWidth(int width); impl<'a> /*trait*/ QPlainTextEdit_setCursorWidth<()> for (i32) { fn setCursorWidth(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit14setCursorWidthEi()}; let arg0 = self as c_int; unsafe {C_ZN14QPlainTextEdit14setCursorWidthEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QPlainTextEdit::documentTitle(); impl /*struct*/ QPlainTextEdit { pub fn documentTitle<RetType, T: QPlainTextEdit_documentTitle<RetType>>(& self, overload_args: T) -> RetType { return overload_args.documentTitle(self); // return 1; } } pub trait QPlainTextEdit_documentTitle<RetType> { fn documentTitle(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QString QPlainTextEdit::documentTitle(); impl<'a> /*trait*/ QPlainTextEdit_documentTitle<QString> for () { fn documentTitle(self , rsthis: & QPlainTextEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit13documentTitleEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit13documentTitleEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextEdit::selectAll(); impl /*struct*/ QPlainTextEdit { pub fn selectAll<RetType, T: QPlainTextEdit_selectAll<RetType>>(& self, overload_args: T) -> RetType { return overload_args.selectAll(self); // return 1; } } pub trait QPlainTextEdit_selectAll<RetType> { fn selectAll(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::selectAll(); impl<'a> /*trait*/ QPlainTextEdit_selectAll<()> for () { fn selectAll(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit9selectAllEv()}; unsafe {C_ZN14QPlainTextEdit9selectAllEv(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextEdit::setPlainText(const QString & text); impl /*struct*/ QPlainTextEdit { pub fn setPlainText<RetType, T: QPlainTextEdit_setPlainText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setPlainText(self); // return 1; } } pub trait QPlainTextEdit_setPlainText<RetType> { fn setPlainText(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setPlainText(const QString & text); impl<'a> /*trait*/ QPlainTextEdit_setPlainText<()> for (&'a QString) { fn setPlainText(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit12setPlainTextERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit12setPlainTextERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setBackgroundVisible(bool visible); impl /*struct*/ QPlainTextEdit { pub fn setBackgroundVisible<RetType, T: QPlainTextEdit_setBackgroundVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setBackgroundVisible(self); // return 1; } } pub trait QPlainTextEdit_setBackgroundVisible<RetType> { fn setBackgroundVisible(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setBackgroundVisible(bool visible); impl<'a> /*trait*/ QPlainTextEdit_setBackgroundVisible<()> for (i8) { fn setBackgroundVisible(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit20setBackgroundVisibleEb()}; let arg0 = self as c_char; unsafe {C_ZN14QPlainTextEdit20setBackgroundVisibleEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setUndoRedoEnabled(bool enable); impl /*struct*/ QPlainTextEdit { pub fn setUndoRedoEnabled<RetType, T: QPlainTextEdit_setUndoRedoEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setUndoRedoEnabled(self); // return 1; } } pub trait QPlainTextEdit_setUndoRedoEnabled<RetType> { fn setUndoRedoEnabled(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setUndoRedoEnabled(bool enable); impl<'a> /*trait*/ QPlainTextEdit_setUndoRedoEnabled<()> for (i8) { fn setUndoRedoEnabled(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit18setUndoRedoEnabledEb()}; let arg0 = self as c_char; unsafe {C_ZN14QPlainTextEdit18setUndoRedoEnabledEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QPlainTextEdit::overwriteMode(); impl /*struct*/ QPlainTextEdit { pub fn overwriteMode<RetType, T: QPlainTextEdit_overwriteMode<RetType>>(& self, overload_args: T) -> RetType { return overload_args.overwriteMode(self); // return 1; } } pub trait QPlainTextEdit_overwriteMode<RetType> { fn overwriteMode(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::overwriteMode(); impl<'a> /*trait*/ QPlainTextEdit_overwriteMode<i8> for () { fn overwriteMode(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit13overwriteModeEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit13overwriteModeEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::centerCursor(); impl /*struct*/ QPlainTextEdit { pub fn centerCursor<RetType, T: QPlainTextEdit_centerCursor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.centerCursor(self); // return 1; } } pub trait QPlainTextEdit_centerCursor<RetType> { fn centerCursor(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::centerCursor(); impl<'a> /*trait*/ QPlainTextEdit_centerCursor<()> for () { fn centerCursor(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit12centerCursorEv()}; unsafe {C_ZN14QPlainTextEdit12centerCursorEv(rsthis.qclsinst)}; // return 1; } } // proto: const QMetaObject * QPlainTextEdit::metaObject(); impl /*struct*/ QPlainTextEdit { pub fn metaObject<RetType, T: QPlainTextEdit_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QPlainTextEdit_metaObject<RetType> { fn metaObject(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: const QMetaObject * QPlainTextEdit::metaObject(); impl<'a> /*trait*/ QPlainTextEdit_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QPlainTextEdit) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit10metaObjectEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMenu * QPlainTextEdit::createStandardContextMenu(); impl<'a> /*trait*/ QPlainTextEdit_createStandardContextMenu<QMenu> for () { fn createStandardContextMenu(self , rsthis: & QPlainTextEdit) -> QMenu { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit25createStandardContextMenuEv()}; let mut ret = unsafe {C_ZN14QPlainTextEdit25createStandardContextMenuEv(rsthis.qclsinst)}; let mut ret1 = QMenu::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QPlainTextEdit::setDocumentTitle(const QString & title); impl /*struct*/ QPlainTextEdit { pub fn setDocumentTitle<RetType, T: QPlainTextEdit_setDocumentTitle<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDocumentTitle(self); // return 1; } } pub trait QPlainTextEdit_setDocumentTitle<RetType> { fn setDocumentTitle(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setDocumentTitle(const QString & title); impl<'a> /*trait*/ QPlainTextEdit_setDocumentTitle<()> for (&'a QString) { fn setDocumentTitle(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit16setDocumentTitleERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit16setDocumentTitleERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::~QPlainTextEdit(); impl /*struct*/ QPlainTextEdit { pub fn free<RetType, T: QPlainTextEdit_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QPlainTextEdit_free<RetType> { fn free(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::~QPlainTextEdit(); impl<'a> /*trait*/ QPlainTextEdit_free<()> for () { fn free(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEditD2Ev()}; unsafe {C_ZN14QPlainTextEditD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextEdit::clear(); impl /*struct*/ QPlainTextEdit { pub fn clear<RetType, T: QPlainTextEdit_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QPlainTextEdit_clear<RetType> { fn clear(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::clear(); impl<'a> /*trait*/ QPlainTextEdit_clear<()> for () { fn clear(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit5clearEv()}; unsafe {C_ZN14QPlainTextEdit5clearEv(rsthis.qclsinst)}; // return 1; } } // proto: QString QPlainTextEdit::anchorAt(const QPoint & pos); impl /*struct*/ QPlainTextEdit { pub fn anchorAt<RetType, T: QPlainTextEdit_anchorAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.anchorAt(self); // return 1; } } pub trait QPlainTextEdit_anchorAt<RetType> { fn anchorAt(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QString QPlainTextEdit::anchorAt(const QPoint & pos); impl<'a> /*trait*/ QPlainTextEdit_anchorAt<QString> for (&'a QPoint) { fn anchorAt(self , rsthis: & QPlainTextEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit8anchorAtERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK14QPlainTextEdit8anchorAtERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QPlainTextEdit::canPaste(); impl /*struct*/ QPlainTextEdit { pub fn canPaste<RetType, T: QPlainTextEdit_canPaste<RetType>>(& self, overload_args: T) -> RetType { return overload_args.canPaste(self); // return 1; } } pub trait QPlainTextEdit_canPaste<RetType> { fn canPaste(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::canPaste(); impl<'a> /*trait*/ QPlainTextEdit_canPaste<i8> for () { fn canPaste(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit8canPasteEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit8canPasteEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::QPlainTextEdit(QWidget * parent); impl<'a> /*trait*/ QPlainTextEdit_new for (Option<&'a QWidget>) { fn new(self) -> QPlainTextEdit { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEditC2EP7QWidget()}; let ctysz: c_int = unsafe{QPlainTextEdit_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN14QPlainTextEditC2EP7QWidget(arg0)}; let rsthis = QPlainTextEdit{qbase: QAbstractScrollArea::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QPlainTextEdit::cut(); impl /*struct*/ QPlainTextEdit { pub fn cut<RetType, T: QPlainTextEdit_cut<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cut(self); // return 1; } } pub trait QPlainTextEdit_cut<RetType> { fn cut(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::cut(); impl<'a> /*trait*/ QPlainTextEdit_cut<()> for () { fn cut(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit3cutEv()}; unsafe {C_ZN14QPlainTextEdit3cutEv(rsthis.qclsinst)}; // return 1; } } // proto: void QPlainTextEdit::appendHtml(const QString & html); impl /*struct*/ QPlainTextEdit { pub fn appendHtml<RetType, T: QPlainTextEdit_appendHtml<RetType>>(& self, overload_args: T) -> RetType { return overload_args.appendHtml(self); // return 1; } } pub trait QPlainTextEdit_appendHtml<RetType> { fn appendHtml(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::appendHtml(const QString & html); impl<'a> /*trait*/ QPlainTextEdit_appendHtml<()> for (&'a QString) { fn appendHtml(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit10appendHtmlERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit10appendHtmlERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QPlainTextEdit::isUndoRedoEnabled(); impl /*struct*/ QPlainTextEdit { pub fn isUndoRedoEnabled<RetType, T: QPlainTextEdit_isUndoRedoEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isUndoRedoEnabled(self); // return 1; } } pub trait QPlainTextEdit_isUndoRedoEnabled<RetType> { fn isUndoRedoEnabled(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::isUndoRedoEnabled(); impl<'a> /*trait*/ QPlainTextEdit_isUndoRedoEnabled<i8> for () { fn isUndoRedoEnabled(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit17isUndoRedoEnabledEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit17isUndoRedoEnabledEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::zoomOut(int range); impl /*struct*/ QPlainTextEdit { pub fn zoomOut<RetType, T: QPlainTextEdit_zoomOut<RetType>>(& self, overload_args: T) -> RetType { return overload_args.zoomOut(self); // return 1; } } pub trait QPlainTextEdit_zoomOut<RetType> { fn zoomOut(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::zoomOut(int range); impl<'a> /*trait*/ QPlainTextEdit_zoomOut<()> for (Option<i32>) { fn zoomOut(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit7zoomOutEi()}; let arg0 = (if self.is_none() {1} else {self.unwrap()}) as c_int; unsafe {C_ZN14QPlainTextEdit7zoomOutEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::setPlaceholderText(const QString & placeholderText); impl /*struct*/ QPlainTextEdit { pub fn setPlaceholderText<RetType, T: QPlainTextEdit_setPlaceholderText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setPlaceholderText(self); // return 1; } } pub trait QPlainTextEdit_setPlaceholderText<RetType> { fn setPlaceholderText(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::setPlaceholderText(const QString & placeholderText); impl<'a> /*trait*/ QPlainTextEdit_setPlaceholderText<()> for (&'a QString) { fn setPlaceholderText(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit18setPlaceholderTextERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit18setPlaceholderTextERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QPlainTextEdit::undo(); impl /*struct*/ QPlainTextEdit { pub fn undo<RetType, T: QPlainTextEdit_undo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.undo(self); // return 1; } } pub trait QPlainTextEdit_undo<RetType> { fn undo(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::undo(); impl<'a> /*trait*/ QPlainTextEdit_undo<()> for () { fn undo(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit4undoEv()}; unsafe {C_ZN14QPlainTextEdit4undoEv(rsthis.qclsinst)}; // return 1; } } // proto: QTextCursor QPlainTextEdit::cursorForPosition(const QPoint & pos); impl /*struct*/ QPlainTextEdit { pub fn cursorForPosition<RetType, T: QPlainTextEdit_cursorForPosition<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorForPosition(self); // return 1; } } pub trait QPlainTextEdit_cursorForPosition<RetType> { fn cursorForPosition(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: QTextCursor QPlainTextEdit::cursorForPosition(const QPoint & pos); impl<'a> /*trait*/ QPlainTextEdit_cursorForPosition<QTextCursor> for (&'a QPoint) { fn cursorForPosition(self , rsthis: & QPlainTextEdit) -> QTextCursor { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit17cursorForPositionERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK14QPlainTextEdit17cursorForPositionERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QTextCursor::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QPlainTextEdit::centerOnScroll(); impl /*struct*/ QPlainTextEdit { pub fn centerOnScroll<RetType, T: QPlainTextEdit_centerOnScroll<RetType>>(& self, overload_args: T) -> RetType { return overload_args.centerOnScroll(self); // return 1; } } pub trait QPlainTextEdit_centerOnScroll<RetType> { fn centerOnScroll(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: bool QPlainTextEdit::centerOnScroll(); impl<'a> /*trait*/ QPlainTextEdit_centerOnScroll<i8> for () { fn centerOnScroll(self , rsthis: & QPlainTextEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit14centerOnScrollEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit14centerOnScrollEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QPlainTextEdit::appendPlainText(const QString & text); impl /*struct*/ QPlainTextEdit { pub fn appendPlainText<RetType, T: QPlainTextEdit_appendPlainText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.appendPlainText(self); // return 1; } } pub trait QPlainTextEdit_appendPlainText<RetType> { fn appendPlainText(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: void QPlainTextEdit::appendPlainText(const QString & text); impl<'a> /*trait*/ QPlainTextEdit_appendPlainText<()> for (&'a QString) { fn appendPlainText(self , rsthis: & QPlainTextEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QPlainTextEdit15appendPlainTextERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QPlainTextEdit15appendPlainTextERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QPlainTextEdit::cursorWidth(); impl /*struct*/ QPlainTextEdit { pub fn cursorWidth<RetType, T: QPlainTextEdit_cursorWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorWidth(self); // return 1; } } pub trait QPlainTextEdit_cursorWidth<RetType> { fn cursorWidth(self , rsthis: & QPlainTextEdit) -> RetType; } // proto: int QPlainTextEdit::cursorWidth(); impl<'a> /*trait*/ QPlainTextEdit_cursorWidth<i32> for () { fn cursorWidth(self , rsthis: & QPlainTextEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit11cursorWidthEv()}; let mut ret = unsafe {C_ZNK14QPlainTextEdit11cursorWidthEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: QRect QPlainTextEdit::cursorRect(const QTextCursor & cursor); impl<'a> /*trait*/ QPlainTextEdit_cursorRect<QRect> for (&'a QTextCursor) { fn cursorRect(self , rsthis: & QPlainTextEdit) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QPlainTextEdit10cursorRectERK11QTextCursor()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK14QPlainTextEdit10cursorRectERK11QTextCursor(rsthis.qclsinst, arg0)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } #[derive(Default)] // for QPlainTextEdit_cursorPositionChanged pub struct QPlainTextEdit_cursorPositionChanged_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn cursorPositionChanged(&self) -> QPlainTextEdit_cursorPositionChanged_signal { return QPlainTextEdit_cursorPositionChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_cursorPositionChanged_signal { pub fn connect<T: QPlainTextEdit_cursorPositionChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_cursorPositionChanged_signal_connect { fn connect(self, sigthis: QPlainTextEdit_cursorPositionChanged_signal); } #[derive(Default)] // for QPlainTextEdit_modificationChanged pub struct QPlainTextEdit_modificationChanged_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn modificationChanged(&self) -> QPlainTextEdit_modificationChanged_signal { return QPlainTextEdit_modificationChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_modificationChanged_signal { pub fn connect<T: QPlainTextEdit_modificationChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_modificationChanged_signal_connect { fn connect(self, sigthis: QPlainTextEdit_modificationChanged_signal); } #[derive(Default)] // for QPlainTextEdit_redoAvailable pub struct QPlainTextEdit_redoAvailable_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn redoAvailable(&self) -> QPlainTextEdit_redoAvailable_signal { return QPlainTextEdit_redoAvailable_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_redoAvailable_signal { pub fn connect<T: QPlainTextEdit_redoAvailable_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_redoAvailable_signal_connect { fn connect(self, sigthis: QPlainTextEdit_redoAvailable_signal); } #[derive(Default)] // for QPlainTextEdit_selectionChanged pub struct QPlainTextEdit_selectionChanged_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn selectionChanged(&self) -> QPlainTextEdit_selectionChanged_signal { return QPlainTextEdit_selectionChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_selectionChanged_signal { pub fn connect<T: QPlainTextEdit_selectionChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_selectionChanged_signal_connect { fn connect(self, sigthis: QPlainTextEdit_selectionChanged_signal); } #[derive(Default)] // for QPlainTextEdit_updateRequest pub struct QPlainTextEdit_updateRequest_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn updateRequest(&self) -> QPlainTextEdit_updateRequest_signal { return QPlainTextEdit_updateRequest_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_updateRequest_signal { pub fn connect<T: QPlainTextEdit_updateRequest_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_updateRequest_signal_connect { fn connect(self, sigthis: QPlainTextEdit_updateRequest_signal); } #[derive(Default)] // for QPlainTextEdit_blockCountChanged pub struct QPlainTextEdit_blockCountChanged_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn blockCountChanged(&self) -> QPlainTextEdit_blockCountChanged_signal { return QPlainTextEdit_blockCountChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_blockCountChanged_signal { pub fn connect<T: QPlainTextEdit_blockCountChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_blockCountChanged_signal_connect { fn connect(self, sigthis: QPlainTextEdit_blockCountChanged_signal); } #[derive(Default)] // for QPlainTextEdit_undoAvailable pub struct QPlainTextEdit_undoAvailable_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn undoAvailable(&self) -> QPlainTextEdit_undoAvailable_signal { return QPlainTextEdit_undoAvailable_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_undoAvailable_signal { pub fn connect<T: QPlainTextEdit_undoAvailable_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_undoAvailable_signal_connect { fn connect(self, sigthis: QPlainTextEdit_undoAvailable_signal); } #[derive(Default)] // for QPlainTextEdit_textChanged pub struct QPlainTextEdit_textChanged_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn textChanged(&self) -> QPlainTextEdit_textChanged_signal { return QPlainTextEdit_textChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_textChanged_signal { pub fn connect<T: QPlainTextEdit_textChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_textChanged_signal_connect { fn connect(self, sigthis: QPlainTextEdit_textChanged_signal); } #[derive(Default)] // for QPlainTextEdit_copyAvailable pub struct QPlainTextEdit_copyAvailable_signal{poi:u64} impl /* struct */ QPlainTextEdit { pub fn copyAvailable(&self) -> QPlainTextEdit_copyAvailable_signal { return QPlainTextEdit_copyAvailable_signal{poi:self.qclsinst}; } } impl /* struct */ QPlainTextEdit_copyAvailable_signal { pub fn connect<T: QPlainTextEdit_copyAvailable_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QPlainTextEdit_copyAvailable_signal_connect { fn connect(self, sigthis: QPlainTextEdit_copyAvailable_signal); } // blockCountChanged(int) extern fn QPlainTextEdit_blockCountChanged_signal_connect_cb_0(rsfptr:fn(i32), arg0: c_int) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i32; rsfptr(rsarg0); } extern fn QPlainTextEdit_blockCountChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(i32)>, arg0: c_int) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i32; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QPlainTextEdit_blockCountChanged_signal_connect for fn(i32) { fn connect(self, sigthis: QPlainTextEdit_blockCountChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_blockCountChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit17blockCountChangedEi(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_blockCountChanged_signal_connect for Box<Fn(i32)> { fn connect(self, sigthis: QPlainTextEdit_blockCountChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_blockCountChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit17blockCountChangedEi(arg0, arg1, arg2)}; } } // undoAvailable(_Bool) extern fn QPlainTextEdit_undoAvailable_signal_connect_cb_1(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QPlainTextEdit_undoAvailable_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QPlainTextEdit_undoAvailable_signal_connect for fn(i8) { fn connect(self, sigthis: QPlainTextEdit_undoAvailable_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_undoAvailable_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13undoAvailableEb(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_undoAvailable_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QPlainTextEdit_undoAvailable_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_undoAvailable_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13undoAvailableEb(arg0, arg1, arg2)}; } } // selectionChanged() extern fn QPlainTextEdit_selectionChanged_signal_connect_cb_2(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QPlainTextEdit_selectionChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QPlainTextEdit_selectionChanged_signal_connect for fn() { fn connect(self, sigthis: QPlainTextEdit_selectionChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_selectionChanged_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit16selectionChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_selectionChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QPlainTextEdit_selectionChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_selectionChanged_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit16selectionChangedEv(arg0, arg1, arg2)}; } } // redoAvailable(_Bool) extern fn QPlainTextEdit_redoAvailable_signal_connect_cb_3(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QPlainTextEdit_redoAvailable_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QPlainTextEdit_redoAvailable_signal_connect for fn(i8) { fn connect(self, sigthis: QPlainTextEdit_redoAvailable_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_redoAvailable_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13redoAvailableEb(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_redoAvailable_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QPlainTextEdit_redoAvailable_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_redoAvailable_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13redoAvailableEb(arg0, arg1, arg2)}; } } // modificationChanged(_Bool) extern fn QPlainTextEdit_modificationChanged_signal_connect_cb_4(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QPlainTextEdit_modificationChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QPlainTextEdit_modificationChanged_signal_connect for fn(i8) { fn connect(self, sigthis: QPlainTextEdit_modificationChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_modificationChanged_signal_connect_cb_4 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit19modificationChangedEb(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_modificationChanged_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QPlainTextEdit_modificationChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_modificationChanged_signal_connect_cb_box_4 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit19modificationChangedEb(arg0, arg1, arg2)}; } } // updateRequest(const class QRect &, int) extern fn QPlainTextEdit_updateRequest_signal_connect_cb_5(rsfptr:fn(QRect, i32), arg0: *mut c_void, arg1: c_int) { println!("{}:{}", file!(), line!()); let rsarg0 = QRect::inheritFrom(arg0 as u64); let rsarg1 = arg1 as i32; rsfptr(rsarg0,rsarg1); } extern fn QPlainTextEdit_updateRequest_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(QRect, i32)>, arg0: *mut c_void, arg1: c_int) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QRect::inheritFrom(arg0 as u64); let rsarg1 = arg1 as i32; // rsfptr(rsarg0,rsarg1); unsafe{(*rsfptr_raw)(rsarg0,rsarg1)}; } impl /* trait */ QPlainTextEdit_updateRequest_signal_connect for fn(QRect, i32) { fn connect(self, sigthis: QPlainTextEdit_updateRequest_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_updateRequest_signal_connect_cb_5 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13updateRequestERK5QRecti(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_updateRequest_signal_connect for Box<Fn(QRect, i32)> { fn connect(self, sigthis: QPlainTextEdit_updateRequest_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_updateRequest_signal_connect_cb_box_5 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13updateRequestERK5QRecti(arg0, arg1, arg2)}; } } // textChanged() extern fn QPlainTextEdit_textChanged_signal_connect_cb_6(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QPlainTextEdit_textChanged_signal_connect_cb_box_6(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QPlainTextEdit_textChanged_signal_connect for fn() { fn connect(self, sigthis: QPlainTextEdit_textChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_textChanged_signal_connect_cb_6 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit11textChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_textChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QPlainTextEdit_textChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_textChanged_signal_connect_cb_box_6 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit11textChangedEv(arg0, arg1, arg2)}; } } // cursorPositionChanged() extern fn QPlainTextEdit_cursorPositionChanged_signal_connect_cb_7(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QPlainTextEdit_cursorPositionChanged_signal_connect_cb_box_7(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QPlainTextEdit_cursorPositionChanged_signal_connect for fn() { fn connect(self, sigthis: QPlainTextEdit_cursorPositionChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_cursorPositionChanged_signal_connect_cb_7 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit21cursorPositionChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_cursorPositionChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QPlainTextEdit_cursorPositionChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_cursorPositionChanged_signal_connect_cb_box_7 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit21cursorPositionChangedEv(arg0, arg1, arg2)}; } } // copyAvailable(_Bool) extern fn QPlainTextEdit_copyAvailable_signal_connect_cb_8(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QPlainTextEdit_copyAvailable_signal_connect_cb_box_8(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QPlainTextEdit_copyAvailable_signal_connect for fn(i8) { fn connect(self, sigthis: QPlainTextEdit_copyAvailable_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_copyAvailable_signal_connect_cb_8 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13copyAvailableEb(arg0, arg1, arg2)}; } } impl /* trait */ QPlainTextEdit_copyAvailable_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QPlainTextEdit_copyAvailable_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QPlainTextEdit_copyAvailable_signal_connect_cb_box_8 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QPlainTextEdit_SlotProxy_connect__ZN14QPlainTextEdit13copyAvailableEb(arg0, arg1, arg2)}; } } // <= body block end
use pyo3::class::basic::CompareOp; use pyo3::class::*; use pyo3::prelude::*; use pyo3::py_run; mod common; #[pyclass] struct UnaryArithmetic { inner: f64, } impl UnaryArithmetic { fn new(value: f64) -> Self { UnaryArithmetic { inner: value } } } #[pyproto] impl PyObjectProtocol for UnaryArithmetic { fn __repr__(&self) -> String { format!("UA({})", self.inner) } } #[pyproto] impl PyNumberProtocol for UnaryArithmetic { fn __neg__(&self) -> Self { Self::new(-self.inner) } fn __pos__(&self) -> Self { Self::new(self.inner) } fn __abs__(&self) -> Self { Self::new(self.inner.abs()) } fn __round__(&self, _ndigits: Option<u32>) -> Self { Self::new(self.inner.round()) } } #[test] fn unary_arithmetic() { let gil = Python::acquire_gil(); let py = gil.python(); let c = PyCell::new(py, UnaryArithmetic::new(2.7)).unwrap(); py_run!(py, c, "assert repr(-c) == 'UA(-2.7)'"); py_run!(py, c, "assert repr(+c) == 'UA(2.7)'"); py_run!(py, c, "assert repr(abs(c)) == 'UA(2.7)'"); py_run!(py, c, "assert repr(round(c)) == 'UA(3)'"); py_run!(py, c, "assert repr(round(c, 1)) == 'UA(3)'"); } #[pyclass] struct BinaryArithmetic {} #[pyproto] impl PyObjectProtocol for BinaryArithmetic { fn __repr__(&self) -> &'static str { "BA" } } #[pyclass] struct InPlaceOperations { value: u32, } #[pyproto] impl PyObjectProtocol for InPlaceOperations { fn __repr__(&self) -> String { format!("IPO({:?})", self.value) } } #[pyproto] impl PyNumberProtocol for InPlaceOperations { fn __iadd__(&mut self, other: u32) { self.value += other; } fn __isub__(&mut self, other: u32) { self.value -= other; } fn __imul__(&mut self, other: u32) { self.value *= other; } fn __ilshift__(&mut self, other: u32) { self.value <<= other; } fn __irshift__(&mut self, other: u32) { self.value >>= other; } fn __iand__(&mut self, other: u32) { self.value &= other; } fn __ixor__(&mut self, other: u32) { self.value ^= other; } fn __ior__(&mut self, other: u32) { self.value |= other; } fn __ipow__(&mut self, other: u32) { self.value = self.value.pow(other); } } #[test] fn inplace_operations() { let gil = Python::acquire_gil(); let py = gil.python(); let init = |value, code| { let c = PyCell::new(py, InPlaceOperations { value }).unwrap(); py_run!(py, c, code); }; init(0, "d = c; c += 1; assert repr(c) == repr(d) == 'IPO(1)'"); init(10, "d = c; c -= 1; assert repr(c) == repr(d) == 'IPO(9)'"); init(3, "d = c; c *= 3; assert repr(c) == repr(d) == 'IPO(9)'"); init(3, "d = c; c <<= 2; assert repr(c) == repr(d) == 'IPO(12)'"); init(12, "d = c; c >>= 2; assert repr(c) == repr(d) == 'IPO(3)'"); init(12, "d = c; c &= 10; assert repr(c) == repr(d) == 'IPO(8)'"); init(12, "d = c; c |= 3; assert repr(c) == repr(d) == 'IPO(15)'"); init(12, "d = c; c ^= 5; assert repr(c) == repr(d) == 'IPO(9)'"); init(3, "d = c; c **= 4; assert repr(c) == repr(d) == 'IPO(81)'"); init( 3, "d = c; c.__ipow__(4); assert repr(c) == repr(d) == 'IPO(81)'", ); } #[pyproto] impl PyNumberProtocol for BinaryArithmetic { fn __add__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} + {:?}", lhs, rhs) } fn __sub__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} - {:?}", lhs, rhs) } fn __mul__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} * {:?}", lhs, rhs) } fn __lshift__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} << {:?}", lhs, rhs) } fn __rshift__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} >> {:?}", lhs, rhs) } fn __and__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} & {:?}", lhs, rhs) } fn __xor__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} ^ {:?}", lhs, rhs) } fn __or__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} | {:?}", lhs, rhs) } fn __pow__(lhs: &PyAny, rhs: &PyAny, mod_: Option<u32>) -> String { format!("{:?} ** {:?} (mod: {:?})", lhs, rhs, mod_) } } #[test] fn binary_arithmetic() { let gil = Python::acquire_gil(); let py = gil.python(); let c = PyCell::new(py, BinaryArithmetic {}).unwrap(); py_run!(py, c, "assert c + c == 'BA + BA'"); py_run!(py, c, "assert c.__add__(c) == 'BA + BA'"); py_run!(py, c, "assert c + 1 == 'BA + 1'"); py_run!(py, c, "assert 1 + c == '1 + BA'"); py_run!(py, c, "assert c - 1 == 'BA - 1'"); py_run!(py, c, "assert 1 - c == '1 - BA'"); py_run!(py, c, "assert c * 1 == 'BA * 1'"); py_run!(py, c, "assert 1 * c == '1 * BA'"); py_run!(py, c, "assert c << 1 == 'BA << 1'"); py_run!(py, c, "assert 1 << c == '1 << BA'"); py_run!(py, c, "assert c >> 1 == 'BA >> 1'"); py_run!(py, c, "assert 1 >> c == '1 >> BA'"); py_run!(py, c, "assert c & 1 == 'BA & 1'"); py_run!(py, c, "assert 1 & c == '1 & BA'"); py_run!(py, c, "assert c ^ 1 == 'BA ^ 1'"); py_run!(py, c, "assert 1 ^ c == '1 ^ BA'"); py_run!(py, c, "assert c | 1 == 'BA | 1'"); py_run!(py, c, "assert 1 | c == '1 | BA'"); py_run!(py, c, "assert c ** 1 == 'BA ** 1 (mod: None)'"); py_run!(py, c, "assert 1 ** c == '1 ** BA (mod: None)'"); py_run!(py, c, "assert pow(c, 1, 100) == 'BA ** 1 (mod: Some(100))'"); } #[pyclass] struct RhsArithmetic {} #[pyproto] impl PyNumberProtocol for RhsArithmetic { fn __radd__(&self, other: &PyAny) -> String { format!("{:?} + RA", other) } fn __rsub__(&self, other: &PyAny) -> String { format!("{:?} - RA", other) } fn __rmul__(&self, other: &PyAny) -> String { format!("{:?} * RA", other) } fn __rlshift__(&self, other: &PyAny) -> String { format!("{:?} << RA", other) } fn __rrshift__(&self, other: &PyAny) -> String { format!("{:?} >> RA", other) } fn __rand__(&self, other: &PyAny) -> String { format!("{:?} & RA", other) } fn __rxor__(&self, other: &PyAny) -> String { format!("{:?} ^ RA", other) } fn __ror__(&self, other: &PyAny) -> String { format!("{:?} | RA", other) } fn __rpow__(&self, other: &PyAny, _mod: Option<&'p PyAny>) -> String { format!("{:?} ** RA", other) } } #[test] fn rhs_arithmetic() { let gil = Python::acquire_gil(); let py = gil.python(); let c = PyCell::new(py, RhsArithmetic {}).unwrap(); py_run!(py, c, "assert c.__radd__(1) == '1 + RA'"); py_run!(py, c, "assert 1 + c == '1 + RA'"); py_run!(py, c, "assert c.__rsub__(1) == '1 - RA'"); py_run!(py, c, "assert 1 - c == '1 - RA'"); py_run!(py, c, "assert c.__rmul__(1) == '1 * RA'"); py_run!(py, c, "assert 1 * c == '1 * RA'"); py_run!(py, c, "assert c.__rlshift__(1) == '1 << RA'"); py_run!(py, c, "assert 1 << c == '1 << RA'"); py_run!(py, c, "assert c.__rrshift__(1) == '1 >> RA'"); py_run!(py, c, "assert 1 >> c == '1 >> RA'"); py_run!(py, c, "assert c.__rand__(1) == '1 & RA'"); py_run!(py, c, "assert 1 & c == '1 & RA'"); py_run!(py, c, "assert c.__rxor__(1) == '1 ^ RA'"); py_run!(py, c, "assert 1 ^ c == '1 ^ RA'"); py_run!(py, c, "assert c.__ror__(1) == '1 | RA'"); py_run!(py, c, "assert 1 | c == '1 | RA'"); py_run!(py, c, "assert c.__rpow__(1) == '1 ** RA'"); py_run!(py, c, "assert 1 ** c == '1 ** RA'"); } #[pyclass] struct LhsAndRhsArithmetic {} #[pyproto] impl PyNumberProtocol for LhsAndRhsArithmetic { fn __radd__(&self, other: &PyAny) -> String { format!("{:?} + RA", other) } fn __rsub__(&self, other: &PyAny) -> String { format!("{:?} - RA", other) } fn __rpow__(&self, other: &PyAny, _mod: Option<&'p PyAny>) -> String { format!("{:?} ** RA", other) } fn __add__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} + {:?}", lhs, rhs) } fn __sub__(lhs: &PyAny, rhs: &PyAny) -> String { format!("{:?} - {:?}", lhs, rhs) } fn __pow__(lhs: &PyAny, rhs: &PyAny, _mod: Option<u32>) -> String { format!("{:?} ** {:?}", lhs, rhs) } } #[pyproto] impl PyObjectProtocol for LhsAndRhsArithmetic { fn __repr__(&self) -> &'static str { "BA" } } #[test] fn lhs_override_rhs() { let gil = Python::acquire_gil(); let py = gil.python(); let c = PyCell::new(py, LhsAndRhsArithmetic {}).unwrap(); // Not overrided py_run!(py, c, "assert c.__radd__(1) == '1 + RA'"); py_run!(py, c, "assert c.__rsub__(1) == '1 - RA'"); py_run!(py, c, "assert c.__rpow__(1) == '1 ** RA'"); // Overrided py_run!(py, c, "assert 1 + c == '1 + BA'"); py_run!(py, c, "assert 1 - c == '1 - BA'"); py_run!(py, c, "assert 1 ** c == '1 ** BA'"); } #[pyclass] struct RichComparisons {} #[pyproto] impl PyObjectProtocol for RichComparisons { fn __repr__(&self) -> &'static str { "RC" } fn __richcmp__(&self, other: &PyAny, op: CompareOp) -> String { match op { CompareOp::Lt => format!("{} < {:?}", self.__repr__(), other), CompareOp::Le => format!("{} <= {:?}", self.__repr__(), other), CompareOp::Eq => format!("{} == {:?}", self.__repr__(), other), CompareOp::Ne => format!("{} != {:?}", self.__repr__(), other), CompareOp::Gt => format!("{} > {:?}", self.__repr__(), other), CompareOp::Ge => format!("{} >= {:?}", self.__repr__(), other), } } } #[pyclass] struct RichComparisons2 {} #[pyproto] impl PyObjectProtocol for RichComparisons2 { fn __repr__(&self) -> &'static str { "RC2" } fn __richcmp__(&self, _other: &PyAny, op: CompareOp) -> PyObject { let gil = GILGuard::acquire(); let py = gil.python(); match op { CompareOp::Eq => true.into_py(py), CompareOp::Ne => false.into_py(py), _ => py.NotImplemented(), } } } #[test] fn rich_comparisons() { let gil = Python::acquire_gil(); let py = gil.python(); let c = PyCell::new(py, RichComparisons {}).unwrap(); py_run!(py, c, "assert (c < c) == 'RC < RC'"); py_run!(py, c, "assert (c < 1) == 'RC < 1'"); py_run!(py, c, "assert (1 < c) == 'RC > 1'"); py_run!(py, c, "assert (c <= c) == 'RC <= RC'"); py_run!(py, c, "assert (c <= 1) == 'RC <= 1'"); py_run!(py, c, "assert (1 <= c) == 'RC >= 1'"); py_run!(py, c, "assert (c == c) == 'RC == RC'"); py_run!(py, c, "assert (c == 1) == 'RC == 1'"); py_run!(py, c, "assert (1 == c) == 'RC == 1'"); py_run!(py, c, "assert (c != c) == 'RC != RC'"); py_run!(py, c, "assert (c != 1) == 'RC != 1'"); py_run!(py, c, "assert (1 != c) == 'RC != 1'"); py_run!(py, c, "assert (c > c) == 'RC > RC'"); py_run!(py, c, "assert (c > 1) == 'RC > 1'"); py_run!(py, c, "assert (1 > c) == 'RC < 1'"); py_run!(py, c, "assert (c >= c) == 'RC >= RC'"); py_run!(py, c, "assert (c >= 1) == 'RC >= 1'"); py_run!(py, c, "assert (1 >= c) == 'RC <= 1'"); } #[test] fn rich_comparisons_python_3_type_error() { let gil = Python::acquire_gil(); let py = gil.python(); let c2 = PyCell::new(py, RichComparisons2 {}).unwrap(); py_expect_exception!(py, c2, "c2 < c2", PyTypeError); py_expect_exception!(py, c2, "c2 < 1", PyTypeError); py_expect_exception!(py, c2, "1 < c2", PyTypeError); py_expect_exception!(py, c2, "c2 <= c2", PyTypeError); py_expect_exception!(py, c2, "c2 <= 1", PyTypeError); py_expect_exception!(py, c2, "1 <= c2", PyTypeError); py_run!(py, c2, "assert (c2 == c2) == True"); py_run!(py, c2, "assert (c2 == 1) == True"); py_run!(py, c2, "assert (1 == c2) == True"); py_run!(py, c2, "assert (c2 != c2) == False"); py_run!(py, c2, "assert (c2 != 1) == False"); py_run!(py, c2, "assert (1 != c2) == False"); py_expect_exception!(py, c2, "c2 > c2", PyTypeError); py_expect_exception!(py, c2, "c2 > 1", PyTypeError); py_expect_exception!(py, c2, "1 > c2", PyTypeError); py_expect_exception!(py, c2, "c2 >= c2", PyTypeError); py_expect_exception!(py, c2, "c2 >= 1", PyTypeError); py_expect_exception!(py, c2, "1 >= c2", PyTypeError); }
// 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::boxed::Box; use alloc::vec::Vec; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::threadmgr::thread::*; use super::super::threadmgr::threads::*; use super::super::threadmgr::pid_namespace::*; use super::super::threadmgr::thread_group::*; use super::super::qlib::auth::id::*; //use super::super::Common::*; use super::super::SignalDef::*; use super::super::task::*; use super::task_stop::*; use super::super::qlib::perf_tunning::*; // An ExitStatus is a value communicated from an exiting task or thread group // to the party that reaps it. #[derive(Clone, Copy, Default, Debug)] pub struct ExitStatus { // Code is the numeric value passed to the call to exit or exit_group that // caused the exit. If the exit was not caused by such a call, Code is 0. pub Code: i32, // Signo is the signal that caused the exit. If the exit was not caused by // a signal, Signo is 0. pub Signo: i32, } impl ExitStatus { pub fn New(code: i32, signo: i32) -> Self { return ExitStatus { Code: code, Signo: signo, } } // Signaled returns true if the ExitStatus indicates that the exiting task or // thread group was killed by a signal. pub fn Signaled(&self) -> bool { return self.Signo != 0; } // Status returns the numeric representation of the ExitStatus returned by e.g. // the wait4() system call. pub fn Status(&self) -> u32 { return (((self.Code as u32) & 0xff) << 8) | ((self.Signo as u32) & 0xff); } // ShellExitCode returns the numeric exit code that Bash would return for an // exit status of es. pub fn ShellExitCode(&self) -> i32 { if self.Signaled() { return 128 + self.Signo } return self.Code } } // TaskExitState represents a step in the task exit path. // // "Exiting" and "exited" are often ambiguous; prefer to name specific states. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum TaskExitState { // TaskExitNone indicates that the task has not begun exiting. TaskExitNone, // TaskExitInitiated indicates that the task goroutine has entered the exit // path, and the task is no longer eligible to participate in group stops // or group signal handling. TaskExitInitiated is analogous to Linux's // PF_EXITING. TaskExitInitiated, // TaskExitZombie indicates that the task has released its resources, and // the task no longer prevents a sibling thread from completing execve. TaskExitZombie, // TaskExitDead indicates that the task's thread IDs have been released, // and the task no longer prevents its thread group leader from being // reaped. ("Reaping" refers to the transitioning of a task from // TaskExitZombie to TaskExitDead.) TaskExitDead, } impl core::default::Default for TaskExitState { fn default() -> Self { return Self::TaskExitNone } } impl TaskExitState { pub fn String(&self) -> &'static str { match self { TaskExitState::TaskExitNone => return "TaskExitNone", TaskExitState::TaskExitInitiated => return "TaskExitInitiated", TaskExitState::TaskExitZombie => return "TaskExitZombie", TaskExitState::TaskExitDead => return "TaskExitDead", } } } impl ThreadInternal { // killLocked marks t as killed by enqueueing a SIGKILL, without causing the // thread-group-affecting side effects SIGKILL usually has. // // Preconditions: The signal mutex must be locked. pub fn killLocked(&mut self) { if self.stop.is_some() && self.stop.clone().unwrap().Killable() { self.endInternalStopLocked(); } self.pendingSignals.Enque(Box::new(SignalInfo { Signo: Signal::SIGKILL, Code: SignalInfo::SIGNAL_INFO_USER, ..Default::default() }), None).expect("killLocked fail"); self.interrupt(); } // killed returns true if t has a SIGKILL pending. killed is analogous to // Linux's fatal_signal_pending(). // // Preconditions: The caller must be running on the task goroutine. pub fn killed(&self) -> bool { let lock = self.tg.lock().signalLock.clone(); let _s = lock.lock(); return self.killedLocked() } pub fn killedLocked(&self) -> bool { return self.pendingSignals.pendingSet.0 & SignalSet::New(Signal(Signal::SIGKILL)).0 != 0 } // advanceExitStateLocked checks that t's current exit state is oldExit, then // sets it to newExit. If t's current exit state is not oldExit, // advanceExitStateLocked panics. // // Preconditions: The TaskSet mutex must be locked. pub fn advanceExitStateLocked(&mut self, oldExit: TaskExitState, newExit: TaskExitState) { info!("advanceExitStateLocked[{}] {:?}=>{:?}", self.id, oldExit, newExit); if self.exitState != oldExit { panic!("Transitioning from exit state {:?} to {:?}: unexpected preceding state {:?}", oldExit, newExit, self.exitState) } self.exitState = newExit; } } // Task events that can be waited for. // EventExit represents an exit notification generated for a child thread // group leader or a tracee under the conditions specified in the comment // above runExitNotify. pub const EVENT_EXIT: EventMask = 1; // EventChildGroupStop occurs when a child thread group completes a group // stop (i.e. all tasks in the child thread group have entered a stopped // state as a result of a group stop). pub const EVENT_CHILD_GROUP_STOP: EventMask = 1 << 1; // EventTraceeStop occurs when a task that is ptraced by a task in the // notified thread group enters a ptrace stop (see ptrace(2)). pub const EVENT_TRACEE_STOP: EventMask = 1 << 2; // EventGroupContinue occurs when a child thread group, or a thread group // whose leader is ptraced by a task in the notified thread group, that had // initiated or completed a group stop leaves the group stop, due to the // child thread group or any task in the child thread group being sent // SIGCONT. pub const EVENT_GROUP_CONTINUE: EventMask = 1 << 3; impl Thread { // findReparentTargetLocked returns the task to which t's children should be // reparented. If no such task exists, findNewParentLocked returns nil. // // Preconditions: The TaskSet mutex must be locked. pub fn findReparentTargetLocked(&self) -> Option<Thread> { let tg = self.lock().tg.clone(); // Reparent to any sibling in the same thread group that hasn't begun // exiting. match tg.anyNonExitingTaskLocked() { Some(t2) => return Some(t2), None => (), } // "A child process that is orphaned within the namespace will be // reparented to [the init process for the namespace] ..." - // pid_namespaces(7) let pidns = tg.PIDNamespace(); let init = match pidns.lock().tasks.get(&INIT_TID) { Some(init) => init.clone(), None => return None }; let inittg = init.lock().tg.clone(); return inittg.anyNonExitingTaskLocked(); } // PrepareExit indicates an exit with status es. // // Preconditions: The caller must be running on the task goroutine. pub fn PrepareExit(&self, es: ExitStatus) { let mut t = self.lock(); let lock = t.tg.lock().signalLock.clone(); let _s = lock.lock(); t.exitStatus = es; } // PrepareGroupExit indicates a group exit with status es to t's thread group. // // PrepareGroupExit is analogous to Linux's do_group_exit(), except that it // does not tail-call do_exit(), except that it *does* set Task.exitStatus. // (Linux does not do so until within do_exit(), since it reuses exit_code for // ptrace.) // // Preconditions: The caller must be running on the task goroutine. pub fn PrepareGroupExit(&self, es: ExitStatus) { let tg = self.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); let exiting = tg.lock().exiting; let execing = tg.lock().execing.Upgrade(); if exiting || execing.is_some() { // Note that if t.tg.exiting is false but t.tg.execing is not nil, i.e. // this "group exit" is being executed by the killed sibling of an // execing task, then Task.Execve never set t.tg.exitStatus, so it's // still the zero value. This is consistent with Linux, both in intent // ("all other threads ... report death as if they exited via _exit(2) // with exit code 0" - ptrace(2), "execve under ptrace") and in // implementation (compare fs/exec.c:de_thread() => // kernel/signal.c:zap_other_threads() and // kernel/exit.c:do_group_exit() => // include/linux/sched.h:signal_group_exit()). self.lock().exitStatus = tg.lock().exitStatus; return } tg.lock().exiting = true; tg.lock().exitStatus = es; self.lock().exitStatus = es; let tasks : Vec<Thread> = tg.lock().tasks.iter().cloned().collect(); for sibling in &tasks { if *sibling != *self { sibling.lock().killLocked(); } } } // exitThreadGroup transitions t to TaskExitInitiated, indicating to t's thread // group that it is no longer eligible to participate in group activities. It // returns true if t is the last task in its thread group to call // exitThreadGroup. pub fn exitThreadGroup(&self) -> bool { let tg = self.ThreadGroup(); let pidns = tg.PIDNamespace(); let _owner = pidns.lock().owner.clone(); let lock = tg.lock().signalLock.clone(); let sig; let notifyParent; let last; { let _s = lock.lock(); self.lock().advanceExitStateLocked(TaskExitState::TaskExitNone, TaskExitState::TaskExitInitiated); tg.lock().activeTasks -= 1; last = tg.lock().activeTasks == 0; // Ensure that someone will handle the signals we can't. self.setSignalMaskLocked(SignalSet(!0)); if !self.lock().groupStopPending { return last } self.lock().groupStopPending = false; sig = tg.lock().groupStopSignal; notifyParent = self.lock().participateGroupStopLocked(); } let leader = tg.lock().leader.Upgrade().unwrap(); if notifyParent && leader.lock().parent.is_some() { let parent = leader.lock().parent.clone().unwrap(); parent.signalStop(self, SignalInfo::CLD_STOPPED, sig.0); let tgOfParent = parent.lock().tg.clone(); tgOfParent.lock().eventQueue.Notify(EVENT_CHILD_GROUP_STOP); } return last } pub fn exitChildren(&self) { let tg = self.lock().tg.clone(); let pidns = tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _l = owner.WriteLock(); let newParent = self.findReparentTargetLocked(); if newParent.is_none() { // "If the init process of a PID namespace terminates, the kernel // terminates all of the processes in the namespace via a SIGKILL // signal." - pid_namespaces(7) pidns.lock().exiting = true; let tgids : Vec<ThreadGroup> = pidns.lock().tgids.keys().cloned().collect(); for other in &tgids { if *other == self.lock().tg.clone() { continue; } let lock = other.lock().signalLock.clone(); let _s = lock.lock(); let leader = other.lock().leader.Upgrade().unwrap(); leader.sendSignalLocked(&SignalInfo { Signo: Signal::SIGKILL, ..Default::default() }, true).unwrap(); } } // This is correct even if newParent is nil (it ensures that children don't // wait for a parent to reap them.) let creds = self.lock().creds.clone(); let mut children = Vec::new(); for c in &self.lock().children { children.push(c.clone()); } for c in &children { let sig = c.ParentDeathSignal(); if sig.0 != 0 { let mut sigInfo = SignalInfo { Signo: sig.0, Code: SignalInfo::SIGNAL_INFO_USER, ..Default::default() }; let sigchild = sigInfo.SigChld(); let tg = c.lock().tg.clone(); let pidns = tg.PIDNamespace(); let userns = c.UserNamespace(); sigchild.pid = *pidns.lock().tids.get(self).unwrap(); sigchild.uid = creds.lock().RealKUID.In(&userns).OrOverflow().0; let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); c.sendSignalLocked(&sigInfo, true).unwrap(); } c.reparentLocked(&newParent); if newParent.is_some() { newParent.clone().unwrap().lock().children.insert(c.clone()); } } } pub fn reparentLocked(&self, parent: &Option<Thread>) { let oldParent = self.lock().parent.clone(); self.lock().parent = parent.clone(); /*{ let oldid = match oldParent.clone() { Some(t) => t.lock().id, None => 0 }; let parent = self.lock().parent.clone(); if parent.is_some() { error!("reparentLocked set {} old parent is {} parent to {}", self.lock().id, oldid, parent.unwrap().lock().id); } else { error!("reparentLocked set {} old parent is {} parent None", self.lock().id, oldid); } }*/ // If a thread group leader's parent changes, reset the thread group's // termination signal to SIGCHLD and re-check exit notification. (Compare // kernel/exit.c:reparent_leader().) let tg = self.lock().tg.clone(); let leader = tg.lock().leader.Upgrade(); if Some(self.clone()) != leader { return } if oldParent.is_none() && parent.is_none() { return } if oldParent.is_some() && parent.is_some() { let oldtg = oldParent.clone().unwrap().lock().tg.clone(); let parenttg = parent.clone().unwrap().lock().tg.clone(); if oldtg == parenttg { return } } tg.lock().terminationSignal = Signal(Signal::SIGCHLD); let exitParentNotified = self.lock().exitParentNotified; let exitParentAcked = self.lock().exitParentAcked; if exitParentNotified && !exitParentAcked { self.lock().exitParentNotified = false; self.exitNotifyLocked() } } pub fn waitOnce(&self, opts: &WaitOptions) -> Result<WaitResult> { let mut anyWaitableTasks = false; let tg = self.lock().tg.clone(); let pidns = tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _lock = owner.WriteLock(); if opts.SiblingChildren { // We can wait on the children and tracees of any task in the // same thread group. let parents: Vec<Thread> = tg.lock().tasks.iter().cloned().collect(); for parent in &parents { let (wr, any) = self.waitParentLocked(opts, parent); if wr.is_some() { return Ok(wr.unwrap()) } anyWaitableTasks = anyWaitableTasks || any; } } else { // We can only wait on this task. let (wr, any) = self.waitParentLocked(opts, self); anyWaitableTasks = any; if wr.is_some() { return Ok(wr.unwrap()) } } if anyWaitableTasks { return Err(Error::ErrNoWaitableEvent) } return Err(Error::SysError(SysErr::ECHILD)) } pub fn waitParentLocked(&self, opts: &WaitOptions, parent: &Thread) -> (Option<WaitResult>, bool) { let mut anyWaitableTasks = false; let parenttg = parent.lock().tg.clone(); let pidns = parenttg.PIDNamespace(); let children: Vec<Thread> = parent.lock().children.iter().cloned().collect(); for child in &children { let child = child.clone(); if !opts.matchesTask(&child, &pidns) { continue; } // Non-leaders don't notify parents on exit and aren't eligible to // be waited on. let childtg = child.lock().tg.clone(); let childleader = childtg.lock().leader.Upgrade(); if opts.Events & EVENT_EXIT != 0 && Some(child.clone()) == childleader && !child.lock().exitParentAcked { anyWaitableTasks = true; let wr = self.waitCollectZombieLocked(&child, opts); if wr.is_some() { return (wr, anyWaitableTasks) } } // Check for group stops and continues. Tasks that have passed // TaskExitInitiated can no longer participate in group stops. if opts.Events & (EVENT_CHILD_GROUP_STOP | EVENT_GROUP_CONTINUE) == 0 { continue; } if child.lock().exitState >= TaskExitState::TaskExitInitiated { continue; } anyWaitableTasks = true; if opts.Events & EVENT_CHILD_GROUP_STOP != 0 { let wr = self.waitCollectChildGroupStopLocked(&child, opts); if wr.is_some() { return (wr, anyWaitableTasks) } } if opts.Events & EVENT_GROUP_CONTINUE != 0 { let wr = self.waitCollectGroupContinueLocked(&child, opts); if wr.is_some() { return (wr, anyWaitableTasks) } } } return (None, anyWaitableTasks) } pub fn waitCollectZombieLocked(&self, target: &Thread, opts: &WaitOptions) -> Option<WaitResult> { if !target.lock().exitParentNotified { return None; } let tg = self.ThreadGroup(); let target = target.clone(); let targetTg = target.ThreadGroup(); let targetLead = targetTg.lock().leader.Upgrade(); // Zombied thread group leaders are never waitable until their thread group // is otherwise empty. Usually this is caught by the // target.exitParentNotified check above, but if t is both (in the thread // group of) target's tracer and parent, asPtracer may be true. if targetLead.is_some() && target == targetLead.unwrap() && targetTg.lock().tasksCount != 1 { return None; } let pidns = targetTg.PIDNamespace(); let pid = pidns.IDOfTaskLocked(&target); // .lock().tids.get(&target).unwrap(); let creds = target.Credentials(); let userns = self.UserNamespace(); let uid = creds.lock().RealKUID.In(&userns).OrOverflow(); let mut status = target.lock().exitStatus.Status(); if !opts.ConsumeEvent { return Some(WaitResult { Thread: target.clone(), TID: pid, UID: uid, Event: EVENT_EXIT, Status: status, }) } // Surprisingly, the exit status reported by a non-consuming wait can // differ from that reported by a consuming wait; the latter will return // the group exit code if one is available. if targetTg.lock().exiting { status = targetTg.lock().exitStatus.Status(); } let targetParent = target.lock().parent.clone(); let exitParentNotified = target.lock().exitParentNotified; assert!(targetParent.is_some(), "waitCollectZombieLocked parent should not be none"); let parentTg = targetParent.unwrap().lock().tg.clone(); let targetLead = targetTg.lock().leader.Upgrade(); if parentTg != targetTg && exitParentNotified { target.lock().exitParentAcked = true; if targetLead.is_some() && target == targetLead.unwrap() { // target.tg.exitedCPUStats doesn't include target.CPUStats() yet, // and won't until after target.exitNotifyLocked() (maybe). Include // target.CPUStats() explicitly. This is consistent with Linux, // which accounts an exited task's cputime to its thread group in // kernel/exit.c:release_task() => __exit_signal(), and uses // thread_group_cputime_adjusted() in wait_task_zombie(). let mut tglock = tg.lock(); let targettglock = targetTg.lock(); tglock.childCPUStats.Accumulate(&target.CPUStats()); tglock.childCPUStats.Accumulate(&targettglock.exitedCPUStats); tglock.childCPUStats.Accumulate(&targettglock.childCPUStats); // Update t's child max resident set size. The size will be the maximum // of this thread's size and all its childrens' sizes. let maxRSS = tglock.maxRSS; if maxRSS < targettglock.maxRSS { tglock.childMaxRSS = targettglock.maxRSS; } let childMaxRSS = tglock.childMaxRSS; if childMaxRSS < targettglock.childMaxRSS { tglock.childMaxRSS = targettglock.childMaxRSS; } } } target.exitNotifyLocked(); return Some(WaitResult { Thread: target, TID: pid, UID: uid, Event: EVENT_EXIT, Status: status, }) } // updateRSSLocked updates t.tg.maxRSS. // // Preconditions: The TaskSet mutex must be locked for writing. pub fn updateRSSLocked(&self) { let mm = self.lock().memoryMgr.clone(); let mmMaxRSS = mm.MaxResidentSetSize(); let tg = self.lock().tg.clone(); if tg.lock().maxRSS < mmMaxRSS { tg.lock().maxRSS = mmMaxRSS; } } pub fn waitCollectChildGroupStopLocked(&self, target: &Thread, opts: &WaitOptions) -> Option<WaitResult> { let targetTg = target.ThreadGroup(); let lock = targetTg.lock().signalLock.clone(); let _s = lock.lock(); if !targetTg.lock().groupStopWaitable { return None; } let pidns = targetTg.PIDNamespace(); let pid = pidns.IDOfTaskLocked(target); let creds = target.Credentials(); let userns = self.UserNamespace(); let uid = creds.lock().RealKUID.In(&userns).OrOverflow(); let signal = targetTg.lock().groupStopSignal; if opts.ConsumeEvent { targetTg.lock().groupStopWaitable = false; } return Some(WaitResult { Thread: target.clone(), TID: pid, UID: uid, Event: EVENT_CHILD_GROUP_STOP, Status: ((signal.0 as u32) & 0xff) << 8 | 0x7f, }) } pub fn waitCollectGroupContinueLocked(&self, target: &Thread, opts: &WaitOptions) -> Option<WaitResult> { let tg = target.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); if !tg.lock().groupContWaitable { return None; } let pidns = self.PIDNamespace(); let pid = *pidns.lock().tids.get(target).unwrap(); let creds = target.Credentials(); let userns = self.UserNamespace(); let uid = creds.lock().RealKUID.In(&userns).OrOverflow(); if opts.ConsumeEvent { tg.lock().groupContWaitable = false; } return Some(WaitResult { Thread: target.clone(), TID: pid, UID: uid, Event: EVENT_GROUP_CONTINUE, Status: 0xffff, }) } // exitNotifyLocked is called after changes to t's state that affect exit // notification. // // // Preconditions: The TaskSet mutex must be locked for writing. pub fn exitNotifyLocked(&self) { let t = self.clone(); if t.lock().exitState != TaskExitState::TaskExitZombie { return } let exitTracerNotified = t.lock().exitTracerNotified; if !exitTracerNotified { t.lock().exitTracerNotified = true; t.lock().exitTracerAcked = true; } let exitTracerAcked = t.lock().exitTracerAcked; let exitParentNotified = t.lock().exitParentNotified; if exitTracerAcked && !exitParentNotified { let tg = t.lock().tg.clone(); let leader = tg.lock().leader.Upgrade(); if Some(t.clone()) != leader { t.lock().exitParentNotified = true; t.lock().exitParentAcked = true; } else if tg.lock().tasksCount == 1 { t.lock().exitParentNotified = true; let parent = t.lock().parent.clone(); if parent.is_none() { t.lock().exitParentAcked = true; } else { // "POSIX.1-2001 specifies that if the disposition of SIGCHLD is // set to SIG_IGN or the SA_NOCLDWAIT flag is set for SIGCHLD (see // sigaction(2)), then children that terminate do not become // zombies and a call to wait() or waitpid() will block until all // children have terminated, and then fail with errno set to // ECHILD. (The original POSIX standard left the behavior of // setting SIGCHLD to SIG_IGN unspecified. Note that even though // the default disposition of SIGCHLD is "ignore", explicitly // setting the disposition to SIG_IGN results in different // treatment of zombie process children.) Linux 2.6 conforms to // this specification." - wait(2) // // Some undocumented Linux-specific details: // // - All of the above is ignored if the termination signal isn't // SIGCHLD. // // - SA_NOCLDWAIT causes the leader to be immediately reaped, but // does not suppress the SIGCHLD. let signal = tg.lock().terminationSignal; let mut signalParent = signal.IsValid(); let parentTg = parent.unwrap().lock().tg.clone(); let lock = parentTg.lock().signalLock.clone(); { let _s = lock.lock(); let sh = parentTg.lock().signalHandlers.clone(); if signal.0 == Signal::SIGCHLD { match sh.lock().actions.get(&signal.0) { None => (), Some(act) => { if act.handler == SigAct::SIGNAL_ACT_IGNORE { t.lock().exitParentAcked = true; signalParent = false; } else if act.flags.IsNoCldWait() { t.lock().exitParentAcked = true; } } } } if signalParent { let leader = parentTg.lock().leader.Upgrade(); let terminationSignal = tg.lock().terminationSignal; let parent = t.lock().parent.clone().unwrap(); let signalInfo = t.exitNotificationSignal(terminationSignal, &parent); leader.unwrap().sendSignalLocked(&signalInfo, true).unwrap(); } } // If a task in the parent was waiting for a child group stop // or continue, it needs to be notified of the exit, because // there may be no remaining eligible tasks (so that wait // should return ECHILD). parentTg.lock().eventQueue.Notify(EVENT_EXIT | EVENT_CHILD_GROUP_STOP | EVENT_GROUP_CONTINUE); } } } let exitTracerAcked = t.lock().exitTracerAcked; let exitParentAcked = t.lock().exitParentAcked; if exitTracerAcked && exitParentAcked { t.lock().advanceExitStateLocked(TaskExitState::TaskExitZombie, TaskExitState::TaskExitDead); let tg = t.lock().tg.clone(); let mut pidns = tg.PIDNamespace(); loop { let tid = *pidns.lock().tids.get(&t).unwrap(); pidns.lock().tasks.remove(&tid); pidns.lock().tids.remove(&t); let leader = tg.lock().leader.Upgrade(); if Some(t.clone()) == leader { pidns.lock().tgids.remove(&tg); } let tmp = pidns.lock().parent.clone(); if tmp.is_none() { break; } pidns = tmp.unwrap(); } tg.lock().exitedCPUStats.Accumulate(&t.lock().CPUStats()); //tg.lock().ioUsage.Accumulate(t.lock().ioUsage); let tc = { let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); tg.lock().tasks.remove(&t); tg.lock().tasksCount -= 1; let tc = tg.lock().tasksCount; tc }; let leader = tg.lock().leader.Upgrade(); if tc == 1 && Some(t.clone()) != leader { // Our fromPtraceDetach doesn't matter here (in Linux terms, this // is via a call to release_task()). leader.unwrap().exitNotifyLocked(); } else if tc == 0 { let processGroup = tg.lock().processGroup.clone(); let parentPg = tg.parentPG(); processGroup.unwrap().decRefWithParent(parentPg); } let parent = t.lock().parent.clone(); if parent.is_some() { parent.unwrap().lock().children.remove(&t); t.lock().parent = None; } } } pub fn exitNotificationSignal(&self, sig: Signal, receiver: &Thread) -> SignalInfo { let mut info = SignalInfo { Signo: sig.0, ..Default::default() }; let tg = receiver.lock().tg.clone(); let pidns = tg.lock().pidns.clone(); let tid = *pidns.lock().tids.get(self).unwrap(); info.SigChld().pid = tid; let creds = self.Credentials(); let kuid = creds.lock().RealKUID; let userns = receiver.UserNamespace(); info.SigChld().uid = kuid.In(&userns).OrOverflow().0; let signaled = self.lock().exitStatus.Signaled(); if signaled { info.Code = SignalInfo::CLD_KILLED; info.SigChld().status = self.lock().exitStatus.Signo; } else { info.Code = SignalInfo::CLD_EXITED; info.SigChld().status = self.lock().exitStatus.Code; } return info; } pub fn ExitStatus(&self) -> ExitStatus { let ts = self.TaskSet(); let tg = self.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _r = ts.read(); let _s = lock.lock(); return self.lock().exitStatus; } pub fn ExitState(&self) -> TaskExitState { return self.lock().exitState; } pub fn ParentDeathSignal(&self) -> Signal { return self.lock().parentDeathSignal; } pub fn SetParentDeathSignal(&self, sig: Signal) { self.lock().parentDeathSignal = sig; } pub fn Signaled(&self) -> bool { let tg = self.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); let tglock = tg.lock(); return tglock.exiting && tglock.exitStatus.Signaled() } pub fn ExitMain(&self) { let lastExiter = self.exitThreadGroup(); let tg = self.lock().tg.clone(); { let pidns = tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _l = owner.WriteLock(); self.updateRSSLocked(); } // todo: fix this let task = Task::Current(); // Handle the robust futex list. self.ExitRobustList(task); self.UnstopVforkParent(); // If this is the last task to exit from the thread group, release the // thread group's resources. if lastExiter { tg.release(); } self.exitChildren(); //self.ExitNotify(); } pub fn ExitNotify(&self) { let tg = self.lock().tg.clone(); let pidns = tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let ownerlock = owner.WriteLock(); self.lock().advanceExitStateLocked(TaskExitState::TaskExitInitiated, TaskExitState::TaskExitZombie); //info!("ExitNotify 1 [{:x}]", self.lock().taskId); { let mut tglock = tg.lock(); tglock.liveTasks -= 1; tglock.liveThreads.Add(-1); // Check if this completes a sibling's execve. if tglock.execing.Upgrade().is_some() && tglock.liveTasks == 1 { // execing blocks the addition of new tasks to the thread group, so // the sole living task must be the execing one. let t = tglock.execing.Upgrade().unwrap(); tglock.signalLock.lock(); let mut tlock = t.lock(); match &tlock.stop { None => (), Some(ref stop) => { if stop.Type() == TaskStopType::EXECSTOP { tlock.endInternalStopLocked(); } } } } } //info!("ExitNotify 2 [{:x}]", self.lock().taskId); self.exitNotifyLocked(); error!("ExitNotify 3 [{:x}]", self.lock().taskId); let taskCnt = owner.write().DecrTaskCount1(); error!("ExitNotify 4 [{:x}], taskcnt is {}", self.lock().taskId, taskCnt); if taskCnt == 0 { //PerfStop(); PerfPrint(); super::super::perflog::THREAD_COUNTS.lock().Print(false); //super::super::AllocatorPrint(); core::mem::drop(ownerlock); let exitStatus = tg.ExitStatus(); super::super::PAGE_MGR.PrintRefs(); super::super::Kernel::HostSpace::ExitVM(exitStatus.ShellExitCode()); } } } impl ThreadGroup { pub fn anyNonExitingTaskLocked(&self) -> Option<Thread> { let tasks : Vec<_> = self.lock().tasks.iter().cloned().collect(); for t in &tasks { if t.lock().exitState == TaskExitState::TaskExitNone { return Some(t.clone()) } } return None } pub fn ExitStatus(&self) -> ExitStatus { let ts = self.TaskSet(); let lock = self.lock().signalLock.clone(); ts.read(); let _s = lock.lock(); { let tglock = self.lock(); if tglock.exiting { return tglock.exitStatus } } //todo: there is chance that the leader is none, need fix let leader = self.lock().leader.Upgrade().unwrap(); return leader.lock().exitStatus; } pub fn TerminationSignal(&self) -> Signal { let ts = self.TaskSet(); let _r = ts.ReadLock(); return self.lock().terminationSignal } } impl TaskSet { // Kill requests that all tasks in ts exit as if group exiting with status es. // Kill does not wait for tasks to exit. // // Kill has no analogue in Linux; it's provided for save/restore only. pub fn Kill(&self, es: ExitStatus) { let _r = self.ReadLock(); let ts = self.read(); let pidns = ts.root.clone().unwrap(); pidns.lock().exiting = true; let threads : Vec<_> = pidns.lock().tids.keys().cloned().collect(); for t in &threads { let mut t = t.lock(); let lock = t.tg.lock().signalLock.clone(); let _s = lock.lock(); if !t.tg.lock().exiting { t.tg.lock().exiting = true; t.tg.lock().exitStatus = es; } t.killLocked(); } } } // WaitOptions controls the behavior of Task.Wait. #[derive(Debug, Clone, Default)] pub struct WaitOptions { // If SpecificTID is non-zero, only events from the task with thread ID // SpecificTID are eligible to be waited for. SpecificTID is resolved in // the PID namespace of the waiter (the method receiver of Task.Wait). If // no such task exists, or that task would not otherwise be eligible to be // waited for by the waiting task, then there are no waitable tasks and // Wait will return ECHILD. pub SpecificTID: ThreadID, // If SpecificPGID is non-zero, only events from ThreadGroups with a // matching ProcessGroupID are eligible to be waited for. (Same // constraints as SpecificTID apply.) pub SpecificPGID: ProcessGroupID, // Terminology note: Per waitpid(2), "a clone child is one which delivers // no signal, or a signal other than SIGCHLD to its parent upon // termination." In Linux, termination signal is technically a per-task // property rather than a per-thread-group property. However, clone() // forces no termination signal for tasks created with CLONE_THREAD, and // execve() resets the termination signal to SIGCHLD, so all // non-group-leader threads have no termination signal and are therefore // "clone tasks". // If NonCloneTasks is true, events from non-clone tasks are eligible to be // waited for. pub NonCloneTasks: bool, // If CloneTasks is true, events from clone tasks are eligible to be waited // for. pub CloneTasks: bool, // If SiblingChildren is true, events from children tasks of any task // in the thread group of the waiter are eligible to be waited for. pub SiblingChildren: bool, // Events is a bitwise combination of the events defined above that specify // what events are of interest to the call to Wait. pub Events: EventMask, // If ConsumeEvent is true, the Wait should consume the event such that it // cannot be returned by a future Wait. Note that if a task exit is // consumed in this way, in most cases the task will be reaped. pub ConsumeEvent: bool, // If BlockInterruptErr is not nil, Wait will block until either an event // is available or there are no tasks that could produce a waitable event; // if that blocking is interrupted, Wait returns BlockInterruptErr. If // BlockInterruptErr is nil, Wait will not block. pub BlockInterruptErr: Option<Error>, } impl WaitOptions { // Preconditions: The TaskSet mutex must be locked (for reading or writing). pub fn matchesTask(&self, t: &Thread, pidns: &PIDNamespace) -> bool { if self.SpecificTID != 0 { // && self.SpecificTID != *pidns.lock().tids.get(t).unwrap() { let id = match pidns.lock().tids.get(t) { None => { panic!("thread id {} doesn't exist", t.lock().id) //return false } Some(id) => *id }; if id != self.SpecificTID { return false } } let tg = t.lock().tg.clone(); let pg = tg.lock().processGroup.clone(); if self.SpecificPGID != 0 && pg.is_some() && self.SpecificPGID != *pidns.lock().pgids.get(&pg.unwrap()).unwrap() { return false } let leader = tg.lock().leader.Upgrade(); if Some(t.clone()) == leader && tg.lock().terminationSignal.0 == Signal::SIGCHLD { return self.NonCloneTasks } return self.CloneTasks } } // WaitResult contains information about a waited-for event. #[derive(Clone)] pub struct WaitResult { pub Thread: Thread, // TID is the thread ID of Task in the PID namespace of the task that // called Wait (that is, the method receiver of the call to Task.Wait). TID // is provided because consuming exit waits cause the thread ID to be // deallocated. pub TID: ThreadID, // UID is the real UID of Task in the user namespace of the task that // called Wait. pub UID: UID, // Event is exactly one of the events defined above. pub Event: EventMask, // Status is the numeric status associated with the event. pub Status: u32, } impl Task { pub fn RunExit(&mut self) -> TaskRunState { let t = self.Thread(); t.ExitMain(); return TaskRunState::RunExitNotify; } pub fn RunExitNotify(&mut self) -> TaskRunState { let t = self.Thread(); //info!("RunExitNotify 1 [{:x}]", self.taskId); self.Exit(); //info!("RunExitNotify 2 [{:x}]", self.taskId); t.ExitNotify(); //info!("RunExitNotify 3 [{:x}]", self.taskId); //won't reach here return TaskRunState::RunExitDone; } pub fn RunThreadExit(&mut self) -> TaskRunState { let t = self.Thread(); t.ExitMain(); return TaskRunState::RunTreadExitNotify; } pub fn RunThreadExitNotify(&mut self) -> TaskRunState { let t = self.Thread(); if self.isWaitThread { panic!("Exit from wait thread!") } if !t.Signaled() { match self.tidInfo.clear_child_tid { None => { //println!("there is no clear_child_tid"); } Some(addr) => { self.CopyOutObj(&(0 as u32), addr).unwrap(); self.futexMgr.Wake(self, addr, false, !0, 1).unwrap(); } } } t.ExitNotify(); //won't reach here return TaskRunState::RunExitDone; } }
// Copyright 2016 Amanieu d'Antras // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use libc; use std::sync::atomic::{AtomicI32, Ordering}; use std::time::Instant; const FUTEX_WAIT: i32 = 0; const FUTEX_WAKE: i32 = 1; const FUTEX_PRIVATE: i32 = 128; // x32 Linux uses a non-standard type for tv_nsec in timespec. // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] #[allow(non_camel_case_types)] type tv_nsec_t = i64; #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] #[allow(non_camel_case_types)] type tv_nsec_t = libc::c_long; // Helper type for putting a thread to sleep until some other thread wakes it up pub struct ThreadParker { futex: AtomicI32, } impl ThreadParker { pub fn new() -> ThreadParker { ThreadParker { futex: AtomicI32::new(0), } } // Prepares the parker. This should be called before adding it to the queue. pub unsafe fn prepare_park(&self) { self.futex.store(1, Ordering::Relaxed); } // Checks if the park timed out. This should be called while holding the // queue lock after park_until has returned false. pub unsafe fn timed_out(&self) -> bool { self.futex.load(Ordering::Relaxed) != 0 } // Parks the thread until it is unparked. This should be called after it has // been added to the queue, after unlocking the queue. pub unsafe fn park(&self) { while self.futex.load(Ordering::Acquire) != 0 { let r = libc::syscall( libc::SYS_futex, &self.futex, FUTEX_WAIT | FUTEX_PRIVATE, 1, 0, ); debug_assert!(r == 0 || r == -1); if r == -1 { debug_assert!( *libc::__errno_location() == libc::EINTR || *libc::__errno_location() == libc::EAGAIN ); } } } // Parks the thread until it is unparked or the timeout is reached. This // should be called after it has been added to the queue, after unlocking // the queue. Returns true if we were unparked and false if we timed out. pub unsafe fn park_until(&self, timeout: Instant) -> bool { while self.futex.load(Ordering::Acquire) != 0 { let now = Instant::now(); if timeout <= now { return false; } let diff = timeout - now; if diff.as_secs() as libc::time_t as u64 != diff.as_secs() { // Timeout overflowed, just sleep indefinitely self.park(); return true; } let ts = libc::timespec { tv_sec: diff.as_secs() as libc::time_t, tv_nsec: diff.subsec_nanos() as tv_nsec_t, }; let r = libc::syscall( libc::SYS_futex, &self.futex, FUTEX_WAIT | FUTEX_PRIVATE, 1, &ts, ); debug_assert!(r == 0 || r == -1); if r == -1 { debug_assert!( *libc::__errno_location() == libc::EINTR || *libc::__errno_location() == libc::EAGAIN || *libc::__errno_location() == libc::ETIMEDOUT ); } } true } // Locks the parker to prevent the target thread from exiting. This is // necessary to ensure that thread-local ThreadData objects remain valid. // This should be called while holding the queue lock. pub unsafe fn unpark_lock(&self) -> UnparkHandle { // We don't need to lock anything, just clear the state self.futex.store(0, Ordering::Release); UnparkHandle { futex: &self.futex } } } // Handle for a thread that is about to be unparked. We need to mark the thread // as unparked while holding the queue lock, but we delay the actual unparking // until after the queue lock is released. pub struct UnparkHandle { futex: *const AtomicI32, } impl UnparkHandle { // Wakes up the parked thread. This should be called after the queue lock is // released to avoid blocking the queue for too long. pub unsafe fn unpark(self) { // The thread data may have been freed at this point, but it doesn't // matter since the syscall will just return EFAULT in that case. let r = libc::syscall(libc::SYS_futex, self.futex, FUTEX_WAKE | FUTEX_PRIVATE, 1); debug_assert!(r == 0 || r == 1 || r == -1); if r == -1 { debug_assert_eq!(*libc::__errno_location(), libc::EFAULT); } } }
use cm_fidl_translator; use failure::Error; use fidl_fuchsia_data as fd; use fidl_fuchsia_sys2::{ CapabilityType, ChildDecl, ComponentDecl, ExposeDecl, OfferDecl, OfferTarget, Relation, RelativeId, UseDecl, }; use std::fs::File; use std::io::Read; use std::path::PathBuf; fn main() { let cm_content = read_cm("/pkg/meta/example.cm").expect("could not open example.cm"); let golden_cm = read_cm("/pkg/data/golden.cm").expect("could not open golden.cm"); assert_eq!(&cm_content, &golden_cm); let cm_decl = cm_fidl_translator::translate(&cm_content).expect("could not translate cm"); let expected_decl = { let program = fd::Dictionary{entries: vec![ fd::Entry{ key: "binary".to_string(), value: Some(Box::new(fd::Value::Str("bin/example".to_string()))), }, ]}; let uses = vec![ UseDecl{ type_: Some(CapabilityType::Service), source_path: Some("/fonts/CoolFonts".to_string()), target_path: Some("/svc/fuchsia.fonts.Provider".to_string()), }, ]; let exposes = vec![ ExposeDecl{ type_: Some(CapabilityType::Directory), source_path: Some("/volumes/blobfs".to_string()), source: Some(RelativeId{ relation: Some(Relation::Myself), child_name: None, }), target_path: Some("/volumes/blobfs".to_string()), }, ]; let offers = vec![ OfferDecl{ type_: Some(CapabilityType::Service), source_path: Some("/svc/fuchsia.logger.Log".to_string()), source: Some(RelativeId{ relation: Some(Relation::Child), child_name: Some("logger".to_string()), }), targets: Some(vec![ OfferTarget{ target_path: Some("/svc/fuchsia.logger.Log".to_string()), child_name: Some("netstack".to_string()), }, ]), }, ]; let children = vec![ ChildDecl{ name: Some("logger".to_string()), uri: Some("fuchsia-pkg://fuchsia.com/logger/stable#meta/logger.cm".to_string()), }, ChildDecl{ name: Some("netstack".to_string()), uri: Some("fuchsia-pkg://fuchsia.com/netstack/stable#meta/netstack.cm".to_string()), }, ]; let facets = fd::Dictionary{entries: vec![ fd::Entry{ key: "author".to_string(), value: Some(Box::new(fd::Value::Str("Fuchsia".to_string()))), }, fd::Entry{ key: "year".to_string(), value: Some(Box::new(fd::Value::Fnum(2018.))), }, ]}; ComponentDecl{ program: Some(program), uses: Some(uses), exposes: Some(exposes), offers: Some(offers), children: Some(children), facets: Some(facets) } }; assert_eq!(cm_decl, expected_decl); } fn read_cm(file: &str) -> Result<String, Error> { let mut buffer = String::new(); let path = PathBuf::from(file); File::open(&path)?.read_to_string(&mut buffer)?; Ok(buffer) }
pub struct Solution; impl Solution { pub fn divide(dividend: i32, divisor: i32) -> i32 { let mut dividend = dividend as i64; let mut divisor = divisor as i64; let mut negative = false; if dividend < 0 { dividend = -dividend; negative = !negative; } if divisor < 0 { divisor = -divisor; negative = !negative; } let mut n = -1; while dividend >= divisor << (n + 1) { n += 1; } let mut quotient = 0; while n >= 0 { if dividend >= divisor << n { dividend -= divisor << n; quotient |= 1 << n; } n -= 1; } if negative { quotient = -quotient; } if quotient > std::i32::MAX as i64 { std::i32::MAX } else if quotient < std::i32::MIN as i64 { std::i32::MIN } else { quotient as i32 } } } #[test] fn test0029() { assert_eq!(Solution::divide(10, 3), 3); assert_eq!(Solution::divide(7, -3), -2); assert_eq!(Solution::divide(-7, 3), -2); assert_eq!(Solution::divide(-7, -3), 2); assert_eq!(Solution::divide(-2147483648, -1), 2147483647); assert_eq!(Solution::divide(-999511578, -2147483648), 0); }
use std::prelude::v1::*; use http_req::uri::*; use std::ops::Range; fn remove_spaces(text: &mut String) { text.retain(|c| !c.is_whitespace()); } const HTTP_PORT: u16 = 80; const HTTPS_PORT: u16 = 443; const TEST_URIS: [&str; 5] = [ "https://user:info@foo.com:12/bar/baz?query#fragment", "file:///C:/Users/User/Pictures/screenshot.png", "https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol", "mailto:John.Doe@example.com", "https://[4b10:bbb0:0:d0::ba7:8001]:443/", ]; const TEST_AUTH: [&str; 4] = [ "user:info@foo.com:12", "en.wikipedia.org", "John.Doe@example.com", "[4b10:bbb0:0:d0::ba7:8001]:443", ]; //#[test] pub fn remove_space() { let mut text = String::from("Hello World !"); let expect = String::from("HelloWorld!"); remove_spaces(&mut text); assert_eq!(text, expect); } //#[test] pub fn uri_full_parse() { let uri = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1" .parse::<Uri>() .unwrap(); assert_eq!(uri.scheme(), "abc"); assert_eq!(uri.user_info(), Some("username:password")); assert_eq!(uri.host(), Some("example.com")); assert_eq!(uri.port(), Some(123)); assert_eq!(uri.path(), Some("/path/data")); assert_eq!(uri.query(), Some("key=value&key2=value2")); assert_eq!(uri.fragment(), Some("fragid1")); } //#[test] pub fn uri_parse() { for uri in TEST_URIS.iter() { uri.parse::<Uri>().unwrap(); } } //#[test] pub fn uri_scheme() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].scheme(), "https"); assert_eq!(uris[1].scheme(), "file"); assert_eq!(uris[2].scheme(), "https"); assert_eq!(uris[3].scheme(), "mailto"); assert_eq!(uris[4].scheme(), "https"); } //#[test] pub fn uri_uesr_info() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].user_info(), Some("user:info")); assert_eq!(uris[1].user_info(), None); assert_eq!(uris[2].user_info(), None); assert_eq!(uris[3].user_info(), None); assert_eq!(uris[4].user_info(), None); } //#[test] pub fn uri_host() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].host(), Some("foo.com")); assert_eq!(uris[1].host(), None); assert_eq!(uris[2].host(), Some("en.wikipedia.org")); assert_eq!(uris[3].host(), None); assert_eq!(uris[4].host(), Some("[4b10:bbb0:0:d0::ba7:8001]")); } //#[test] pub fn uri_host_header() { let uri_def: Uri = "https://en.wikipedia.org:443/wiki/Hypertext_Transfer_Protocol" .parse() .unwrap(); let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].host_header(), Some("foo.com:12".to_string())); assert_eq!(uris[2].host_header(), Some("en.wikipedia.org".to_string())); assert_eq!(uri_def.host_header(), Some("en.wikipedia.org".to_string())); } //#[test] pub fn uri_port() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].port(), Some(12)); assert_eq!(uris[4].port(), Some(443)); for i in 1..3 { assert_eq!(uris[i].port(), None); } } //#[test] pub fn uri_corr_port() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].corr_port(), 12); assert_eq!(uris[1].corr_port(), HTTP_PORT); assert_eq!(uris[2].corr_port(), HTTPS_PORT); assert_eq!(uris[3].corr_port(), HTTP_PORT); assert_eq!(uris[4].corr_port(), HTTPS_PORT); } //#[test] pub fn uri_path() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].path(), Some("/bar/baz")); assert_eq!( uris[1].path(), Some("/C:/Users/User/Pictures/screenshot.png") ); assert_eq!(uris[2].path(), Some("/wiki/Hypertext_Transfer_Protocol")); assert_eq!(uris[3].path(), Some("John.Doe@example.com")); assert_eq!(uris[4].path(), None); } //#[test] pub fn uri_query() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].query(), Some("query")); for i in 1..4 { assert_eq!(uris[i].query(), None); } } //#[test] pub fn uri_fragment() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].fragment(), Some("fragment")); for i in 1..4 { assert_eq!(uris[i].fragment(), None); } } //#[test] pub fn uri_resource() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!(uris[0].resource(), "/bar/baz?query#fragment"); assert_eq!(uris[1].resource(), "/C:/Users/User/Pictures/screenshot.png"); assert_eq!(uris[2].resource(), "/wiki/Hypertext_Transfer_Protocol"); assert_eq!(uris[3].resource(), "John.Doe@example.com"); assert_eq!(uris[4].resource(), "/"); } //#[test] pub fn uri_display() { let uris: Vec<_> = TEST_URIS .iter() .map(|uri| uri.parse::<Uri>().unwrap()) .collect(); assert_eq!( uris[0].to_string(), "https://user:****@foo.com:12/bar/baz?query#fragment" ); for i in 1..uris.len() { let s = uris[i].to_string(); assert_eq!(s, TEST_URIS[i]); } } //#[test] pub fn authority_username() { let auths: Vec<_> = TEST_AUTH .iter() .map(|auth| auth.parse::<Authority>().unwrap()) .collect(); assert_eq!(auths[0].username(), Some("user")); assert_eq!(auths[1].username(), None); assert_eq!(auths[2].username(), Some("John.Doe")); assert_eq!(auths[3].username(), None); } //#[test] pub fn authority_password() { let auths: Vec<_> = TEST_AUTH .iter() .map(|auth| auth.parse::<Authority>().unwrap()) .collect(); assert_eq!(auths[0].password(), Some("info")); assert_eq!(auths[1].password(), None); assert_eq!(auths[2].password(), None); assert_eq!(auths[3].password(), None); } //#[test] pub fn authority_host() { let auths: Vec<_> = TEST_AUTH .iter() .map(|auth| auth.parse::<Authority>().unwrap()) .collect(); assert_eq!(auths[0].host(), "foo.com"); assert_eq!(auths[1].host(), "en.wikipedia.org"); assert_eq!(auths[2].host(), "example.com"); assert_eq!(auths[3].host(), "[4b10:bbb0:0:d0::ba7:8001]"); } //#[test] pub fn authority_port() { let auths: Vec<_> = TEST_AUTH .iter() .map(|auth| auth.parse::<Authority>().unwrap()) .collect(); assert_eq!(auths[0].port(), Some(12)); assert_eq!(auths[1].port(), None); assert_eq!(auths[2].port(), None); assert_eq!(auths[3].port(), Some(443)); } //#[test] pub fn authority_from_str() { for auth in TEST_AUTH.iter() { auth.parse::<Authority>().unwrap(); } } //#[test] pub fn authority_display() { let auths: Vec<_> = TEST_AUTH .iter() .map(|auth| auth.parse::<Authority>().unwrap()) .collect(); assert_eq!("user:****@foo.com:12", auths[0].to_string()); for i in 1..auths.len() { let s = auths[i].to_string(); assert_eq!(s, TEST_AUTH[i]); } } //#[test] pub fn range_c_new() { assert_eq!( RangeC::new(22, 343), RangeC { start: 22, end: 343, } ) } //#[test] pub fn range_from_range_c() { assert_eq!( Range::from(RangeC::new(222, 43)), Range { start: 222, end: 43, } ) } //#[test] pub fn range_c_index() { const RANGE: RangeC = RangeC::new(0, 4); let text = TEST_AUTH[0].to_string(); assert_eq!(text[..4], text[RANGE]) }
use crate::prelude::*; use std::sync::{Arc, Mutex}; pub enum ClearValue { Color([f32; 4]), Depth(f32, u32), } pub struct CustomTarget { pub usage: VkImageUsageFlagBits, pub format: VkFormat, pub clear_on_load: bool, pub store_on_save: bool, pub attach_sampler: bool, pub clear_value: ClearValue, } impl CustomTarget { pub fn depth() -> CustomTarget { CustomTarget { usage: VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT.into(), format: VK_FORMAT_D16_UNORM, clear_on_load: true, store_on_save: false, attach_sampler: false, clear_value: ClearValue::Depth(1.0, 0), } } } pub struct RenderTargetBuilder<'a> { width: u32, height: u32, sample_count: VkSampleCountFlags, target_infos: Vec<CustomTarget>, // (images, index, clear_color, clear_on_load) prepared_targets: Option<(&'a [Arc<Image>], usize, [f32; 4], bool)>, resolve_targets: Option<&'a [Arc<Image>]>, } impl<'a> RenderTargetBuilder<'a> { pub fn set_sample_count(mut self, sample_count: VkSampleCountFlags) -> Self { self.sample_count = sample_count; self } pub fn add_target_info(mut self, target: CustomTarget) -> Self { self.target_infos.push(target); self } pub fn set_prepared_targets( mut self, prepared_targets: &'a [Arc<Image>], target_index: usize, clear_color: impl Into<[f32; 4]>, clear_on_load: bool, ) -> Self { self.prepared_targets = Some(( prepared_targets, target_index, clear_color.into(), clear_on_load, )); self } pub fn set_resolve_targets(mut self, resolve_targets: &'a [Arc<Image>]) -> Self { self.resolve_targets = Some(resolve_targets); self } pub fn build( self, device: &Arc<Device>, queue: &Arc<Mutex<Queue>>, ) -> VerboseResult<RenderTarget> { let (render_pass, images, clear_values) = self.create_images_and_renderpass(device, queue)?; let mut framebuffers = Vec::new(); match (self.resolve_targets, self.prepared_targets) { (Some(resolve_targets), Some((prepared_targets, index, _, _))) => { debug_assert!(prepared_targets.len() == resolve_targets.len()); for (i, resolve_target) in resolve_targets.iter().enumerate() { let ref_images = Self::insert_prepared_target(&images, &prepared_targets[i], index); let mut framebuffer_builder = Framebuffer::builder() .set_render_pass(&render_pass) .set_width(self.width) .set_height(self.height); for ref_image in ref_images { framebuffer_builder = framebuffer_builder.add_attachment(ref_image); } let framebuffer = framebuffer_builder .add_attachment(resolve_target) .build(device.clone())?; framebuffers.push(framebuffer); } } (Some(resolve_targets), None) => { for resolve_target in resolve_targets { let mut framebuffer_builder = Framebuffer::builder() .set_render_pass(&render_pass) .set_width(self.width) .set_height(self.height); for image in &images { framebuffer_builder = framebuffer_builder.add_attachment(image); } let framebuffer = framebuffer_builder .add_attachment(&resolve_target) .build(device.clone())?; framebuffers.push(framebuffer); } } (None, Some((prepared_targets, index, _, _))) => { for prepared_target in prepared_targets { let ref_images = Self::insert_prepared_target(&images, &prepared_target, index); let mut framebuffer_builder = Framebuffer::builder() .set_render_pass(&render_pass) .set_width(self.width) .set_height(self.height); for image in &ref_images { framebuffer_builder = framebuffer_builder.add_attachment(image); } let framebuffer = framebuffer_builder.build(device.clone())?; framebuffers.push(framebuffer); } } (None, None) => { let mut framebuffer_builder = Framebuffer::builder() .set_render_pass(&render_pass) .set_width(self.width) .set_height(self.height); for image in &images { framebuffer_builder = framebuffer_builder.add_attachment(image); } let framebuffer = framebuffer_builder.build(device.clone())?; framebuffers.push(framebuffer); } } Ok(RenderTarget { render_pass, framebuffers, images, extent: VkExtent2D { width: self.width, height: self.height, }, clear_values, }) } } pub struct RenderTarget { render_pass: Arc<RenderPass>, framebuffers: Vec<Arc<Framebuffer>>, images: Vec<Arc<Image>>, extent: VkExtent2D, clear_values: Vec<VkClearValue>, } impl RenderTarget { pub fn new<'a>(width: u32, height: u32) -> RenderTargetBuilder<'a> { RenderTargetBuilder { width, height, sample_count: VK_SAMPLE_COUNT_1_BIT, target_infos: Vec::new(), prepared_targets: None, resolve_targets: None, } } pub fn render_pass(&self) -> &Arc<RenderPass> { &self.render_pass } pub fn framebuffer(&self, index: usize) -> &Arc<Framebuffer> { &self.framebuffers[index] } pub fn images(&self) -> &Vec<Arc<Image>> { &self.images } pub fn width(&self) -> u32 { self.extent.width } pub fn height(&self) -> u32 { self.extent.height } pub fn begin( &self, command_buffer: &Arc<CommandBuffer>, subpass_content: VkSubpassContents, framebuffer_index: usize, ) { let renderpass_begin = VkRenderPassBeginInfo::new( self.render_pass.vk_handle(), self.framebuffers[framebuffer_index].vk_handle(), VkRect2D { offset: VkOffset2D { x: 0, y: 0 }, extent: self.extent, }, self.clear_values.as_slice(), ); command_buffer.begin_render_pass(renderpass_begin, subpass_content); } pub fn end(&self, command_buffer: &Arc<CommandBuffer>) { command_buffer.end_render_pass(); } } impl<'a> RenderTargetBuilder<'a> { fn insert_prepared_target<'b>( images: &'b [Arc<Image>], prepared_target: &'b Arc<Image>, index: usize, ) -> Vec<&'b Arc<Image>> { let mut ref_images = Vec::new(); for image in images.iter() { ref_images.push(image); } ref_images.insert(index, prepared_target); ref_images } fn create_images_and_renderpass( &self, device: &Arc<Device>, queue: &Arc<Mutex<Queue>>, ) -> VerboseResult<(Arc<RenderPass>, Vec<Arc<Image>>, Vec<VkClearValue>)> { // check for correct sample count let checked_sample_count = device.max_supported_sample_count(self.sample_count); // throw an error if we don't use muultisampling and have an resolve target if checked_sample_count == VK_SAMPLE_COUNT_1_BIT && self.resolve_targets.is_some() { create_error!("Sample count 1 and using resolve target is not supported"); } let mut images = Vec::new(); let mut clear_values = Vec::new(); // init values for renderpass let mut color_references = Vec::new(); let mut resolve_reference = None; let mut depth_reference = None; let mut attachments = Vec::new(); let mut attachment_count = 0; for target_info in self.target_infos.iter() { let clear_operation = Self::clear_op(target_info.clear_on_load); let store_operation = Self::store_op(target_info.store_on_save); // push clear values match target_info.clear_value { ClearValue::Color(color) => { clear_values.push(VkClearValue::color(VkClearColorValue::float32(color))) } ClearValue::Depth(depth, stencil) => { clear_values.push(VkClearValue::depth_stencil(VkClearDepthStencilValue { depth, stencil, })) } }; if let Some((_, index, _, _)) = self.prepared_targets { if index as u32 == attachment_count { attachment_count += 1; } } // check for color attachment flag let (format, aspect) = if (target_info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0 { // add color attachment attachments.push(VkAttachmentDescription::new( 0, target_info.format, self.sample_count, clear_operation, store_operation, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_UNDEFINED, if target_info.attach_sampler { VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL } else { VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }, )); // add color reference color_references.push(VkAttachmentReference { attachment: attachment_count, layout: VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }); attachment_count += 1; // take format and aspect mask (target_info.format, VK_IMAGE_ASPECT_COLOR_BIT) // check for depth attachment flag } else if (target_info.usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0 { // set depth reference if depth_reference.is_some() { create_error!("more than one depth attachment is not allowed!"); } // add depth attachment attachments.push(VkAttachmentDescription::new( 0, target_info.format, self.sample_count, clear_operation, store_operation, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, )); depth_reference = Some(VkAttachmentReference { attachment: attachment_count, layout: VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, }); attachment_count += 1; // take format and aspect mask (target_info.format, VK_IMAGE_ASPECT_DEPTH_BIT) } else { // TODO: add more as required unimplemented!(); }; let mut image_builder = Image::empty( self.width, self.height, target_info.usage, self.sample_count, ) .format(format) .aspect_mask(aspect) .memory_properties(0); if target_info.attach_sampler { image_builder = image_builder.attach_sampler(Sampler::nearest_sampler().build(device)?); } let image = image_builder.build(device, queue)?; match aspect { VK_IMAGE_ASPECT_DEPTH_BIT => { Image::convert_layout(&image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL)? } VK_IMAGE_ASPECT_COLOR_BIT => { Image::convert_layout(&image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)? } _ => unimplemented!(), } images.push(image); } // insert prepared images if let Some((prepared_images, index, clear_color, clear_on_load)) = self.prepared_targets { // assume prepared images are always color attachments clear_values.insert( index, VkClearValue::color(VkClearColorValue::float32(clear_color)), ); let clear_operation = Self::clear_op(clear_on_load); // add color attachment attachments.insert( index, VkAttachmentDescription::new( 0, prepared_images[0].vk_format(), VK_SAMPLE_COUNT_1_BIT, clear_operation, VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, prepared_images[0].image_layout()?, prepared_images[0].image_layout()?, ), ); // add color reference color_references.insert( index, VkAttachmentReference { attachment: index as u32, layout: VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }, ); attachment_count += 1; } // add resolve target if possible if let Some(resolve_targets) = self.resolve_targets { // push color clear values clear_values.push(VkClearValue::color(VkClearColorValue::float32([ 0.0, 0.0, 0.0, 1.0, ]))); // add color attachment attachments.push(VkAttachmentDescription::new( 0, resolve_targets[0].vk_format(), VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, resolve_targets[0].image_layout()?, resolve_targets[0].image_layout()?, )); resolve_reference = Some(VkAttachmentReference { attachment: attachment_count, layout: resolve_targets[0].image_layout()?, }); } let subpass_descriptions = [match resolve_reference { Some(resvole_ref) => VkSubpassDescription::new( 0, &[], color_references.as_slice(), &[resvole_ref], match depth_reference { Some(ref depth_ref) => Some(depth_ref), None => None, }, &[], ), None => VkSubpassDescription::new( 0, &[], color_references.as_slice(), &[], match depth_reference { Some(ref depth_ref) => Some(depth_ref), None => None, }, &[], ), }]; let dependencies = if color_references.is_empty() { // assume, that when no color references are given, // we want to store the depth information for later if depth_reference.is_some() { for attachment in &mut attachments { if attachment.format == VK_FORMAT_D16_UNORM { attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; break; } } } [ VkSubpassDependency::new( VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, 0, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_DEPENDENCY_BY_REGION_BIT, ), VkSubpassDependency::new( 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_DEPENDENCY_BY_REGION_BIT, ), ] } else { [ VkSubpassDependency::new( VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_DEPENDENCY_BY_REGION_BIT, ), VkSubpassDependency::new( 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT, VK_DEPENDENCY_BY_REGION_BIT, ), ] }; let renderpass = RenderPass::new( device.clone(), &subpass_descriptions, attachments.as_slice(), &dependencies, )?; Ok((renderpass, images, clear_values)) } #[inline] fn clear_op(clear_on_load: bool) -> VkAttachmentLoadOp { if clear_on_load { VK_ATTACHMENT_LOAD_OP_CLEAR } else { VK_ATTACHMENT_LOAD_OP_LOAD } } #[inline] fn store_op(store_on_save: bool) -> VkAttachmentStoreOp { if store_on_save { VK_ATTACHMENT_STORE_OP_STORE } else { VK_ATTACHMENT_STORE_OP_DONT_CARE } } }
use apilib::transfer::Transfer; use serde::Serialize; use serde::Deserialize; #[derive(Debug, Serialize, Deserialize, Clone)] pub enum TResponse<T: Transfer> { Ok(T), Err(u16, String), } impl<'de, T: Transfer + Serialize + Deserialize<'de>> TResponse<T> { pub fn ok(value: T) -> Self { TResponse::Ok(value) } // maybe 'code' should be an enum to only allow valid http codes pub fn err(code: u16, message: String) -> Self { TResponse::Err(code, message) } } impl<'de, T: Transfer + Serialize + Deserialize<'de>> Transfer for TResponse<T> { fn clean(self) -> Self { match self { TResponse::Ok(value) => TResponse::Ok(value.clean()), err => err, } } } // TODO @mverleg: I would like to use derive so I don't have to type this impl<T> PartialEq for TResponse<T> where T: Transfer + PartialEq { fn eq(&self, other: &TResponse<T>) -> bool { match (self, other) { (TResponse::Ok(sok), TResponse::Ok(ook)) => sok == ook, (TResponse::Ok(_), TResponse::Err(_, _)) => false, (TResponse::Err(_, _), TResponse::Ok(_)) => false, (TResponse::Err(sec, ser), TResponse::Err(oec, oer)) => sec == oec && ser == oer, } } }
fn main() { println!("Hello, world!"); println!("{}", another_function(4)); } fn another_function(x: i32) -> i32 { let test = [1,2,3,4]; for i in test.iter() { println!("{}", i); } for j in (1..4).rev() { println!("{}", j); } x + 4 }
mod interp; use interp::LLVMIRInterpreter; use llvm_ir::Module; use std::env; fn main() { let args: Vec<String> = env::args().collect(); match create_module(&args[1]) { Ok(module) => { let mut lii = LLVMIRInterpreter::new(module); match lii.interpret() { Ok(_) => {} Err(str) => println!("{}", str), } } Err(error_message) => println!("{}", error_message), }; } fn create_module(path_s: &str) -> Result<Module, String> { Module::from_bc_path(path_s) }
use std::io::{self, Write}; use varisat_formula::Lit; use varisat_internal_proof::ProofStep; /// Prepares a proof step for DRAT writing fn drat_step( step: &ProofStep, mut emit_drat_step: impl FnMut(bool, &[Lit]) -> io::Result<()>, ) -> io::Result<()> { match step { ProofStep::AtClause { clause, .. } => { emit_drat_step(true, &clause)?; } ProofStep::UnitClauses { units } => { for &(unit, _hash) in units.iter() { emit_drat_step(true, &[unit])?; } } ProofStep::DeleteClause { clause, .. } => { emit_drat_step(false, &clause[..])?; } ProofStep::SolverVarName { .. } | ProofStep::UserVarName { .. } | ProofStep::DeleteVar { .. } | ProofStep::ChangeSamplingMode { .. } | ProofStep::ChangeHashBits { .. } | ProofStep::Model { .. } | ProofStep::End => (), ProofStep::AddClause { .. } => { // TODO allow error handling here? panic!("incremental clause additions not supported by DRAT proofs"); } ProofStep::Assumptions { .. } | ProofStep::FailedAssumptions { .. } => { // TODO allow error handling here? panic!("assumptions not supported by DRAT proofs"); } } Ok(()) } /// Writes a proof step in DRAT format pub fn write_step<'s>(target: &mut impl Write, step: &'s ProofStep<'s>) -> io::Result<()> { drat_step(step, |add, clause| { if !add { target.write_all(b"d ")?; } write_literals(target, &clause[..])?; Ok(()) }) } /// Writes a proof step in binary DRAT format pub fn write_binary_step<'s>(target: &mut impl Write, step: &'s ProofStep<'s>) -> io::Result<()> { drat_step(step, |add, clause| { if add { target.write_all(b"a")?; } else { target.write_all(b"d")?; } write_binary_literals(target, &clause[..])?; Ok(()) }) } /// Writes the literals of a clause for a step in a DRAT proof. fn write_literals(target: &mut impl Write, literals: &[Lit]) -> io::Result<()> { for &lit in literals { itoa::write(&mut *target, lit.to_dimacs())?; target.write_all(b" ")?; } target.write_all(b"0\n")?; Ok(()) } /// Writes the literals of a clause for a step in a binary DRAT proof. fn write_binary_literals(target: &mut impl Write, literals: &[Lit]) -> io::Result<()> { for &lit in literals { let drat_code = lit.code() as u64 + 2; leb128::write::unsigned(target, drat_code)?; } target.write_all(&[0])?; Ok(()) }
use std::collections::BTreeMap; use std::path::PathBuf; use std::str::FromStr; #[cfg(feature = "offline")] use std::sync::{Arc, Mutex}; use once_cell::sync::Lazy; use proc_macro2::TokenStream; use syn::Type; pub use input::QueryMacroInput; use quote::{format_ident, quote}; use sqlx_core::connection::Connection; use sqlx_core::database::Database; use sqlx_core::{column::Column, describe::Describe, type_info::TypeInfo}; use sqlx_rt::{block_on, AsyncMutex}; use crate::database::DatabaseExt; use crate::query::data::QueryData; use crate::query::input::RecordType; use either::Either; mod args; mod data; mod input; mod output; struct Metadata { #[allow(unused)] manifest_dir: PathBuf, offline: bool, database_url: Option<String>, #[cfg(feature = "offline")] package_name: String, #[cfg(feature = "offline")] target_dir: PathBuf, #[cfg(feature = "offline")] workspace_root: Arc<Mutex<Option<PathBuf>>>, } #[cfg(feature = "offline")] impl Metadata { pub fn workspace_root(&self) -> PathBuf { let mut root = self.workspace_root.lock().unwrap(); if root.is_none() { use serde::Deserialize; use std::process::Command; let cargo = env("CARGO").expect("`CARGO` must be set"); let output = Command::new(&cargo) .args(&["metadata", "--format-version=1", "--no-deps"]) .current_dir(&self.manifest_dir) .env_remove("__CARGO_FIX_PLZ") .output() .expect("Could not fetch metadata"); #[derive(Deserialize)] struct CargoMetadata { workspace_root: PathBuf, } let metadata: CargoMetadata = serde_json::from_slice(&output.stdout).expect("Invalid `cargo metadata` output"); *root = Some(metadata.workspace_root); } root.clone().unwrap() } } // If we are in a workspace, lookup `workspace_root` since `CARGO_MANIFEST_DIR` won't // reflect the workspace dir: https://github.com/rust-lang/cargo/issues/3946 static METADATA: Lazy<Metadata> = Lazy::new(|| { let manifest_dir: PathBuf = env("CARGO_MANIFEST_DIR") .expect("`CARGO_MANIFEST_DIR` must be set") .into(); #[cfg(feature = "offline")] let package_name: String = env("CARGO_PKG_NAME") .expect("`CARGO_PKG_NAME` must be set") .into(); #[cfg(feature = "offline")] let target_dir = env("CARGO_TARGET_DIR").map_or_else(|_| "target".into(), |dir| dir.into()); // If a .env file exists at CARGO_MANIFEST_DIR, load environment variables from this, // otherwise fallback to default dotenv behaviour. let env_path = manifest_dir.join(".env"); #[cfg_attr(not(procmacro2_semver_exempt), allow(unused_variables))] let env_path = if env_path.exists() { let res = dotenvy::from_path(&env_path); if let Err(e) = res { panic!("failed to load environment from {:?}, {}", env_path, e); } Some(env_path) } else { dotenvy::dotenv().ok() }; // tell the compiler to watch the `.env` for changes, if applicable #[cfg(procmacro2_semver_exempt)] if let Some(env_path) = env_path.as_ref().and_then(|path| path.to_str()) { proc_macro::tracked_path::path(env_path); } let offline = env("SQLX_OFFLINE") .map(|s| s.eq_ignore_ascii_case("true") || s == "1") .unwrap_or(false); let database_url = env("DATABASE_URL").ok(); Metadata { manifest_dir, offline, database_url, #[cfg(feature = "offline")] package_name, #[cfg(feature = "offline")] target_dir, #[cfg(feature = "offline")] workspace_root: Arc::new(Mutex::new(None)), } }); pub fn expand_input(input: QueryMacroInput) -> crate::Result<TokenStream> { match &*METADATA { #[cfg(not(any( feature = "postgres", feature = "mysql", feature = "mssql", feature = "sqlite" )))] Metadata { offline: false, database_url: Some(db_url), .. } => Err( "At least one of the features ['postgres', 'mysql', 'mssql', 'sqlite'] must be enabled \ to get information directly from a database" .into(), ), #[cfg(any( feature = "postgres", feature = "mysql", feature = "mssql", feature = "sqlite" ))] Metadata { offline: false, database_url: Some(db_url), .. } => expand_from_db(input, &db_url), #[cfg(feature = "offline")] _ => { let data_file_path = METADATA.manifest_dir.join("sqlx-data.json"); if data_file_path.exists() { expand_from_file(input, data_file_path) } else { let workspace_data_file_path = METADATA.workspace_root().join("sqlx-data.json"); if workspace_data_file_path.exists() { expand_from_file(input, workspace_data_file_path) } else { Err( "`DATABASE_URL` must be set, or `cargo sqlx prepare` must have been run \ and sqlx-data.json must exist, to use query macros" .into(), ) } } } #[cfg(not(feature = "offline"))] Metadata { offline: true, .. } => { Err("The cargo feature `offline` has to be enabled to use `SQLX_OFFLINE`".into()) } #[cfg(not(feature = "offline"))] Metadata { offline: false, database_url: None, .. } => Err("`DATABASE_URL` must be set to use query macros".into()), } } #[cfg(any( feature = "postgres", feature = "mysql", feature = "mssql", feature = "sqlite" ))] fn expand_from_db(input: QueryMacroInput, db_url: &str) -> crate::Result<TokenStream> { use sqlx_core::any::{AnyConnectOptions, AnyConnection}; let connect_opts = AnyConnectOptions::from_str(db_url)?; // SQLite is not used in the connection cache due to issues with newly created // databases seemingly being locked for several seconds when journaling is off. This // isn't a huge issue since the intent of the connection cache was to make connections // to remote databases much faster. Relevant links: // - https://github.com/launchbadge/sqlx/pull/1782#issuecomment-1089226716 // - https://github.com/launchbadge/sqlx/issues/1929 #[cfg(feature = "sqlite")] if let Some(sqlite_opts) = connect_opts.as_sqlite() { // Since proc-macros don't benefit from async, we can make a describe call directly // which also ensures that the database is closed afterwards, regardless of errors. let describe = sqlx_core::sqlite::describe_blocking(sqlite_opts, &input.sql)?; let data = QueryData::from_describe(&input.sql, describe); return expand_with_data(input, data, false); } block_on(async { static CONNECTION_CACHE: Lazy<AsyncMutex<BTreeMap<String, AnyConnection>>> = Lazy::new(|| AsyncMutex::new(BTreeMap::new())); let mut cache = CONNECTION_CACHE.lock().await; if !cache.contains_key(db_url) { let conn = AnyConnection::connect_with(&connect_opts).await?; let _ = cache.insert(db_url.to_owned(), conn); } let conn_item = cache.get_mut(db_url).expect("Item was just inserted"); match conn_item.private_get_mut() { #[cfg(feature = "postgres")] sqlx_core::any::AnyConnectionKind::Postgres(conn) => { let data = QueryData::from_db(conn, &input.sql).await?; expand_with_data(input, data, false) } #[cfg(feature = "mssql")] sqlx_core::any::AnyConnectionKind::Mssql(conn) => { let data = QueryData::from_db(conn, &input.sql).await?; expand_with_data(input, data, false) } #[cfg(feature = "mysql")] sqlx_core::any::AnyConnectionKind::MySql(conn) => { let data = QueryData::from_db(conn, &input.sql).await?; expand_with_data(input, data, false) } // Variants depend on feature flags #[allow(unreachable_patterns)] item => { return Err(format!("Missing expansion needed for: {:?}", item).into()); } } }) } #[cfg(feature = "offline")] pub fn expand_from_file(input: QueryMacroInput, file: PathBuf) -> crate::Result<TokenStream> { use data::offline::DynQueryData; let query_data = DynQueryData::from_data_file(file, &input.sql)?; assert!(!query_data.db_name.is_empty()); match &*query_data.db_name { #[cfg(feature = "postgres")] sqlx_core::postgres::Postgres::NAME => expand_with_data( input, QueryData::<sqlx_core::postgres::Postgres>::from_dyn_data(query_data)?, true, ), #[cfg(feature = "mysql")] sqlx_core::mysql::MySql::NAME => expand_with_data( input, QueryData::<sqlx_core::mysql::MySql>::from_dyn_data(query_data)?, true, ), #[cfg(feature = "sqlite")] sqlx_core::sqlite::Sqlite::NAME => expand_with_data( input, QueryData::<sqlx_core::sqlite::Sqlite>::from_dyn_data(query_data)?, true, ), _ => Err(format!( "found query data for {} but the feature for that database was not enabled", query_data.db_name ) .into()), } } // marker trait for `Describe` that lets us conditionally require it to be `Serialize + Deserialize` #[cfg(feature = "offline")] trait DescribeExt: serde::Serialize + serde::de::DeserializeOwned {} #[cfg(feature = "offline")] impl<DB: Database> DescribeExt for Describe<DB> where Describe<DB>: serde::Serialize + serde::de::DeserializeOwned { } #[cfg(not(feature = "offline"))] trait DescribeExt {} #[cfg(not(feature = "offline"))] impl<DB: Database> DescribeExt for Describe<DB> {} fn expand_with_data<DB: DatabaseExt>( input: QueryMacroInput, data: QueryData<DB>, #[allow(unused_variables)] offline: bool, ) -> crate::Result<TokenStream> where Describe<DB>: DescribeExt, { // validate at the minimum that our args match the query's input parameters let num_parameters = match data.describe.parameters() { Some(Either::Left(params)) => Some(params.len()), Some(Either::Right(num)) => Some(num), None => None, }; if let Some(num) = num_parameters { if num != input.arg_exprs.len() { return Err( format!("expected {} parameters, got {}", num, input.arg_exprs.len()).into(), ); } } let args_tokens = args::quote_args(&input, &data.describe)?; let query_args = format_ident!("query_args"); let output = if data .describe .columns() .iter() .all(|it| it.type_info().is_void()) { let db_path = DB::db_path(); let sql = &input.sql; quote! { ::sqlx::query_with::<#db_path, _>(#sql, #query_args) } } else { match input.record_type { RecordType::Generated => { let columns = output::columns_to_rust::<DB>(&data.describe)?; let record_name: Type = syn::parse_str("Record").unwrap(); for rust_col in &columns { if rust_col.type_.is_wildcard() { return Err( "wildcard overrides are only allowed with an explicit record type, \ e.g. `query_as!()` and its variants" .into(), ); } } let record_fields = columns.iter().map( |&output::RustColumn { ref ident, ref type_, .. }| quote!(#ident: #type_,), ); let mut record_tokens = quote! { #[derive(Debug)] struct #record_name { #(#record_fields)* } }; record_tokens.extend(output::quote_query_as::<DB>( &input, &record_name, &query_args, &columns, )); record_tokens } RecordType::Given(ref out_ty) => { let columns = output::columns_to_rust::<DB>(&data.describe)?; output::quote_query_as::<DB>(&input, out_ty, &query_args, &columns) } RecordType::Scalar => { output::quote_query_scalar::<DB>(&input, &query_args, &data.describe)? } } }; let ret_tokens = quote! { { #[allow(clippy::all)] { use ::sqlx::Arguments as _; #args_tokens #output } } }; // Store query metadata only if offline support is enabled but the current build is online. // If the build is offline, the cache is our input so it's pointless to also write data for it. #[cfg(feature = "offline")] if !offline { // Use a separate sub-directory for each crate in a workspace. This avoids a race condition // where `prepare` can pull in queries from multiple crates if they happen to be generated // simultaneously (e.g. Rust Analyzer building in the background). let save_dir = METADATA .target_dir .join("sqlx") .join(&METADATA.package_name); std::fs::create_dir_all(&save_dir)?; data.save_in(save_dir, input.src_span)?; } Ok(ret_tokens) } /// Get the value of an environment variable, telling the compiler about it if applicable. fn env(name: &str) -> Result<String, std::env::VarError> { #[cfg(procmacro2_semver_exempt)] { proc_macro::tracked_env::var(name) } #[cfg(not(procmacro2_semver_exempt))] { std::env::var(name) } }
use log::*; use crate::instruction::{AccountMeta, Instruction}; use crate::instruction_processor_utils::DecodeError; use crate::pubkey::Pubkey; use crate::system_program; use num_derive::FromPrimitive; use morgan_helper::logHelper::*; #[derive(Serialize, Debug, Clone, PartialEq, FromPrimitive)] pub enum SystemError { AccountAlreadyInUse, ResultWithNegativeDifs, SourceNotSystemAccount, ResultWithNegativeReputations, } impl<T> DecodeError<T> for SystemError { fn type_of(&self) -> &'static str { "SystemError" } } impl std::fmt::Display for SystemError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "error") } } impl std::error::Error for SystemError {} #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum SystemInstruction { /// Create a new account /// * Transaction::keys[0] - source /// * Transaction::keys[1] - new account key /// * difs - number of difs to transfer to the new account /// * space - memory to allocate if greater then zero /// * program_id - the program id of the new account CreateAccount { difs: u64, reputations: u64, space: u64, program_id: Pubkey, }, /// Assign account to a program /// * Transaction::keys[0] - account to assign Assign { program_id: Pubkey }, /// Transfer difs /// * Transaction::keys[0] - source /// * Transaction::keys[1] - destination Transfer { difs: u64 }, /// Create a new account /// * Transaction::keys[0] - source /// * Transaction::keys[1] - new account key /// * reputations - number of reputations to transfer to the new account /// * space - memory to allocate if greater then zero /// * program_id - the program id of the new account CreateAccountWithReputation { reputations: u64, space: u64, program_id: Pubkey, }, /// Transfer reputations /// * Transaction::keys[0] - source /// * Transaction::keys[1] - destination TransferReputations { reputations: u64 }, } pub fn create_account( from_pubkey: &Pubkey, to_pubkey: &Pubkey, difs: u64, space: u64, program_id: &Pubkey, ) -> Instruction { let account_metas = vec![ AccountMeta::new(*from_pubkey, true), AccountMeta::new(*to_pubkey, false), ]; let reputations = 0; Instruction::new( system_program::id(), &SystemInstruction::CreateAccount { difs, reputations, space, program_id: *program_id, }, account_metas, ) } pub fn create_account_with_reputation( from_pubkey: &Pubkey, to_pubkey: &Pubkey, reputations: u64, space: u64, program_id: &Pubkey, ) -> Instruction { let account_metas = vec![ AccountMeta::new(*from_pubkey, true), AccountMeta::new(*to_pubkey, false), ]; // info!("{}", Info(format!("create_account_with_reputation: {:?}", account_metas).to_string())); println!("{}", printLn( format!("create_account_with_reputation: {:?}", account_metas).to_string(), module_path!().to_string() ) ); Instruction::new( system_program::id(), &SystemInstruction::CreateAccountWithReputation { reputations, space, program_id: *program_id, }, account_metas, ) } /// Create and sign a transaction to create a system account pub fn create_user_account(from_pubkey: &Pubkey, to_pubkey: &Pubkey, difs: u64) -> Instruction { let program_id = system_program::id(); create_account(from_pubkey, to_pubkey, difs, 0, &program_id) } /// Create and sign a transaction to create a system account with reputation pub fn create_user_account_with_reputation(from_pubkey: &Pubkey, to_pubkey: &Pubkey, reputations: u64) -> Instruction { let program_id = system_program::id(); // info!("{}", Info(format!("create_user_account_with_reputation to : {:?}", to_pubkey).to_string())); println!("{}", printLn( format!("create_user_account_with_reputation to : {:?}", to_pubkey).to_string(), module_path!().to_string() ) ); create_account_with_reputation(from_pubkey, to_pubkey, reputations, 0, &program_id) } pub fn assign(from_pubkey: &Pubkey, program_id: &Pubkey) -> Instruction { let account_metas = vec![AccountMeta::new(*from_pubkey, true)]; Instruction::new( system_program::id(), &SystemInstruction::Assign { program_id: *program_id, }, account_metas, ) } pub fn transfer(from_pubkey: &Pubkey, to_pubkey: &Pubkey, difs: u64) -> Instruction { let account_metas = vec![ AccountMeta::new(*from_pubkey, true), AccountMeta::new(*to_pubkey, false), ]; Instruction::new( system_program::id(), &SystemInstruction::Transfer { difs }, account_metas, ) } pub fn transfer_reputations(from_pubkey: &Pubkey, to_pubkey: &Pubkey, reputations: u64) -> Instruction { let account_metas = vec![ AccountMeta::new(*from_pubkey, true), AccountMeta::new(*to_pubkey, false), ]; Instruction::new( system_program::id(), &SystemInstruction::TransferReputations { reputations }, account_metas, ) } /// Create and sign new SystemInstruction::Transfer transaction to many destinations pub fn transfer_many(from_pubkey: &Pubkey, to_difs: &[(Pubkey, u64)]) -> Vec<Instruction> { to_difs .iter() .map(|(to_pubkey, difs)| transfer(from_pubkey, to_pubkey, *difs)) .collect() } #[cfg(test)] mod tests { use super::*; fn get_keys(instruction: &Instruction) -> Vec<Pubkey> { instruction.accounts.iter().map(|x| x.pubkey).collect() } #[test] fn test_move_many() { let alice_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand(); let carol_pubkey = Pubkey::new_rand(); let to_difs = vec![(bob_pubkey, 1), (carol_pubkey, 2)]; let instructions = transfer_many(&alice_pubkey, &to_difs); assert_eq!(instructions.len(), 2); assert_eq!(get_keys(&instructions[0]), vec![alice_pubkey, bob_pubkey]); assert_eq!(get_keys(&instructions[1]), vec![alice_pubkey, carol_pubkey]); } }
use crate::model::{project::Project, user::User}; pub enum MyError { NotFound, DatabaseError, } #[derive(Deserialize, Serialize, Debug)] pub struct Msgs { pub status: i32, pub message: String, } #[derive(Deserialize, Serialize, Debug)] pub struct UserMsgs { pub status: i32, pub message: String, pub user: User, } #[derive(Deserialize, Serialize, Debug)] pub struct SigninMsgs { pub status: i32, pub token: String, pub signin_user: User, pub message: String, } #[derive(Deserialize, Serialize, Debug)] pub struct ProjectInfoMsgs { pub status: i32, pub project: Project, pub message: String, }
/* * @lc app=leetcode.cn id=69 lang=rust * * [69] x 的平方根 * * https://leetcode-cn.com/problems/sqrtx/description/ * * algorithms * Easy (34.96%) * Total Accepted: 28.2K * Total Submissions: 80.2K * Testcase Example: '4' * * 实现 int sqrt(int x) 函数。 * * 计算并返回 x 的平方根,其中 x 是非负整数。 * * 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 * * 示例 1: * * 输入: 4 * 输出: 2 * * * 示例 2: * * 输入: 8 * 输出: 2 * 说明: 8 的平方根是 2.82842..., * 由于返回类型是整数,小数部分将被舍去。 * * */ impl Solution { pub fn my_sqrt(x: i32) -> i32 { if x < 0 { unreachable!(); } if x <= 1 { return x; } let mut i = 0; let mut j = x; while i + 1 < j { let mid = (i + j) / 2; if mid == x / mid { return mid; } if mid > x / mid { j = mid; } else { i = mid; } } i } } fn main() { vec![80, 82, 1, 0, 5, 10, 2147395599].iter().for_each(|it| { assert_eq!(f64::sqrt(*it as f64) as i32, Solution::my_sqrt(*it)); }); } struct Solution {}
use super::ema::series_ema; use super::sma::{declare_ma_var, wma_func}; use super::tr::tr_func; use super::VarResult; use crate::ast::stat_expr_types::VarIndex; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType}; use crate::helper::err_msgs::*; use crate::helper::str_replace; use crate::helper::{ ensure_srcs, move_element, pine_ref_to_bool, pine_ref_to_f64, pine_ref_to_f64_series, pine_ref_to_i64, require_param, }; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::InputSrc; use crate::types::{ downcast_pf_ref, int2float, Arithmetic, Callable, CallableCreator, CallableFactory, Evaluate, EvaluateVal, Float, Int, ParamCollectCall, PineRef, RefData, RuntimeErr, Series, SeriesCall, Tuple, }; use std::mem; use std::rc::Rc; pub type ValGenerator<'a> = fn((Float, Float, Float)) -> PineRef<'a>; fn val_generator<'a>(vals: (Float, Float, Float)) -> PineRef<'a> { let (basis, ema1, ema2) = vals; PineRef::new(Tuple(vec![ PineRef::new_rc(Series::from(basis)), PineRef::new_rc(Series::from(ema1)), PineRef::new_rc(Series::from(ema2)), ])) } #[derive(Debug, Clone, PartialEq)] pub struct KcVal<'a> { ema1s: Series<'a, Float>, ema2s: Series<'a, Float>, dems: Series<'a, Float>, } impl<'a> KcVal<'a> { pub fn new() -> KcVal<'a> { KcVal { ema1s: Series::new(), ema2s: Series::new(), dems: Series::new(), } } fn process_macd( &mut self, _ctx: &mut dyn Ctx<'a>, mut param: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<(Float, Float, Float), RuntimeErr> { move_tuplet!((source, fastlen, slowlen, siglen) = param); let close = pine_ref_to_f64(source); let fastlen = require_param("fastlen", pine_ref_to_i64(fastlen))?; let slowlen = require_param("slowlen", pine_ref_to_i64(slowlen))?; let siglen = require_param("siglen", pine_ref_to_i64(siglen))?; let ema1 = series_ema(close, fastlen, &mut self.ema1s)?; let ema2 = series_ema(close, slowlen, &mut self.ema2s)?; let dif = ema1.minus(ema2); let dem = series_ema(dif, siglen, &mut self.dems)?; let osc = dif.minus(dem); self.ema1s.commit(); self.ema2s.commit(); self.dems.commit(); Ok((dif, dem, osc)) } } impl<'a> SeriesCall<'a> for KcVal<'a> { fn step( &mut self, _ctx: &mut dyn Ctx<'a>, param: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { Ok(val_generator(self.process_macd(_ctx, param, _func_type)?)) } fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> { Box::new(self.clone()) } } pub fn declare_var<'a>() -> VarResult<'a> { let value = PineRef::new(CallableFactory::new(|| { Callable::new( None, Some(Box::new(ParamCollectCall::new_with_caller(Box::new( KcVal::new(), )))), ) })); let func_type = FunctionTypes(vec![FunctionType::new(( vec![ ("source", SyntaxType::float_series()), ("fastlen", SyntaxType::int()), ("slowlen", SyntaxType::int()), ("siglen", SyntaxType::int()), ], SyntaxType::Tuple(Rc::new(vec![ SyntaxType::float_series(), SyntaxType::float_series(), SyntaxType::float_series(), ])), ))]); let syntax_type = SyntaxType::Function(Rc::new(func_type)); VarResult::new(value, syntax_type, "macd") } #[cfg(test)] mod tests { use super::*; use crate::ast::syntax_type::SyntaxType; use crate::runtime::VarOperate; use crate::runtime::{AnySeries, NoneCallback}; use crate::types::Series; use crate::{LibInfo, PineParser, PineRunner}; // use crate::libs::{floor, exp, }; #[test] fn alma_test() { let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::float_series())], ); let src = "[m1, m2, m3] = macd(close, 12, 26, 9)\n"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![( "close", AnySeries::from_float_vec(vec![Some(10f64), Some(20f64)]), )], None, ) .unwrap(); // assert_eq!( // runner.get_context().move_var(VarIndex::new(2, 0)), // Some(PineRef::new(Series::from_vec(vec![ // Some(5f64), // Some(12.5f64) // ]))) // ); } }
// 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 common_base::base::GlobalInstance; use common_config::InnerConfig; use common_exception::Result; use common_tracing::set_panic_hook; use databend_query::clusters::ClusterDiscovery; use databend_query::GlobalServices; use tracing::info; pub struct TestGlobalServices; unsafe impl Send for TestGlobalServices {} unsafe impl Sync for TestGlobalServices {} impl TestGlobalServices { pub async fn setup(config: InnerConfig) -> Result<TestGuard> { set_panic_hook(); std::env::set_var("UNIT_TEST", "TRUE"); let thread_name = match std::thread::current().name() { None => panic!("thread name is none"), Some(thread_name) => thread_name.to_string(), }; GlobalInstance::init_testing(&thread_name); GlobalServices::init_with(config.clone()).await?; // Cluster register. { ClusterDiscovery::instance() .register_to_metastore(&config) .await?; info!( "Databend query has been registered:{:?} to metasrv:{:?}.", config.query.cluster_id, config.meta.endpoints ); } Ok(TestGuard { thread_name: thread_name.to_string(), }) } } pub struct TestGuard { thread_name: String, } impl Drop for TestGuard { fn drop(&mut self) { GlobalInstance::drop_testing(&self.thread_name); } }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_create_api( input: &crate::input::CreateApiInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_api_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_api_mapping( input: &crate::input::CreateApiMappingInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_api_mapping_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_authorizer( input: &crate::input::CreateAuthorizerInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_authorizer_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_deployment( input: &crate::input::CreateDeploymentInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_deployment_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_domain_name( input: &crate::input::CreateDomainNameInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_domain_name_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_integration( input: &crate::input::CreateIntegrationInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_integration_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_integration_response( input: &crate::input::CreateIntegrationResponseInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_integration_response_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_model( input: &crate::input::CreateModelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_model_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_route( input: &crate::input::CreateRouteInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_route_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_route_response( input: &crate::input::CreateRouteResponseInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_route_response_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_stage( input: &crate::input::CreateStageInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_stage_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_create_vpc_link( input: &crate::input::CreateVpcLinkInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_vpc_link_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_import_api( input: &crate::input::ImportApiInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_import_api_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_reimport_api( input: &crate::input::ReimportApiInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_reimport_api_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_tag_resource( input: &crate::input::TagResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_tag_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_api( input: &crate::input::UpdateApiInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_api_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_api_mapping( input: &crate::input::UpdateApiMappingInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_api_mapping_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_authorizer( input: &crate::input::UpdateAuthorizerInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_authorizer_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_deployment( input: &crate::input::UpdateDeploymentInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_deployment_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_domain_name( input: &crate::input::UpdateDomainNameInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_domain_name_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_integration( input: &crate::input::UpdateIntegrationInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_integration_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_integration_response( input: &crate::input::UpdateIntegrationResponseInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_integration_response_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_model( input: &crate::input::UpdateModelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_model_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_route( input: &crate::input::UpdateRouteInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_route_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_route_response( input: &crate::input::UpdateRouteResponseInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_route_response_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_stage( input: &crate::input::UpdateStageInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_stage_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_update_vpc_link( input: &crate::input::UpdateVpcLinkInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_update_vpc_link_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn NetDfsAdd(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, comment: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsAddFtRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, ftdfsname: super::super::Foundation::PWSTR, comment: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsAddRootTarget(pdfspath: super::super::Foundation::PWSTR, ptargetpath: super::super::Foundation::PWSTR, majorversion: u32, pcomment: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsAddStdRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, comment: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsEnum(dfsname: super::super::Foundation::PWSTR, level: u32, prefmaxlen: u32, buffer: *mut *mut u8, entriesread: *mut u32, resumehandle: *mut u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsGetClientInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *mut *mut u8) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn NetDfsGetFtContainerSecurity(domainname: super::super::Foundation::PWSTR, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsGetInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *mut *mut u8) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn NetDfsGetSecurity(dfsentrypath: super::super::Foundation::PWSTR, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn NetDfsGetStdContainerSecurity(machinename: super::super::Foundation::PWSTR, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsGetSupportedNamespaceVersion(origin: DFS_NAMESPACE_VERSION_ORIGIN, pname: super::super::Foundation::PWSTR, ppversioninfo: *mut *mut DFS_SUPPORTED_NAMESPACE_VERSION_INFO) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsMove(olddfsentrypath: super::super::Foundation::PWSTR, newdfsentrypath: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsRemove(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsRemoveFtRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, ftdfsname: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsRemoveFtRootForced(domainname: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, ftdfsname: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsRemoveRootTarget(pdfspath: super::super::Foundation::PWSTR, ptargetpath: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsRemoveStdRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, flags: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsSetClientInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *const u8) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn NetDfsSetFtContainerSecurity(domainname: super::super::Foundation::PWSTR, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn NetDfsSetInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *const u8) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn NetDfsSetSecurity(dfsentrypath: super::super::Foundation::PWSTR, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn NetDfsSetStdContainerSecurity(machinename: super::super::Foundation::PWSTR, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32; } pub const DFS_ADD_VOLUME: u32 = 1u32; pub const DFS_FORCE_REMOVE: u32 = 2147483648u32; #[repr(C)] pub struct DFS_GET_PKT_ENTRY_STATE_ARG { pub DfsEntryPathLen: u16, pub ServerNameLen: u16, pub ShareNameLen: u16, pub Level: u32, pub Buffer: [u16; 1], } impl ::core::marker::Copy for DFS_GET_PKT_ENTRY_STATE_ARG {} impl ::core::clone::Clone for DFS_GET_PKT_ENTRY_STATE_ARG { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_1 { pub EntryPath: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_1 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_100 { pub Comment: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_100 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_100 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_101 { pub State: u32, } impl ::core::marker::Copy for DFS_INFO_101 {} impl ::core::clone::Clone for DFS_INFO_101 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_102 { pub Timeout: u32, } impl ::core::marker::Copy for DFS_INFO_102 {} impl ::core::clone::Clone for DFS_INFO_102 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_103 { pub PropertyFlagMask: u32, pub PropertyFlags: u32, } impl ::core::marker::Copy for DFS_INFO_103 {} impl ::core::clone::Clone for DFS_INFO_103 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_104 { pub TargetPriority: DFS_TARGET_PRIORITY, } impl ::core::marker::Copy for DFS_INFO_104 {} impl ::core::clone::Clone for DFS_INFO_104 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_105 { pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub PropertyFlagMask: u32, pub PropertyFlags: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_105 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_105 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_106 { pub State: u32, pub TargetPriority: DFS_TARGET_PRIORITY, } impl ::core::marker::Copy for DFS_INFO_106 {} impl ::core::clone::Clone for DFS_INFO_106 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_107 { pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub PropertyFlagMask: u32, pub PropertyFlags: u32, pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::marker::Copy for DFS_INFO_107 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::clone::Clone for DFS_INFO_107 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_150 { pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::marker::Copy for DFS_INFO_150 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::clone::Clone for DFS_INFO_150 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_1_32 { pub EntryPath: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for DFS_INFO_1_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for DFS_INFO_1_32 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_2 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub NumberOfStorages: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_2 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_200 { pub FtDfsName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_200 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_200 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_2_32 { pub EntryPath: u32, pub Comment: u32, pub State: u32, pub NumberOfStorages: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for DFS_INFO_2_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for DFS_INFO_2_32 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_3 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_3 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_3 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_300 { pub Flags: u32, pub DfsName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_300 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_300 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_3_32 { pub EntryPath: u32, pub Comment: u32, pub State: u32, pub NumberOfStorages: u32, pub Storage: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for DFS_INFO_3_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for DFS_INFO_3_32 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_4 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows_sys::core::GUID, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_4 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_4 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_4_32 { pub EntryPath: u32, pub Comment: u32, pub State: u32, pub Timeout: u32, pub Guid: ::windows_sys::core::GUID, pub NumberOfStorages: u32, pub Storage: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for DFS_INFO_4_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for DFS_INFO_4_32 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_5 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows_sys::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub NumberOfStorages: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_5 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_5 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_50 { pub NamespaceMajorVersion: u32, pub NamespaceMinorVersion: u32, pub NamespaceCapabilities: u64, } impl ::core::marker::Copy for DFS_INFO_50 {} impl ::core::clone::Clone for DFS_INFO_50 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_6 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows_sys::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO_1, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_INFO_6 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_INFO_6 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_INFO_7 { pub GenerationGuid: ::windows_sys::core::GUID, } impl ::core::marker::Copy for DFS_INFO_7 {} impl ::core::clone::Clone for DFS_INFO_7 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_8 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows_sys::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, pub NumberOfStorages: u32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::marker::Copy for DFS_INFO_8 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::clone::Clone for DFS_INFO_8 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_9 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows_sys::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO_1, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::marker::Copy for DFS_INFO_9 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::clone::Clone for DFS_INFO_9 { fn clone(&self) -> Self { *self } } pub const DFS_MOVE_FLAG_REPLACE_IF_EXISTS: u32 = 1u32; pub type DFS_NAMESPACE_VERSION_ORIGIN = i32; pub const DFS_NAMESPACE_VERSION_ORIGIN_COMBINED: DFS_NAMESPACE_VERSION_ORIGIN = 0i32; pub const DFS_NAMESPACE_VERSION_ORIGIN_SERVER: DFS_NAMESPACE_VERSION_ORIGIN = 1i32; pub const DFS_NAMESPACE_VERSION_ORIGIN_DOMAIN: DFS_NAMESPACE_VERSION_ORIGIN = 2i32; pub const DFS_PROPERTY_FLAG_ABDE: u32 = 32u32; pub const DFS_PROPERTY_FLAG_CLUSTER_ENABLED: u32 = 16u32; pub const DFS_PROPERTY_FLAG_INSITE_REFERRALS: u32 = 1u32; pub const DFS_PROPERTY_FLAG_ROOT_SCALABILITY: u32 = 2u32; pub const DFS_PROPERTY_FLAG_SITE_COSTING: u32 = 4u32; pub const DFS_PROPERTY_FLAG_TARGET_FAILBACK: u32 = 8u32; pub const DFS_RESTORE_VOLUME: u32 = 2u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_SITELIST_INFO { pub cSites: u32, pub Site: [DFS_SITENAME_INFO; 1], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_SITELIST_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_SITELIST_INFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_SITENAME_INFO { pub SiteFlags: u32, pub SiteName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_SITENAME_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_SITENAME_INFO { fn clone(&self) -> Self { *self } } pub const DFS_SITE_PRIMARY: u32 = 1u32; pub const DFS_STORAGE_FLAVOR_UNUSED2: u32 = 768u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_STORAGE_INFO { pub State: u32, pub ServerName: super::super::Foundation::PWSTR, pub ShareName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_STORAGE_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_STORAGE_INFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_STORAGE_INFO_0_32 { pub State: u32, pub ServerName: u32, pub ShareName: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for DFS_STORAGE_INFO_0_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for DFS_STORAGE_INFO_0_32 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_STORAGE_INFO_1 { pub State: u32, pub ServerName: super::super::Foundation::PWSTR, pub ShareName: super::super::Foundation::PWSTR, pub TargetPriority: DFS_TARGET_PRIORITY, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DFS_STORAGE_INFO_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DFS_STORAGE_INFO_1 { fn clone(&self) -> Self { *self } } pub const DFS_STORAGE_STATES: u32 = 15u32; pub const DFS_STORAGE_STATE_ACTIVE: u32 = 4u32; pub const DFS_STORAGE_STATE_OFFLINE: u32 = 1u32; pub const DFS_STORAGE_STATE_ONLINE: u32 = 2u32; #[repr(C)] pub struct DFS_SUPPORTED_NAMESPACE_VERSION_INFO { pub DomainDfsMajorVersion: u32, pub DomainDfsMinorVersion: u32, pub DomainDfsCapabilities: u64, pub StandaloneDfsMajorVersion: u32, pub StandaloneDfsMinorVersion: u32, pub StandaloneDfsCapabilities: u64, } impl ::core::marker::Copy for DFS_SUPPORTED_NAMESPACE_VERSION_INFO {} impl ::core::clone::Clone for DFS_SUPPORTED_NAMESPACE_VERSION_INFO { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DFS_TARGET_PRIORITY { pub TargetPriorityClass: DFS_TARGET_PRIORITY_CLASS, pub TargetPriorityRank: u16, pub Reserved: u16, } impl ::core::marker::Copy for DFS_TARGET_PRIORITY {} impl ::core::clone::Clone for DFS_TARGET_PRIORITY { fn clone(&self) -> Self { *self } } pub type DFS_TARGET_PRIORITY_CLASS = i32; pub const DfsInvalidPriorityClass: DFS_TARGET_PRIORITY_CLASS = -1i32; pub const DfsSiteCostNormalPriorityClass: DFS_TARGET_PRIORITY_CLASS = 0i32; pub const DfsGlobalHighPriorityClass: DFS_TARGET_PRIORITY_CLASS = 1i32; pub const DfsSiteCostHighPriorityClass: DFS_TARGET_PRIORITY_CLASS = 2i32; pub const DfsSiteCostLowPriorityClass: DFS_TARGET_PRIORITY_CLASS = 3i32; pub const DfsGlobalLowPriorityClass: DFS_TARGET_PRIORITY_CLASS = 4i32; pub const DFS_VOLUME_FLAVORS: u32 = 768u32; pub const DFS_VOLUME_FLAVOR_AD_BLOB: u32 = 512u32; pub const DFS_VOLUME_FLAVOR_STANDALONE: u32 = 256u32; pub const DFS_VOLUME_FLAVOR_UNUSED1: u32 = 0u32; pub const DFS_VOLUME_STATES: u32 = 15u32; pub const DFS_VOLUME_STATE_FORCE_SYNC: u32 = 64u32; pub const DFS_VOLUME_STATE_INCONSISTENT: u32 = 2u32; pub const DFS_VOLUME_STATE_OFFLINE: u32 = 3u32; pub const DFS_VOLUME_STATE_OK: u32 = 1u32; pub const DFS_VOLUME_STATE_ONLINE: u32 = 4u32; pub const DFS_VOLUME_STATE_RESYNCHRONIZE: u32 = 16u32; pub const DFS_VOLUME_STATE_STANDBY: u32 = 32u32; pub const FSCTL_DFS_BASE: u32 = 6u32; pub const FSCTL_DFS_GET_PKT_ENTRY_STATE: u32 = 401340u32; pub const NET_DFS_SETDC_FLAGS: u32 = 0u32; pub const NET_DFS_SETDC_INITPKT: u32 = 2u32; pub const NET_DFS_SETDC_TIMEOUT: u32 = 1u32;
pub mod data { use chrono::{DateTime, Utc}; use vcgencmd::measure_temp; #[derive(Debug)] pub struct MonitorData { date: String, temperature: String, } impl Default for MonitorData { fn default() -> Self { MonitorData::new() } } impl MonitorData { pub fn new() -> MonitorData { MonitorData { date: get_current_date(), temperature: get_current_temperature(), } } pub fn header() -> Vec<String> { { vec!["date".to_string(), "temperature".to_string()] } } pub fn to_vec(&self) -> Vec<String> { vec![self.date.clone(), self.temperature.clone()] } } pub fn get_current_date() -> String { let now: DateTime<Utc> = Utc::now(); format!("{}", now) } pub fn get_current_temperature() -> String { let temp = measure_temp().unwrap(); format!("{:.2}", temp) } } pub mod output { use crate::data::MonitorData; use csv::Writer; use std::error::Error; use std::fs::File; use std::io; use std::io::Stdout; pub trait DataOutput { fn init(header: Vec<String>) -> Self; fn write(&mut self, data: &MonitorData) -> Result<(), Box<dyn Error>>; } pub struct StdOutWriter { wtr: Writer<Stdout>, } impl DataOutput for StdOutWriter { fn init(header: Vec<String>) -> Self { let mut wtr = csv::Writer::from_writer(io::stdout()); wtr.write_record(&header).unwrap(); StdOutWriter { wtr } } fn write(&mut self, data: &MonitorData) -> Result<(), Box<dyn Error>> { self.wtr.write_record(&data.to_vec())?; self.wtr.flush()?; Ok(()) } } pub struct CsvFileWriter { wtr: Writer<File>, } impl DataOutput for CsvFileWriter { fn init(header: Vec<String>) -> Self { let mut wtr = csv::Writer::from_path("data.csv").unwrap(); wtr.write_record(&header).unwrap(); CsvFileWriter { wtr } } fn write(&mut self, data: &MonitorData) -> Result<(), Box<dyn Error>> { self.wtr.write_record(&data.to_vec())?; self.wtr.flush()?; Ok(()) } } }
// Enables `no_coverage` on the entire crate #![feature(no_coverage)] #[no_coverage] fn do_not_add_coverage_1() { println!("called but not covered"); } #[no_coverage] fn do_not_add_coverage_2() { println!("called but not covered"); } fn main() { do_not_add_coverage_1(); do_not_add_coverage_2(); }
use fraction::ToPrimitive; use crate::{effects::*, enums::*, io::*, gp::*, beat::*, key_signature::*}; #[derive(Debug,Clone, PartialEq)] pub struct Note { pub value: i16, pub velocity: i16, pub string: i8, pub effect: NoteEffect, pub duration_percent: f32, pub swap_accidentals: bool, pub kind: NoteType, duration: Option<i8>, tuplet: Option<i8,> } impl Default for Note {fn default() -> Self {Note { value: 0, velocity: DEFAULT_VELOCITY, string: 0, effect: NoteEffect::default(), duration_percent:1.0, swap_accidentals: false, kind: NoteType::Rest, duration: None, tuplet: None, }}} impl Note { pub(crate) fn real_value(&self, strings: &[(i8,i8)]) -> i8 { if self.string > 0 {return self.value.to_i8().unwrap() + strings[self.string.to_usize().unwrap() -1].1;} panic!("Cannot get real value for the note."); } } /// Contains all effects which can be applied to one note. #[derive(Debug,Clone, PartialEq,Eq)] pub struct NoteEffect { pub accentuated_note: bool, pub bend: Option<BendEffect>, pub ghost_note: bool, pub grace: Option<GraceEffect>, pub hammer: bool, pub harmonic: Option<HarmonicEffect>, pub heavy_accentuated_note: bool, pub left_hand_finger: Fingering, pub let_ring: bool, pub palm_mute: bool, pub right_hand_finger: Fingering, pub slides: Vec<SlideType>, pub staccato: bool, pub tremolo_picking: Option<TremoloPickingEffect>, pub trill: Option<TrillEffect>, pub vibrato: bool, } impl Default for NoteEffect { fn default() -> Self {NoteEffect { accentuated_note: false, bend: None, ghost_note: false, grace: None, hammer: false, harmonic: None, heavy_accentuated_note: false, left_hand_finger: Fingering::Open, let_ring: false, palm_mute: false, right_hand_finger: Fingering::Open, slides: Vec::new(), staccato: false, tremolo_picking: None, trill: None, vibrato: false, }} } impl NoteEffect { pub(crate) fn is_bend(&self) -> bool {self.bend.is_some()} pub(crate) fn is_harmonic(&self) -> bool {self.harmonic.is_some()} pub(crate) fn is_grace(&self) -> bool {self.grace.is_some()} pub(crate) fn is_trill(&self) -> bool {self.trill.is_some()} pub(crate) fn is_tremollo_picking(&self) -> bool {self.tremolo_picking.is_some()} pub(crate) fn is_default(&self) -> bool { let d = NoteEffect::default(); self.left_hand_finger == d.left_hand_finger && self.right_hand_finger == d.right_hand_finger && self.bend == d.bend && self.harmonic == d.harmonic && self.grace == d.grace && self.trill == d.trill && self.tremolo_picking == d.tremolo_picking && self.vibrato == d.vibrato && self.slides == d.slides && self.hammer == d.hammer && self.palm_mute == d.palm_mute && self.staccato == d.staccato && self.let_ring == d.let_ring } pub(crate) fn is_fingering(&self) -> bool {self.left_hand_finger != Fingering::Open || self.right_hand_finger != Fingering::Open} } impl Song { /// Read notes. First byte lists played strings: /// - *0x01*: 7th string /// - *0x02*: 6th string /// - *0x04*: 5th string /// - *0x08*: 4th string /// - *0x10*: 3th string /// - *0x20*: 2th string /// - *0x40*: 1th string /// - *0x80*: *blank* pub(crate) fn read_notes(&mut self, data: &[u8], seek: &mut usize, track_index: usize, beat: &mut Beat, duration: &Duration, note_effect: NoteEffect) { let flags = read_byte(data, seek); //println!("read_notes(), flags: {}", flags); for i in 0..self.tracks[track_index].strings.len() { if (flags & 1 << (7 - self.tracks[track_index].strings[i].0)) > 0 { let mut note = Note{effect: note_effect.clone(), ..Default::default()}; if self.version.number < (5,0,0) {self.read_note(data, seek, &mut note, self.tracks[track_index].strings[i], track_index);} else {self.read_note_v5(data, seek, &mut note, self.tracks[track_index].strings[i], track_index);} beat.notes.push(note); } beat.duration = duration.clone(); } } /// Read note. The first byte is note flags: /// - *0x01*: time-independent duration /// - *0x02*: heavy accentuated note /// - *0x04*: ghost note /// - *0x08*: presence of note effects /// - *0x10*: dynamics /// - *0x20*: fret /// - *0x40*: accentuated note /// - *0x80*: right hand or left hand fingering /// /// Flags are followed by: /// - Note type: `byte`. Note is normal if values is 1, tied if value is 2, dead if value is 3. /// - Time-independent duration: 2 `SignedBytes <signed-byte>`. Correspond to duration and tuplet. See `read_duration()` for reference. /// - Note dynamics: `signed-byte`. See `unpack_velocity()`. /// - Fret number: `signed-byte`. If flag at *0x20* is set then read fret number. /// - Fingering: 2 `SignedBytes <signed-byte>`. See `Fingering`. /// - Note effects. See `read_note_effects()`. fn read_note(&mut self, data: &[u8], seek: &mut usize, note: &mut Note, guitar_string: (i8,i8), track_index: usize) { let flags = read_byte(data, seek); note.string = guitar_string.0; note.effect.ghost_note = (flags & 0x04) == 0x04; //println!("read_note(), flags: {} \t string: {} \t ghost note: {}", flags, guitar_string.0, note.effect.ghost_note); if (flags & 0x20) == 0x20 {note.kind = get_note_type(read_byte(data, seek)); } if (flags & 0x01) == 0x01 { //println!("read_note(), duration: {} \t tuplet: {}",duration, tuplet); note.duration = Some(read_signed_byte(data, seek)); note.tuplet = Some(read_signed_byte(data, seek)); } if (flags & 0x10) == 0x10 { let v = read_signed_byte(data, seek); //println!("read_note(), v: {}", v); note.velocity = crate::effects::unpack_velocity(v.to_i16().unwrap()); //println!("read_note(), velocity: {}", note.velocity); } if (flags & 0x20) == 0x20 { let fret = read_signed_byte(data, seek); let value = if note.kind == NoteType::Tie { self.get_tied_note_value(guitar_string.0, track_index)} else {fret.to_i16().unwrap()}; note.value = value.clamp(0, 99); //println!("read_note(), value: {}", note.value); } if (flags & 0x80) == 0x80 { note.effect.left_hand_finger = get_fingering(read_signed_byte(data, seek)); note.effect.right_hand_finger= get_fingering(read_signed_byte(data, seek)); } if (flags & 0x08) == 0x08 { if self.version.number == (3,0,0) {self.read_note_effects_v3(data, seek, note);} else if self.version.number.0 == 4 {self.read_note_effects_v4(data, seek, note);} if note.effect.is_harmonic() && note.effect.harmonic.is_some() { let mut h = note.effect.harmonic.take().unwrap(); if h.kind == HarmonicType::Tapped {h.fret = Some(note.value.to_i8().unwrap() + 12);} note.effect.harmonic = Some(h); } } } /// Read note. The first byte is note flags: /// - *0x01*: duration percent /// - *0x02*: heavy accentuated note /// - *0x04*: ghost note /// - *0x08*: presence of note effects /// - *0x10*: dynamics /// - *0x20*: fret /// - *0x40*: accentuated note /// - *0x80*: right hand or left hand fingering /// /// Flags are followed by: /// - Note type: `byte`. Note is normal if values is 1, tied if value is 2, dead if value is 3. /// - Note dynamics: `signed-byte`. See `unpackVelocity`. /// - Fret number: `signed-byte`. If flag at *0x20* is set then read fret number. /// - Fingering: 2 `SignedBytes <signed-byte>`. See :class:`Fingering`. /// - Duration percent: `double`. /// - Second set of flags: `byte`. /// - *0x02*: swap accidentals. /// - Note effects. See `read_note_effects()`. fn read_note_v5(&mut self, data: &[u8], seek: &mut usize, note: &mut Note, guitar_string: (i8,i8), track_index: usize) { let flags = read_byte(data, seek); //println!("read_note_v5(), flags: {}", flags); note.string = guitar_string.0; note.effect.heavy_accentuated_note = (flags &0x02) == 0x02; note.effect.ghost_note = (flags &0x04) == 0x04; note.effect.accentuated_note = (flags &0x40) == 0x40; if (flags &0x20) == 0x20 {note.kind = get_note_type(read_byte(data, seek));} if (flags &0x10) == 0x10 { let v = read_signed_byte(data, seek); //println!("read_note(), v: {}", v); note.velocity = crate::effects::unpack_velocity(v.to_i16().unwrap()); //println!("read_note(), velocity: {}", note.velocity); } if (flags &0x20) == 0x20 { let fret = read_signed_byte(data, seek); let value = if note.kind == NoteType::Tie { self.get_tied_note_value(guitar_string.0, track_index)} else {fret.to_i16().unwrap()}; note.value = value.clamp(0, 99); //println!("read_note(), value: {}", note.value); } if (flags &0x80) == 0x80 { note.effect.left_hand_finger = get_fingering(read_signed_byte(data, seek)); note.effect.right_hand_finger= get_fingering(read_signed_byte(data, seek)); } if (flags & 0x01) == 0x01 {note.duration_percent = read_double(data, seek).to_f32().unwrap();} note.swap_accidentals = (read_byte(data, seek) & 0x02) == 0x02; if (flags & 0x08) == 0x08 {self.read_note_effects_v4(data, seek, note);} } /// Read note effects. First byte is note effects flags: /// - *0x01*: bend presence /// - *0x02*: hammer-on/pull-off /// - *0x04*: slide /// - *0x08*: let-ring /// - *0x10*: grace note presence /// /// Flags are followed by: /// - Bend. See `readBend`. /// - Grace note. See `readGrace`. fn read_note_effects_v3(&self, data: &[u8], seek: &mut usize, note: &mut Note) { let flags = read_byte(data, seek); //println!("read_effect(), flags: {}", flags); note.effect.hammer = (flags & 0x02) == 0x02; note.effect.let_ring = (flags & 0x08) == 0x08; if (flags & 0x01) == 0x01 {note.effect.bend = self.read_bend_effect(data, seek);} if (flags & 0x10) == 0x10 {note.effect.grace = Some(self.read_grace_effect(data, seek));} if (flags & 0x04) == 0x04 {note.effect.slides.push(SlideType::ShiftSlideTo);} //println!("read_note_effects(): {:?}", note); } /// Read note effects. The effects presence for the current note is set by the 2 bytes of flags. First set of flags: /// - *0x01*: bend /// - *0x02*: hammer-on/pull-off /// - *0x04*: *blank* /// - *0x08*: let-ring /// - *0x10*: grace note /// - *0x20*: *blank* /// - *0x40*: *blank* /// - *0x80*: *blank* /// /// Second set of flags: /// - *0x01*: staccato /// - *0x02*: palm mute /// - *0x04*: tremolo picking /// - *0x08*: slide /// - *0x10*: harmonic /// - *0x20*: trill /// - *0x40*: vibrato /// - *0x80*: *blank* /// /// Flags are followed by: /// - Bend. See `read_bend()`. /// - Grace note. See `read_grace()`. /// - Tremolo picking. See `read_tremolo_picking()`. /// - Slide. See `read_slides()`. /// - Harmonic. See `read_harmonic()`. /// - Trill. See `read_trill()`. fn read_note_effects_v4(&mut self, data: &[u8], seek: &mut usize, note: &mut Note) { let flags1 = read_signed_byte(data, seek); let flags2 = read_signed_byte(data, seek); note.effect.hammer = (flags1 & 0x02) == 0x02; note.effect.let_ring = (flags1 & 0x08) == 0x08; note.effect.staccato = (flags2 & 0x01) == 0x01; note.effect.palm_mute = (flags2 & 0x02) == 0x02; note.effect.vibrato = (flags2 & 0x40) == 0x40 || note.effect.vibrato; if (flags1 & 0x01) == 0x01 {note.effect.bend = self.read_bend_effect(data, seek);} if (flags1 & 0x10) == 0x10 { if self.version.number >= (5,0,0) {note.effect.grace = Some(self.read_grace_effect_v5(data,seek));} else {note.effect.grace = Some(self.read_grace_effect(data, seek));} } if (flags2 & 0x04) == 0x04 {note.effect.tremolo_picking = Some(self.read_tremolo_picking(data, seek));} if (flags2 & 0x08) == 0x08 { if self.version.number >= (5,0,0) {note.effect.slides.extend(self.read_slides_v5(data, seek));} else {note.effect.slides.push(get_slide_type(read_signed_byte(data, seek)));} } if (flags2 & 0x10) == 0x10 { if self.version.number >= (5,0,0) {note.effect.harmonic = Some(self.read_harmonic_v5(data, seek));} else {note.effect.harmonic = Some(self.read_harmonic(data, seek, note));} } if (flags2 & 0x20) == 0x20 {note.effect.trill = Some(self.read_trill(data, seek));} } /// Get note value of tied note fn get_tied_note_value(&self, string_index: i8, track_index: usize) -> i16 { //println!("get_tied_note_value()"); for m in (0usize..self.tracks[track_index].measures.len()).rev() { for v in (0usize..self.tracks[track_index].measures[m].voices.len()).rev() { for b in 0..self.tracks[track_index].measures[m].voices[v].beats.len() { if self.tracks[track_index].measures[m].voices[v].beats[b].status != BeatStatus::Empty { for n in 0..self.tracks[track_index].measures[m].voices[v].beats[b].notes.len() { if self.tracks[track_index].measures[m].voices[v].beats[b].notes[n].string == string_index {return self.tracks[track_index].measures[m].voices[v].beats[b].notes[n].value;} } } } } } -1 } pub(crate) fn write_notes(&self, data: &mut Vec<u8>, beat: &Beat, strings: &[(i8,i8)], version: &(u8,u8,u8)) { let mut string_flags: u8 = 0; for i in 0..beat.notes.len() {string_flags |= 1 << (7 - beat.notes[i].string);} write_byte(data, string_flags); let mut notes = beat.notes.clone(); notes.sort_by_key(|k|k.string); for note in &notes { if version.0 == 3 {self.write_note_v3(data, note);} else if version.0 == 4 {self.write_note_v4(data, note, strings, version);} else if version.0 == 5 {self.write_note_v5(data, note, strings, version);} } } fn write_note_v3(&self, data: &mut Vec<u8>, note: &Note) { let flags: u8 = self.pack_note_flags(note, &(3,0,0)); write_byte(data, flags); if (flags & 0x20) == 0x20 {write_byte(data, from_note_type(&note.kind));} if (flags & 0x01) == 0x01 { write_signed_byte(data, note.duration.unwrap()); write_signed_byte(data, note.tuplet.unwrap()); } if (flags & 0x10) == 0x10 {write_signed_byte(data, crate::effects::pack_velocity(note.velocity));} if (flags & 0x20) == 0x20 { if note.kind != NoteType::Rest {write_signed_byte(data, note.value.to_i8().unwrap());} else {write_signed_byte(data, 0);} } if (flags & 0x08) == 0x08 {self.write_note_effects_v3(data, note);} } fn write_note_v4(&self, data: &mut Vec<u8>, note: &Note, strings: &[(i8,i8)], version: &(u8,u8,u8)) { let flags: u8 = self.pack_note_flags(note, version); write_byte(data, flags); if (flags & 0x20) == 0x20 {write_byte(data, from_note_type(&note.kind));} if (flags & 0x01) == 0x01 { write_signed_byte(data, note.duration.unwrap()); write_signed_byte(data, note.tuplet.unwrap()); } if (flags & 0x10) == 0x10 {write_signed_byte(data, crate::effects::pack_velocity(note.velocity));} if (flags & 0x20) == 0x20 { if note.kind != NoteType::Rest {write_signed_byte(data, note.value.to_i8().unwrap());} else {write_signed_byte(data, 0);} } if (flags & 0x80) == 0x80 { write_signed_byte(data, from_fingering(&note.effect.left_hand_finger)); write_signed_byte(data, from_fingering(&note.effect.right_hand_finger)); } if (flags & 0x08) == 0x08 { if version.0 == 3 {self.write_note_effects_v3(data, note);} else {self.write_note_effects(data, note, strings, version);} } } fn write_note_v5(&self, data: &mut Vec<u8>, note: &Note, strings: &[(i8,i8)], version: &(u8,u8,u8)) { let flags: u8 = self.pack_note_flags(note, version); write_byte(data, flags); if (flags & 0x20) == 0x20 {write_byte(data, from_note_type(&note.kind));} if (flags & 0x10) == 0x10 {write_signed_byte(data, crate::effects::pack_velocity(note.velocity));} if (flags & 0x20) == 0x20 { if note.kind != NoteType::Tie {write_signed_byte(data, note.value.to_i8().unwrap());} else {write_signed_byte(data, 0);} } if (flags & 0x80) == 0x80 { write_signed_byte(data, from_fingering(&note.effect.left_hand_finger)); write_signed_byte(data, from_fingering(&note.effect.right_hand_finger)); } if (flags & 0x01) == 0x01 {write_f64(data, note.duration_percent.to_f64().unwrap());} let mut flags2 = 0u8; if note.swap_accidentals {flags2 |= 0x02;} write_byte(data, flags2); if (flags & 0x08) == 0x08 {self.write_note_effects(data, note, strings, version);} } fn pack_note_flags(&self, note: &Note, version: &(u8,u8,u8)) -> u8 { let mut flags: u8 = 0u8; if note.duration.is_some() && note.tuplet.is_some() {flags |= 0x01;} if note.effect.heavy_accentuated_note {flags |= 0x02;} if note.effect.ghost_note {flags |= 0x04;} if note.effect.is_default() {flags |= 0x08;} if note.velocity != DEFAULT_VELOCITY {flags |= 0x10;} flags |= 0x20; if version.0 > 3 { if note.effect.accentuated_note {flags |= 0x40;} if note.effect.is_fingering() {flags |= 0x80;} } if version.0 >= 5 && (note.duration_percent - 1.0).abs() > 1e-3 {flags |= 0x01;} flags } fn write_note_effects_v3(&self, data: &mut Vec<u8>, note: &Note) { let mut flags1 = 0u8; if note.effect.is_bend() {flags1 |= 0x01;} if note.effect.hammer {flags1 |= 0x02;} if note.effect.slides.contains(&SlideType::ShiftSlideTo) || note.effect.slides.contains(&SlideType::LegatoSlideTo) {flags1 |= 0x04;} if note.effect.let_ring {flags1 |= 0x08;} if note.effect.is_grace() {flags1 |= 0x10;} write_byte(data, flags1); if (flags1 & 0x01) == 0x01 {self.write_bend(data, &note.effect.bend);} if (flags1 & 0x10) == 0x10 {self.write_grace(data, &note.effect.grace);} } fn write_note_effects(&self, data: &mut Vec<u8>, note: &Note, strings: &[(i8,i8)], version: &(u8,u8,u8)) { let mut flags1 = 0i8; if note.effect.is_bend() {flags1 |= 0x01;} if note.effect.hammer {flags1 |= 0x02;} if note.effect.let_ring {flags1 |= 0x08;} if note.effect.is_grace() {flags1 |= 0x10;} write_signed_byte(data, flags1); let mut flags2 = 0i8; if note.effect.staccato {flags2 |= 0x01;} if note.effect.palm_mute {flags2 |= 0x01;} if note.effect.is_tremollo_picking() {flags2 |= 0x01;} if !note.effect.slides.is_empty() {flags2 |= 0x01;} if note.effect.is_harmonic() {flags2 |= 0x01;} if note.effect.is_trill() {flags2 |= 0x01;} if note.effect.vibrato {flags2 |= 0x01;} write_signed_byte(data, flags2); if (flags1 & 0x01) == 0x01 {self.write_bend(data, &note.effect.bend);} if (flags1 & 0x10) == 0x10 { if version.0 <5 {self.write_grace(data, &note.effect.grace);} else {self.write_grace_v5(data, &note.effect.grace);} } if (flags2 & 0x04) == 0x04 {if let Some(tp) = &note.effect.tremolo_picking { write_signed_byte(data, match tp.duration.value.to_u8().unwrap() { DURATION_EIGHTH => 1, DURATION_SIXTEENTH => 2, DURATION_THIRTY_SECOND => 3, _ => panic!("Cannot write tremolo picking"),}); }} if (flags2 & 0x08) == 0x08 { if version.0 < 5 {write_signed_byte(data, from_slide_type(&note.effect.slides[0]));} else {self.write_slides_v5(data, &note.effect.slides);} } if (flags2 & 0x10) == 0x10 { if version.0 <5 {self.write_harmonic(data, note, strings);} else {self.write_harmonic_v5(data, note, strings);} } if (flags2 & 0x20) == 0x20 { //trill if let Some(t) = &note.effect.trill { write_signed_byte(data, t.fret); write_signed_byte(data, match t.duration.value.to_u8().unwrap() { DURATION_SIXTEENTH => 1, DURATION_THIRTY_SECOND => 2, DURATION_SIXTY_FOURTH => 3, _ => panic!("Cannot write tremolo picking"),}); } else {panic!("No trill data");} } } }
#![feature(map_in_place)] use std::thread; #[derive(Clone)] struct Backpack { weight: u64, nuggets: Vec<u64>, } impl Backpack { fn new() -> Backpack { Backpack { weight: 0u64, nuggets: Vec::new() } } fn add(&mut self, nugget: u64) { self.weight = self.weight + nugget; self.nuggets.push(nugget); } } fn read_input() -> (u64, Vec<u64>) { let mut line = String::new(); let mut stdin = std::io::stdin(); stdin.read_line(&mut line).unwrap(); let capacity = line.trim().parse::<f64>().unwrap(); line.clear(); stdin.read_line(&mut line).unwrap(); let n_nuggets = line.trim().parse::<usize>().unwrap(); let mut nuggets = Vec::<f64>::with_capacity(n_nuggets); for _ in 0..n_nuggets { line.clear(); stdin.read_line(&mut line).unwrap(); nuggets.push(line.trim().parse().unwrap()); } nuggets.sort_by(|a, b| b.partial_cmp(a).expect("NaN cannot be sorted")); ((capacity * 10_000_000f64) as u64, nuggets.map_in_place(|f| (f * 10_000_000f64) as u64)) } fn recurse(capacity: u64, nuggets: &[u64], backpack: Backpack) -> Backpack { let mut solution: Option<Backpack> = None; for (i, nugget) in nuggets.iter().enumerate() { if backpack.weight + nugget <= capacity { let mut backpack_try = backpack.clone(); backpack_try.add(*nugget); backpack_try = recurse(capacity, &nuggets[(i + 1)..], backpack_try); if solution.is_none() || solution.as_ref().unwrap().weight < backpack_try.weight { solution = Some(backpack_try); } } } match solution { None => backpack, Some(backpack_heavier) => backpack_heavier, } } fn solve(capacity: u64, nuggets: Vec<u64>, backpack: Backpack) -> Backpack { let mut guards: Vec<thread::JoinHandle<Backpack>> = Vec::new(); for (i, nugget) in nuggets.iter().enumerate() { if backpack.weight + nugget <= capacity { let mut backpack_try = backpack.clone(); backpack_try.add(*nugget); let nuggets = nuggets.clone(); guards.push(thread::spawn(move || { recurse(capacity, &nuggets[(i + 1)..], backpack_try) })); } } guards.into_iter().map(|handle: thread::JoinHandle<Backpack>| handle.join().unwrap()).fold(Backpack::new(), |solution, backpack| { if backpack.weight > solution.weight { backpack } else { solution } }) } fn main() { let (capacity, nuggets) = read_input(); let backpack = solve(capacity, nuggets, Backpack::new()); if backpack.weight == 0u64 { println!("You'd better pick a better backpack…") } else { println!("total: {}", (backpack.weight as f64) / 10_000_000f64 ); for nugget in backpack.nuggets { println!("{}", (nugget as f64) / 10_000_000f64) } } }
use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::fs; fn main() { let result = solve_puzzle("input"); println!("And the result is {}", result); } fn solve_puzzle(file_name: &str) -> u64 { let data = read_data(file_name); let mut memory: HashMap<u64, u64> = HashMap::new(); let mut mask = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".to_string(); let mut permutations: HashMap<u32, Vec<Vec<char>>> = HashMap::new(); let mut x_count: u32 = mask.chars().filter(|x| *x == 'X').count() as u32; data.lines().for_each(|line| { match line.split(" = ").next().unwrap() { "mask" => { mask = line.replace("mask = ", ""); x_count = mask.chars().filter(|x| *x == 'X').count() as u32; match permutations.get(&x_count) { Some(_) => (), None => { permutations.insert(x_count, get_permutations(x_count)); } } } _ => { let (addresses, value) = get_values(line, &mask, &permutations.get(&x_count).unwrap()); addresses.iter().for_each(|address| { memory.insert(read_binary(address.clone()), value); }) } } }); memory.values().sum() } fn get_values(line: &str, mask: &String, permutations: &Vec<Vec<char>>) -> (HashSet<String>, u64) { let re = Regex::new(r"mem\[(?P<key>\d+)\] = (?P<value>\d+)").unwrap(); let caps = re.captures(line).unwrap(); let memory_address = write_binary(caps["key"].to_string().parse::<u64>().unwrap()); let memory_addresses = apply_mask(memory_address, mask, permutations); let decimal_value = caps["value"].to_string().parse::<u64>().unwrap(); (memory_addresses, decimal_value) } fn read_data(file_name: &str) -> String { fs::read_to_string(file_name).expect("Error") } fn write_binary(decimal: u64) -> String { format!("{:036b}", decimal) } fn read_binary(binary: String) -> u64 { binary .chars() .rev() .enumerate() .fold(0, |result, (idx, value)| match value { '1' => result + 2u64.pow(idx as u32), _ => result, }) } fn get_permutations(x_count: u32) -> Vec<Vec<char>> { let mut permutations: Vec<Vec<char>> = vec![vec!['0'], vec!['1']]; for _ in 1..x_count { let mut new_permutations = vec![]; for mut p in permutations { let mut duplicate = p.clone(); p.push('0'); duplicate.push('1'); new_permutations.push(duplicate); new_permutations.push(p); } permutations = new_permutations } permutations } fn apply_mask(input: String, mask: &String, permutations: &Vec<Vec<char>>) -> HashSet<String> { let mut addresses = HashSet::new(); permutations.iter().for_each(|permut| { let mut iter_comb = permut.iter(); let new_address = input .chars() .enumerate() .map(|(idx, value)| match mask.chars().nth(idx).unwrap() { 'X' => { let next_value = iter_comb.next().unwrap(); *next_value } '1' => '1', _ => value, }) .collect::<String>(); addresses.insert(new_address); }); addresses } #[cfg(test)] mod test { use super::*; #[test] fn test_example() { assert_eq!(208, solve_puzzle("example_data")); } #[test] fn test_input() { assert_eq!(3706820676200, solve_puzzle("input")); } #[test] fn test_write_binary() { assert_eq!( "000000000000000000000000000000001011".to_string(), write_binary(11) ); assert_eq!( "000000000000000000000000000001100101".to_string(), write_binary(101) ); assert_eq!( "000000000000000000000000000001001001".to_string(), write_binary(73) ); } #[test] fn test_read_binary() { assert_eq!( 64, read_binary("000000000000000000000000000001000000".to_string()) ); assert_eq!( 101, read_binary("000000000000000000000000000001100101".to_string()) ); assert_eq!( 73, read_binary("000000000000000000000000000001001001".to_string()) ); } #[test] fn test_apply_mask_two_x() { let input = "000000000000000000000000000000101010".to_string(); let mask = "000000000000000000000000000000X1001X".to_string(); let mut output = HashSet::new(); output.insert("000000000000000000000000000000011010".to_string()); output.insert("000000000000000000000000000000011011".to_string()); output.insert("000000000000000000000000000000111010".to_string()); output.insert("000000000000000000000000000000111011".to_string()); assert_eq!(output, apply_mask(input, &mask, &get_permutations(2))); } #[test] fn test_apply_mask_three_x() { let input = "000000000000000000000000000000011010".to_string(); let mask = "00000000000000000000000000000000X0XX".to_string(); let mut output = HashSet::new(); output.insert("000000000000000000000000000000010000".to_string()); output.insert("000000000000000000000000000000010001".to_string()); output.insert("000000000000000000000000000000010010".to_string()); output.insert("000000000000000000000000000000010011".to_string()); output.insert("000000000000000000000000000000011000".to_string()); output.insert("000000000000000000000000000000011001".to_string()); output.insert("000000000000000000000000000000011010".to_string()); output.insert("000000000000000000000000000000011011".to_string()); assert_eq!(output, apply_mask(input, &mask, &get_permutations(3))); } #[test] fn test_permutations() { assert_eq!(4, get_permutations(2).len()); assert_eq!(8, get_permutations(3).len()); assert_eq!(128, get_permutations(7).len()); assert_eq!(256, get_permutations(8).len()); assert_eq!(512, get_permutations(9).len()); } }
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; fn main() { let (r, c): (usize, usize) = parse_line().unwrap(); let mut senbeis: Vec<Vec<bool>> = vec![]; for _ in 0..r { let line: Vec<usize> = parse_line().unwrap(); let line = line.into_iter().map(|b| b == 0).collect_vec(); senbeis.push(line); } let gyous = (0..r).collect_vec(); let mut ans = 0; for mut bits in 0..2_u64.pow(gyous.len() as u32) { let mut vv = vec![]; for i in 0..gyous.len() { if bits % 2 == 1 { vv.push(gyous[i]); } bits /= 2; } ans = max(ans, nanko(senbeis.clone(), &vv)); } println!("{}", ans); } fn nanko(mut senbeis: Vec<Vec<bool>>, gyous: &Vec<usize>) -> u64 { for r in gyous.iter() { senbeis[*r] = senbeis[*r].iter().map(|b| !b).collect_vec(); } let mut ans = 0; for c in 0..senbeis[0].len() { let mut trus = 0; for r in 0..senbeis.len() { if senbeis[r][c] { trus += 1; } } ans += max(senbeis.len() as u64 - trus, trus); } return ans; }
// 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::fmt::Display; use std::fmt::Formatter; use common_exception::ErrorCode; use common_exception::Result; use common_expression::types::number::NumberScalar; use common_expression::Scalar; use ordered_float::OrderedFloat; pub type F64 = OrderedFloat<f64>; /// Datum is the struct to represent a single value in optimizer. #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum Datum { Bool(bool), Int(i64), UInt(u64), Float(F64), Bytes(Vec<u8>), } impl Datum { pub fn from_data_value(data_value: &Scalar) -> Option<Self> { match data_value { Scalar::Boolean(v) => Some(Datum::Bool(*v)), Scalar::Number(NumberScalar::Int64(v)) => Some(Datum::Int(*v)), Scalar::Number(NumberScalar::Int32(v)) => Some(Datum::Int(*v as i64)), Scalar::Number(NumberScalar::Int16(v)) => Some(Datum::Int(*v as i64)), Scalar::Number(NumberScalar::Int8(v)) => Some(Datum::Int(*v as i64)), Scalar::Number(NumberScalar::UInt64(v)) => Some(Datum::UInt(*v)), Scalar::Number(NumberScalar::UInt32(v)) => Some(Datum::UInt(*v as u64)), Scalar::Number(NumberScalar::UInt16(v)) => Some(Datum::UInt(*v as u64)), Scalar::Number(NumberScalar::UInt8(v)) => Some(Datum::UInt(*v as u64)), Scalar::Number(NumberScalar::Float64(v)) => Some(Datum::Float(*v)), Scalar::Number(NumberScalar::Float32(v)) => { Some(Datum::Float(F64::from(f32::from(*v) as f64))) } Scalar::String(v) => Some(Datum::Bytes(v.clone())), _ => None, } } pub fn from_scalar(data_value: &Scalar) -> Option<Self> { match data_value { Scalar::Boolean(v) => Some(Datum::Bool(*v)), Scalar::Number(NumberScalar::Int64(v)) => Some(Datum::Int(*v)), Scalar::Number(NumberScalar::Int32(v)) => Some(Datum::Int(*v as i64)), Scalar::Number(NumberScalar::Int16(v)) => Some(Datum::Int(*v as i64)), Scalar::Number(NumberScalar::Int8(v)) => Some(Datum::Int(*v as i64)), Scalar::Number(NumberScalar::UInt64(v)) => Some(Datum::UInt(*v)), Scalar::Number(NumberScalar::UInt32(v)) => Some(Datum::UInt(*v as u64)), Scalar::Number(NumberScalar::UInt16(v)) => Some(Datum::UInt(*v as u64)), Scalar::Number(NumberScalar::UInt8(v)) => Some(Datum::UInt(*v as u64)), Scalar::Number(NumberScalar::Float64(v)) => Some(Datum::Float(*v)), Scalar::Number(NumberScalar::Float32(v)) => { Some(Datum::Float(F64::from(f32::from(*v) as f64))) } Scalar::String(v) => Some(Datum::Bytes(v.clone())), _ => None, } } pub fn to_double(&self) -> Result<f64> { match self { Datum::Int(v) => Ok(*v as f64), Datum::UInt(v) => Ok(*v as f64), Datum::Float(v) => Ok(v.into_inner()), _ => Err(ErrorCode::IllegalDataType(format!( "Cannot convert {:?} to double", self ))), } } } impl Display for Datum { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Datum::Bool(v) => write!(f, "{}", v), Datum::Int(v) => write!(f, "{}", v), Datum::UInt(v) => write!(f, "{}", v), Datum::Float(v) => write!(f, "{}", v), Datum::Bytes(v) => { let s = String::from_utf8_lossy(v); write!(f, "{}", s) } } } } impl Datum { pub fn type_comparable(&self, other: &Datum) -> bool { matches!( (self, other), (Datum::Bool(_), Datum::Bool(_)) | (Datum::Bytes(_), Datum::Bytes(_)) | (Datum::Int(_), Datum::UInt(_)) | (Datum::Int(_), Datum::Int(_)) | (Datum::Int(_), Datum::Float(_)) | (Datum::UInt(_), Datum::Int(_)) | (Datum::UInt(_), Datum::UInt(_)) | (Datum::UInt(_), Datum::Float(_)) | (Datum::Float(_), Datum::Float(_)) | (Datum::Float(_), Datum::Int(_)) | (Datum::Float(_), Datum::UInt(_)) ) } pub fn compare(&self, other: &Self) -> Result<std::cmp::Ordering> { match (self, other) { (Datum::Bool(l), Datum::Bool(r)) => Ok(l.cmp(r)), (Datum::Int(l), Datum::Int(r)) => Ok(l.cmp(r)), (Datum::Int(_), Datum::UInt(r)) => { Ok(Datum::Int(i64::try_from(*r)?).compare(self)?.reverse()) } (Datum::Int(l), Datum::Float(_)) => Datum::Float(F64::from(*l as f64)).compare(other), (Datum::UInt(l), Datum::UInt(r)) => Ok(l.cmp(r)), (Datum::UInt(_), Datum::Int(_)) => Ok(other.compare(self)?.reverse()), (Datum::UInt(l), Datum::Float(_)) => Datum::Float(F64::from(*l as f64)).compare(other), (Datum::Float(l), Datum::Float(r)) => Ok(l.cmp(r)), (Datum::Float(_), Datum::Int(_)) => Ok(other.compare(self)?.reverse()), (Datum::Float(_), Datum::UInt(_)) => Ok(other.compare(self)?.reverse()), (Datum::Bytes(l), Datum::Bytes(r)) => Ok(l.cmp(r)), _ => Err(ErrorCode::Internal(format!( "Cannot compare between different kinds of datum: {:?}, {:?}", self, other ))), } } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::{Error, ResultExt}, fidl::encoding::OutOfLine, fidl_fuchsia_mem::Buffer, fidl_fuchsia_modular::{ EntityRequest, EntityRequestStream, EntityResolverRequest, EntityResolverRequestStream, EntityWriteStatus, }, fuchsia_async as fasync, fuchsia_syslog::macros::*, fuchsia_zircon as zx, futures::prelude::*, std::collections::HashMap, }; #[derive(Clone)] pub struct FakeEntityData { pub types: Vec<String>, pub data: String, } impl FakeEntityData { pub fn new(types: Vec<String>, data: &str) -> Self { FakeEntityData { types, data: data.to_string() } } } pub struct FakeEntityResolver { entities: HashMap<String, FakeEntityData>, } impl FakeEntityResolver { pub fn new() -> Self { FakeEntityResolver { entities: HashMap::new() } } pub fn register_entity(&mut self, reference: &str, data: FakeEntityData) { self.entities.insert(reference.to_string(), data); } pub fn spawn(self, mut stream: EntityResolverRequestStream) { fasync::spawn( async move { while let Some(request) = stream.try_next().await.context("error running entity resolver")? { match request { EntityResolverRequest::ResolveEntity { entity_reference, entity_request, .. } => { let stream = entity_request.into_stream()?; if let Some(entity) = self.entities.get(&entity_reference) { FakeEntityServer::new(&entity_reference, entity.clone()) .spawn(stream); } } } } Ok(()) } .unwrap_or_else(|e: Error| { fx_log_err!("error serving fake entity resolver: {:?}", e) }), ); } } pub struct FakeEntityServer { entity_reference: String, entity: FakeEntityData, } impl FakeEntityServer { pub fn new(reference: &str, entity: FakeEntityData) -> Self { FakeEntityServer { entity_reference: reference.to_string(), entity } } pub fn spawn(mut self, mut stream: EntityRequestStream) { fasync::spawn( async move { while let Some(request) = stream.try_next().await.context("error running entity server")? { match request { EntityRequest::GetTypes { responder } => { responder.send(&mut self.entity.types.iter().map(|s| s.as_ref()))?; } EntityRequest::GetData { responder, .. } => { let data = self.entity.data.as_bytes(); let vmo = zx::Vmo::create(data.len() as u64)?; vmo.write(&data, 0)?; responder.send(Some(OutOfLine(&mut Buffer { vmo, size: data.len() as u64, })))?; } EntityRequest::WriteData { responder, .. } => { responder.send(EntityWriteStatus::ReadOnly)?; } EntityRequest::GetReference { responder } => { responder.send(&mut self.entity_reference)?; } EntityRequest::Watch { .. } => { // Not implemented. } } } Ok(()) } .unwrap_or_else(|e: Error| fx_log_err!("error serving fake entity: {:?}", e)), ); } }
//! Oasis Contract SDK. #![cfg_attr(target_arch = "wasm32", feature(wasm_abi))] #[cfg(target_arch = "wasm32")] pub mod abi; pub mod context; pub mod contract; pub mod env; pub mod error; pub mod event; pub mod memory; pub mod storage; #[cfg(not(target_arch = "wasm32"))] pub mod testing; // Re-export types. pub use oasis_contract_sdk_types as types; // Re-export the CBOR crate for use in macros. pub use cbor; // Re-exports. pub use self::{context::Context, contract::Contract, error::Error, event::Event}; // Re-export the SDK support proc-macros. #[cfg(feature = "oasis-contract-sdk-macros")] pub use oasis_contract_sdk_macros::*; // Use `wee_alloc` as the global allocator. #[cfg(target_arch = "wasm32")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
use super::pool::{Fits, Pool}; use core::{ alloc::{AllocErr, CannotReallocInPlace, Excess, Layout}, cmp, ptr::{self, NonNull}, slice::SliceIndex, }; /// Allocator for a generic memory pools layout. /// /// The trait is supposed to be implemented for an array of pools. /// [`heap`](crate::heap) macro should be used to generate the concrete type and /// the implementation. #[allow(clippy::trivially_copy_pass_by_ref)] pub trait Allocator { /// The total number of memory pools. const POOL_COUNT: usize; /// Returns a reference to a pool or subslice, without doing bounds /// checking. /// /// # Safety /// /// Calling this method with an out-of-bounds index is Undefined Behavior. unsafe fn get_pool_unchecked<I>(&self, index: I) -> &I::Output where I: SliceIndex<[Pool]>; /// Returns a mutable reference to a pool or subslice, without doing bounds /// checking. /// /// # Safety /// /// Calling this method with an out-of-bounds index is Undefined Behavior. unsafe fn get_pool_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output where I: SliceIndex<[Pool]>; /// Empty allocation hook. Can be re-defined by the implementation. #[inline] fn alloc_hook(_layout: Layout, _pool: &Pool) {} /// Empty deallocation hook. Can be re-defined by the implementation. #[inline] fn dealloc_hook(_layout: Layout, _pool: &Pool) {} /// Empty growing in place hook. Can be re-defined by the implementation. #[inline] fn grow_in_place_hook(_layout: Layout, _new_size: usize) {} /// Empty shrinking in place hook. Can be re-defined by the implementation. #[inline] fn shrink_in_place_hook(_layout: Layout, _new_size: usize) {} /// Does a binary search for the pool with the smallest block size to fit /// `value`. fn binary_search<T: Fits>(&self, value: T) -> usize { let (mut left, mut right) = (0, Self::POOL_COUNT); while right > left { let middle = left + ((right - left) >> 1); let pool = unsafe { self.get_pool_unchecked(middle) }; if value.fits(pool) { right = middle; } else { left = middle + 1; } } left } #[doc(hidden)] unsafe fn alloc<'a, T: WithPool<'a, U>, U: MaybePool<'a>>( &'a self, layout: Layout, ) -> Result<T, AllocErr> { for pool_idx in self.binary_search(&layout)..Self::POOL_COUNT { let pool = self.get_pool_unchecked(pool_idx); if let Some(ptr) = pool.alloc() { Self::alloc_hook(layout, pool); return Ok(T::from(ptr, || U::from(pool))); } } Err(AllocErr) } #[doc(hidden)] #[allow(clippy::cast_ptr_alignment)] unsafe fn realloc<'a, T: WithPool<'a, U>, U: MaybePool<'a>>( &'a self, ptr: NonNull<u8>, layout: Layout, new_size: usize, ) -> Result<T, AllocErr> { if new_size < layout.size() { let _ = self.shrink_in_place(ptr, layout, new_size); Ok(T::from(ptr, || U::from(self.get_pool_unchecked(self.binary_search(ptr))))) } else if let Ok(pool) = self.grow_in_place(ptr, layout, new_size) { Ok(T::from(ptr, || pool)) } else { self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())).map( |new_ptr: T| { ptr::copy_nonoverlapping( ptr.as_ptr() as *const usize, new_ptr.as_ptr() as *mut usize, cmp::min(layout.size(), new_size), ); self.dealloc(ptr, layout); new_ptr }, ) } } #[doc(hidden)] unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) { let pool = self.get_pool_unchecked(self.binary_search(ptr)); Self::dealloc_hook(layout, pool); pool.dealloc(ptr); } #[doc(hidden)] unsafe fn usable_size(&self, layout: &Layout) -> (usize, usize) { let pool = self.get_pool_unchecked(self.binary_search(layout)); (0, pool.size()) } #[doc(hidden)] unsafe fn grow_in_place<'a, T: MaybePool<'a>>( &'a self, ptr: NonNull<u8>, layout: Layout, new_size: usize, ) -> Result<T, CannotReallocInPlace> { let pool = self.get_pool_unchecked(self.binary_search(ptr)); if Layout::from_size_align_unchecked(new_size, layout.align()).fits(pool) { Self::grow_in_place_hook(layout, new_size); Ok(T::from(pool)) } else { Err(CannotReallocInPlace) } } #[doc(hidden)] unsafe fn shrink_in_place( &self, _ptr: NonNull<u8>, layout: Layout, new_size: usize, ) -> Result<(), CannotReallocInPlace> { Self::shrink_in_place_hook(layout, new_size); Ok(()) } } pub trait MaybePool<'a> { fn from(pool: &'a Pool) -> Self; } impl<'a> MaybePool<'a> for () { #[inline] fn from(_pool: &'a Pool) {} } impl<'a> MaybePool<'a> for &'a Pool { #[inline] fn from(pool: Self) -> Self { pool } } pub trait WithPool<'a, T: MaybePool<'a>> { fn from<F>(ptr: NonNull<u8>, pool: F) -> Self where F: FnOnce() -> T; fn as_ptr(&self) -> *mut u8; } impl<'a> WithPool<'a, ()> for NonNull<u8> { #[inline] fn from<F>(ptr: NonNull<u8>, _pool: F) -> Self where F: FnOnce(), { ptr } #[inline] fn as_ptr(&self) -> *mut u8 { NonNull::as_ptr(*self) } } impl<'a> WithPool<'a, &'a Pool> for (NonNull<u8>, &'a Pool) { #[inline] fn from<F>(ptr: NonNull<u8>, pool: F) -> Self where F: FnOnce() -> &'a Pool, { (ptr, pool()) } #[inline] fn as_ptr(&self) -> *mut u8 { NonNull::as_ptr(self.0) } } impl<'a> WithPool<'a, &'a Pool> for Excess { #[inline] fn from<F>(ptr: NonNull<u8>, pool: F) -> Self where F: FnOnce() -> &'a Pool, { Self(ptr, pool().size()) } #[inline] fn as_ptr(&self) -> *mut u8 { NonNull::as_ptr(self.0) } } #[cfg(test)] mod tests { use super::*; struct TestHeap { pools: [Pool; 10], } impl Allocator for TestHeap { const POOL_COUNT: usize = 10; unsafe fn get_pool_unchecked<I>(&self, index: I) -> &I::Output where I: SliceIndex<[Pool]>, { self.pools.get_unchecked(index) } unsafe fn get_pool_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output where I: SliceIndex<[Pool]>, { self.pools.get_unchecked_mut(index) } } impl TestHeap { fn search_layout(&self, size: usize) -> Option<usize> { let pool_idx = self.binary_search(&Layout::from_size_align(size, 4).unwrap()); if pool_idx < TestHeap::POOL_COUNT { unsafe { Some(self.get_pool_unchecked(pool_idx).size()) } } else { None } } fn search_ptr(&self, ptr: usize) -> Option<usize> { let pool_idx = self.binary_search(unsafe { NonNull::new_unchecked(ptr as *mut u8) }); if pool_idx < TestHeap::POOL_COUNT { unsafe { Some(self.get_pool_unchecked(pool_idx).size()) } } else { None } } unsafe fn alloc_and_set(&self, layout: Layout, value: u8) { *(self.alloc::<NonNull<u8>, ()>(layout).unwrap().as_ptr() as *mut u8) = value; } } #[test] fn binary_search() { let heap = TestHeap { pools: [ Pool::new(20, 2, 100), Pool::new(220, 5, 100), Pool::new(720, 8, 100), Pool::new(1520, 12, 100), Pool::new(2720, 16, 100), Pool::new(4320, 23, 100), Pool::new(6620, 38, 100), Pool::new(10420, 56, 100), Pool::new(16020, 72, 100), Pool::new(23220, 91, 100), ], }; assert_eq!(heap.search_layout(1), Some(2)); assert_eq!(heap.search_layout(2), Some(2)); assert_eq!(heap.search_layout(15), Some(16)); assert_eq!(heap.search_layout(16), Some(16)); assert_eq!(heap.search_layout(17), Some(23)); assert_eq!(heap.search_layout(91), Some(91)); assert_eq!(heap.search_layout(92), None); assert_eq!(heap.search_ptr(0), Some(2)); assert_eq!(heap.search_ptr(20), Some(2)); assert_eq!(heap.search_ptr(219), Some(2)); assert_eq!(heap.search_ptr(220), Some(5)); assert_eq!(heap.search_ptr(719), Some(5)); assert_eq!(heap.search_ptr(720), Some(8)); assert_eq!(heap.search_ptr(721), Some(8)); assert_eq!(heap.search_ptr(5000), Some(23)); assert_eq!(heap.search_ptr(23220), Some(91)); assert_eq!(heap.search_ptr(32319), Some(91)); assert_eq!(heap.search_ptr(32320), None); assert_eq!(heap.search_ptr(50000), None); } #[test] fn allocations() { let mut m = [0u8; 3230]; let o = &mut m as *mut _ as usize; let heap = TestHeap { pools: [ Pool::new(o + 0, 2, 10), Pool::new(o + 20, 5, 10), Pool::new(o + 70, 8, 10), Pool::new(o + 150, 12, 10), Pool::new(o + 270, 16, 10), Pool::new(o + 430, 23, 10), Pool::new(o + 660, 38, 10), Pool::new(o + 1040, 56, 10), Pool::new(o + 1600, 72, 10), Pool::new(o + 2320, 91, 10), ], }; let layout = Layout::from_size_align(32, 1).unwrap(); unsafe { heap.alloc_and_set(layout, 111); assert_eq!(m[660], 111); heap.alloc_and_set(layout, 222); assert_eq!(m[698], 222); heap.alloc_and_set(layout, 123); assert_eq!(m[736], 123); heap.dealloc(NonNull::new_unchecked((o + 660) as *mut u8), layout); assert_eq!(m[660], 0); heap.dealloc(NonNull::new_unchecked((o + 736) as *mut u8), layout); assert_eq!(*(&m[736] as *const _ as *const usize), o + 660); heap.alloc_and_set(layout, 202); assert_eq!(m[736], 202); heap.dealloc(NonNull::new_unchecked((o + 698) as *mut u8), layout); assert_eq!(*(&m[698] as *const _ as *const usize), o + 660); heap.dealloc(NonNull::new_unchecked((o + 736) as *mut u8), layout); assert_eq!(*(&m[736] as *const _ as *const usize), o + 698); } } }
use std::fmt; use std::fmt::Debug; use std::io::{Cursor, Read, Write}; use std::fs::{File, OpenOptions}; use std::io; use std::path::Path; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use gba_mem::Address; pub const BYTE_WIDTH: u16 = 8; #[derive(Clone, Copy, Debug)] pub enum BusWidth { BW16, BW32, } impl BusWidth { #[inline] pub fn to_bytes(&self) -> u16 { match *self { BusWidth::BW16 => 2, BusWidth::BW32 => 4, } } #[inline] pub fn to_bits(&self) -> u16 { self.to_bytes() * BYTE_WIDTH } } pub trait MemoryRegion { fn lo() -> Address; fn hi() -> Address; fn bus_width() -> BusWidth; #[inline] fn len() -> usize { (Self::hi() - Self::lo())/BYTE_WIDTH as Address + 1 } #[inline] fn contains_cmp(addr: Address) -> isize { if addr < Self::lo() { -1 } else if addr > Self::hi() { 1 } else { 0 } } #[inline] fn contains(addr: Address) -> bool { match Self::contains_cmp(addr) { 0 => true, _ => false, } } } pub trait MemRead<T> { fn read(&self, addr: Address) -> T; } pub trait MemWrite<T> { fn write(&mut self, addr: Address, val: T); } macro_rules! new_mem_region { ($name:ident, $lo:expr, $hi:expr, $bus:expr) => { pub struct $name { mem: Vec<u8>,//Box<[u8; (($hi - $lo) as usize)/(BYTE_WIDTH as usize) + 1]>, } impl $name { pub fn create_from_array(array: &[u8]) -> $name { let mut ret = $name { mem: vec![0; (($hi - $lo) as usize)/(BYTE_WIDTH as usize) + 1], }; println!("{:x}\n{:x}", ret.mem.len(), array.len()); ret.mem.copy_from_slice(array); ret } pub fn create_from_file(file_path: &str) -> io::Result<$name> { let file_path = Path::new(file_path); let mut file = try!(File::open(file_path)); let file_len = try!(file.metadata()).len() as usize; let mem_len = $name::len(); if file_len > mem_len { let errmsg = match file_path.to_str() { Some(f) => format!("File {} ({} Bytes) is too big for the {} memory region ({} Bytes).", f, file_len, stringify!($name), mem_len), None => format!("File is too big for the {} memory region.", stringify!($name)), }; Err(io::Error::new(io::ErrorKind::Other, errmsg)) } else { let mut ret = $name { mem: vec![0; (($hi - $lo) as usize)/(BYTE_WIDTH as usize) + 1], }; try!(file.read(ret.mem.as_mut_slice())); Ok(ret) } } pub fn to_file(&self, file_path: &str) { let file_path = Path::new(file_path); let mut file = OpenOptions::new() .write(true) .create(true) .open(file_path).unwrap(); file.write_all(self.mem.as_ref()).unwrap(); } } impl Default for $name { fn default() -> Self { $name { mem: vec![0; (($hi - $lo) as usize)/(BYTE_WIDTH as usize) + 1], } } } impl Debug for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}{{ lo:{:#x}, lo:{:#x}, bus_width:{} }}", stringify!($name), $name::lo(), $name::hi(), $name::bus_width().to_bits()) } } impl MemoryRegion for $name { #[inline] fn lo() -> Address { $lo } #[inline] fn hi() -> Address { $hi } #[inline] fn bus_width() -> BusWidth { $bus } } }; } macro_rules! def_mem_region_ops { ($name:ty) => {}; (mem_read_as_self: $name:ty, $func:ident, $ty:ty) => { #[allow(trivial_numeric_casts)] impl MemRead<$ty> for $name { fn read(&self, addr: Address) -> $ty { self.mem[(addr - Self::lo()) as usize] as $ty } } }; (mem_read_as_other: $name:ty, $func:ident, $ty:ty) => { impl MemRead<$ty> for $name { fn read(&self, addr: Address) -> $ty { let loc = (addr - Self::lo()) as u64; let mut rdr = Cursor::new((*self.mem).as_ref()); rdr.set_position(loc); rdr.$func::<LittleEndian>().unwrap() } } }; (mem_write_as_self: $name:ty, $func:ident, $ty:ty) => { #[allow(trivial_numeric_casts)] impl MemWrite<$ty> for $name { fn write(&mut self, addr: Address, val: $ty) { self.mem[addr - Self::lo()] = val as u8; } } }; (mem_write_as_other: $name:ty, $func:ident, $ty:ty) => { impl MemWrite<$ty> for $name { fn write(&mut self, addr: Address, val: $ty) { let loc = (addr - Self::lo()) as u64; let mut wtr = Cursor::new((*self.mem).as_mut()); wtr.set_position(loc); wtr.$func::<LittleEndian>(val).unwrap() } } }; (read: $name:ty, 8) => { def_mem_region_ops!(mem_read_as_self: $name, read_i8, i8 ); def_mem_region_ops!(mem_read_as_self: $name, read_u8, u8 ); }; (read: $name:ty, 16) => { def_mem_region_ops!(mem_read_as_other: $name, read_i16, i16); def_mem_region_ops!(mem_read_as_other: $name, read_u16, u16); }; (read: $name:ty, 32) => { def_mem_region_ops!(mem_read_as_other: $name, read_i32, i32); def_mem_region_ops!(mem_read_as_other: $name, read_u32, u32); def_mem_region_ops!(mem_read_as_other: $name, read_f32, f32); }; (write: $name:ty, 8) => { def_mem_region_ops!(mem_write_as_self: $name, write_i8, i8 ); def_mem_region_ops!(mem_write_as_self: $name, write_u8, u8 ); }; (write: $name:ty, 16) => { def_mem_region_ops!(mem_write_as_other: $name, write_i16, i16); def_mem_region_ops!(mem_write_as_other: $name, write_u16, u16); }; (write: $name:ty, 32) => { def_mem_region_ops!(mem_write_as_other: $name, write_i32, i32); def_mem_region_ops!(mem_write_as_other: $name, write_u32, u32); def_mem_region_ops!(mem_write_as_other: $name, write_f32, f32); }; ($name:ty, r, $tok:tt) => { def_mem_region_ops!(read: $name, $tok); }; ($name:ty, w, $tok:tt) => { def_mem_region_ops!(write: $name, $tok); }; ($name:ty, rw, $tok:tt) => { def_mem_region_ops!(read: $name, $tok); def_mem_region_ops!(write: $name, $tok); }; ($name:ty, wr, $tok:tt) => { def_mem_region_ops!($name, rw, $tok); }; ($name:ty, $op:tt[]) => {}; ($name:ty, $op:tt[ $tok:tt ]) => { def_mem_region_ops!($name, $op, $tok); }; ($name:ty, $op:tt[ $tok:tt, $($toks:tt),* ]) => { def_mem_region_ops!($name, $op, $tok); def_mem_region_ops!($name, $op[ $($toks),* ]); }; ($name:ty, $op:tt[ $($toks:tt),* ], $( $r_op:tt[ $($r_size:tt),* ] ),*) => { def_mem_region_ops!($name, $op[ $($toks),* ]); def_mem_region_ops!($name, $( $r_op[ $($r_size),* ] ),*); }; } // Declare memory regions new_mem_region!(SystemRom, 0x00000000, 0x0001FFFF, BusWidth::BW32); new_mem_region!(ExternRam, 0x02000000, 0x0203FFFF, BusWidth::BW32); new_mem_region!(InternRam, 0x03000000, 0x03007FFF, BusWidth::BW32); new_mem_region!(PalettRam, 0x05000000, 0x050003FF, BusWidth::BW32); new_mem_region!(VisualRam, 0x06000000, 0x06017FFF, BusWidth::BW16); new_mem_region!(OAM, 0x07000000, 0x070003FF, BusWidth::BW32); new_mem_region!(PakRom, 0x08000000, 0x0FFFFFFF, BusWidth::BW16); // Implement read and write operations def_mem_region_ops!(SystemRom, r[8, 16, 32]); def_mem_region_ops!(ExternRam, rw[8, 16, 32]); def_mem_region_ops!(InternRam, rw[8, 16, 32]); def_mem_region_ops!(PalettRam, r[8, 16, 32], w[16, 32]); def_mem_region_ops!(VisualRam, r[8, 16, 32], w[16, 32]); def_mem_region_ops!(OAM, r[8, 16, 32], w[16, 32]); def_mem_region_ops!(PakRom, rw[8, 16, 32]);
fn main() { let x: i32 = 10; let y: u32 = to_u32(x); println!("{}", y); } fn to_u32(v: i32) -> u32 { //u32::from(v) v.into() }
use crate::lexer::*; use crate::parsers::expression::begin::body_statement; use crate::parsers::expression::expression; use crate::parsers::expression::method::defined_method_name; use crate::parsers::expression::method::method_body; use crate::parsers::expression::method::method_parameter_part; use crate::parsers::expression::variable::variable_reference; use crate::parsers::program::separator; /// `class` `<<` *expression* *separator* *singleton_class_body* `end` pub(crate) fn singleton_class_definition(i: Input) -> NodeResult { map( tuple(( tag("class"), ws0, tag("<<"), ws0, expression, separator, singleton_class_body, tag("end"), )), |_| Node::Placeholder, )(i) } /// *body_statement* pub(crate) fn singleton_class_body(i: Input) -> NodeResult { body_statement(i) } /// `def` *singleton* ( `.` | `::` ) *defined_method_name* [ no ⏎ ] *method_parameter_part* *method_body* `end` pub(crate) fn singleton_method_definition(i: Input) -> NodeResult { map( tuple(( tag("def"), ws0, singleton, alt((tag("."), tag("::"))), ws0, defined_method_name, no_lt, method_parameter_part, method_body, tag("end"), )), |_| Node::Placeholder, )(i) } /// *variable_reference* | `(` *expression* `)` pub(crate) fn singleton(i: Input) -> NodeResult { alt(( variable_reference, map(tuple((char('('), ws0, expression, ws0, char(')'))), |t| t.2), ))(i) }
//! An ephemeral in-memory file system, intended mainly for unit tests use super::traits::{OpenOptions, VFile, VMetadata, VPath, VFS}; use async_trait::async_trait; use futures_lite::{ io::{AsyncRead, AsyncSeek, AsyncWrite}, stream, }; use std; use std::cmp; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::io::{self, Read, Result, Seek, SeekFrom, Write}; use std::io::{Error, ErrorKind, IoSlice, IoSliceMut}; use std::ops::{Deref, DerefMut}; use std::pin::Pin; use std::sync::Arc; use std::sync::RwLock; use std::task::{Context, Poll}; pub type Filename = String; #[derive(Debug, Clone)] pub struct DataHandle(pub(crate) Arc<RwLock<Vec<u8>>>); impl DataHandle { fn new() -> DataHandle { DataHandle(Arc::new(RwLock::new(Vec::new()))) } pub fn with_data(data: Vec<u8>) -> DataHandle { DataHandle(Arc::new(RwLock::new(data))) } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum NodeKind { Directory, File, } #[derive(Debug)] struct FsNode { kind: NodeKind, pub children: HashMap<String, FsNode>, pub data: DataHandle, } impl FsNode { pub fn new_directory() -> Self { FsNode { kind: NodeKind::Directory, children: HashMap::new(), data: DataHandle::new(), } } pub fn new_file() -> Self { FsNode { kind: NodeKind::File, children: HashMap::new(), data: DataHandle::new(), } } fn metadata(&mut self) -> Result<MemoryMetadata> { Ok(MemoryMetadata { kind: self.kind.clone(), len: self.data.0.read().unwrap().len() as u64, }) } } #[derive(Debug)] pub struct MemoryFSImpl { root: FsNode, } pub type MemoryFSHandle = Arc<RwLock<MemoryFSImpl>>; /// An ephemeral in-memory file system, intended mainly for unit tests #[derive(Debug, Clone)] pub struct MemoryFS { handle: MemoryFSHandle, } impl MemoryFS { pub fn new() -> MemoryFS { MemoryFS { handle: Arc::new(RwLock::new(MemoryFSImpl { root: FsNode::new_directory(), })), } } } #[derive(Debug)] pub struct MemoryFile { pub(crate) data: DataHandle, pub(crate) pos: u64, } impl Read for MemoryFile { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let data = self.data.0.write().unwrap(); let n = (&data.deref()[self.pos as usize..]).read(buf)?; self.pos += n as u64; Ok(n) } } impl AsyncRead for MemoryFile { #[cfg(feature = "read-initializer")] unsafe fn initializer(&self) -> Initializer { io::Read::initializer(self) } fn poll_read( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize>> { Poll::Ready(io::Read::read(&mut *self, buf)) } fn poll_read_vectored( mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>], ) -> Poll<Result<usize>> { Poll::Ready(io::Read::read_vectored(&mut *self, bufs)) } } impl Write for MemoryFile { fn write(&mut self, buf: &[u8]) -> Result<usize> { let mut guard = self.data.0.write().unwrap(); let ref mut vec: &mut Vec<u8> = guard.deref_mut(); // From cursor.rs let pos = self.pos; let len = vec.len(); let amt = pos.saturating_sub(len as u64); vec.resize(len + amt as usize, 0); { let pos = pos as usize; let space = vec.len() - pos; let (left, right) = buf.split_at(cmp::min(space, buf.len())); vec[pos..pos + left.len()].clone_from_slice(left); vec.extend_from_slice(right); } // Bump us forward self.pos = pos + buf.len() as u64; Ok(buf.len()) } fn flush(&mut self) -> Result<()> { // Nothing to do Ok(()) } } impl AsyncWrite for MemoryFile { fn poll_write( mut self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize>> { Poll::Ready(Write::write(&mut *self, buf)) } fn poll_write_vectored( mut self: Pin<&mut Self>, _cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<Result<usize>> { Poll::Ready(Write::write_vectored(&mut *self, bufs)) } fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> { Poll::Ready(Write::flush(&mut *self)) } fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> { Poll::Ready(Ok(())) } } impl VFile for MemoryFile {} impl Seek for MemoryFile { fn seek(&mut self, style: SeekFrom) -> Result<u64> { let pos = match style { SeekFrom::Start(n) => { self.pos = n; return Ok(n); } SeekFrom::End(n) => { let data = self.data.0.read().unwrap(); data.len() as i64 + n } SeekFrom::Current(n) => self.pos as i64 + n, }; if pos < 0 { Err(Error::new( ErrorKind::InvalidInput, "invalid seek to a negative position", )) } else { self.pos = pos as u64; Ok(self.pos) } } } impl AsyncSeek for MemoryFile { fn poll_seek( mut self: Pin<&mut Self>, _cx: &mut Context<'_>, pos: SeekFrom, ) -> Poll<Result<u64>> { Poll::Ready(Seek::seek(&mut *self, pos)) } } pub struct MemoryMetadata { kind: NodeKind, len: u64, } impl VMetadata for MemoryMetadata { fn is_dir(&self) -> bool { self.kind == NodeKind::Directory } fn is_file(&self) -> bool { self.kind == NodeKind::File } fn len(&self) -> u64 { self.len } } impl VFS for MemoryFS { type Path = MemoryPath; fn path(&self, path: &str) -> MemoryPath { MemoryPath::new(&self.handle, path.to_string()) } } #[derive(Debug, Clone)] pub struct MemoryPath { pub path: Filename, fs: MemoryFSHandle, } impl MemoryPath { pub fn new(fs: &MemoryFSHandle, path: Filename) -> Self { return MemoryPath { path: path, fs: fs.clone(), }; } fn with_node<R, F: FnOnce(&mut FsNode) -> R>(&self, f: F) -> Result<R> { let root = &mut self.fs.write().unwrap().root; let mut components: Vec<&str> = self.path.split("/").collect(); components.reverse(); components.pop(); return traverse_with(root, &mut components, f); } pub fn decompose_path(&self) -> (Option<String>, String) { let mut split = self.path.rsplitn(2, "/"); if let Some(mut filename) = split.next() { if let Some(mut parent) = split.next() { if parent.is_empty() { parent = "/"; } if filename.is_empty() { filename = parent; return (None, filename.to_owned()); } return (Some(parent.to_owned()), filename.to_owned()); } } return (None, self.path.clone()); } fn parent_internal(&self) -> Option<MemoryPath> { self.decompose_path() .0 .map(|parent| MemoryPath::new(&self.fs.clone(), parent)) } } fn traverse_mkdir(node: &mut FsNode, components: &mut Vec<&str>) -> Result<()> { if let Some(component) = components.pop() { let directory = &mut node .children .entry(component.to_owned()) .or_insert_with(FsNode::new_directory); if directory.kind != NodeKind::Directory { return Err(Error::new( ErrorKind::Other, format!("File is not a directory: {}", component), )); } traverse_mkdir(directory, components) } else { Ok(()) } } fn traverse_with<R, F: FnOnce(&mut FsNode) -> R>( node: &mut FsNode, components: &mut Vec<&str>, f: F, ) -> Result<R> { if let Some(component) = components.pop() { if component.is_empty() { return traverse_with(node, components, f); } let entry = node.children.get_mut(component); if let Some(directory) = entry { return traverse_with(directory, components, f); } else { return Err(Error::new( ErrorKind::Other, format!("File not found {:?}", component), )); } } else { Ok(f(node)) } } impl MemoryPath { pub(crate) fn open_with_options(&self, open_options: &OpenOptions) -> Result<MemoryFile> { let parent_path = match self.parent_internal() { None => { return Err(Error::new( ErrorKind::Other, format!("File is not a file: {:?}", self.file_name()), )); } Some(parent) => parent, }; let data_handle = parent_path.with_node(|node| { let file_name = self.file_name().unwrap(); let file_node_entry = node.children.entry(file_name); let file_node = match file_node_entry { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { if !open_options.create { return Err(Error::new( ErrorKind::Other, format!("File does not exist: {}", self.path), )); } entry.insert(FsNode::new_file()) } }; if file_node.kind != NodeKind::File { return Err(Error::new( ErrorKind::Other, format!("File is not a file: {:?}", self.file_name()), )); } return Ok(file_node.data.clone()); })??; if open_options.truncate { let mut data = data_handle.0.write().unwrap(); data.clear(); } let mut pos = 0u64; if open_options.append { pos = data_handle.0.read().unwrap().len() as u64; } Ok(MemoryFile { data: data_handle, pos: pos, }) } pub(crate) fn create_dir_inner(&self) -> Result<()> { let root = &mut self.fs.write().unwrap().root; let mut components: Vec<&str> = self.path.split("/").collect(); components.reverse(); components.pop(); traverse_mkdir(root, &mut components) } } #[async_trait] impl VPath for MemoryPath { type Metadata = MemoryMetadata; type File = MemoryFile; type ReadDir = stream::Iter<<Vec<Result<MemoryPath>> as IntoIterator>::IntoIter>; fn parent(&self) -> Option<MemoryPath> { self.parent_internal() } fn file_name(&self) -> Option<String> { Some(self.decompose_path().1) } fn extension(&self) -> Option<String> { match self.file_name() { Some(name) => pathutils::extname(&name).map(|m| m.to_string()), None => None, } } fn resolve(&self, path: &str) -> MemoryPath { let mut new_path = self.path.clone(); if !new_path.ends_with('/') { new_path.push_str("/"); } new_path.push_str(&path); return MemoryPath::new(&self.fs, new_path); } async fn exists(&self) -> bool { self.with_node(|_node| ()).is_ok() } async fn metadata(&self) -> Result<MemoryMetadata> { match self.with_node(FsNode::metadata) { Ok(o) => o, Err(e) => Err(e), } } fn to_string(&self) -> std::borrow::Cow<str> { std::borrow::Cow::Owned(self.path.clone()) } // fn to_path_buf(&self) -> Option<PathBuf> { // None // } async fn open(&self, options: OpenOptions) -> Result<Self::File> { self.open_with_options(&options) } async fn read_dir(&self) -> Result<Self::ReadDir> { let children = self.with_node(|node| { let children: Vec<_> = node .children .keys() .map(|name| Ok(MemoryPath::new(&self.fs, self.path.clone() + "/" + name))) .collect(); children }); match children { Ok(children) => Ok(stream::iter(children.into_iter())), Err(e) => Err(e), } } async fn create_dir(&self) -> Result<()> { let root = &mut self.fs.write().unwrap().root; let mut components: Vec<&str> = self.path.split("/").collect(); components.reverse(); components.pop(); traverse_mkdir(root, &mut components) } async fn rm(&self) -> Result<()> { let parent_path = match self.parent_internal() { None => { return Err(Error::new( ErrorKind::Other, format!("File is not a file: {:?}", self.file_name()), )) } Some(parent) => parent, }; parent_path.with_node(|node| { let file_name = self.file_name().unwrap(); node.children.remove(&file_name); }) } async fn rm_all(&self) -> Result<()> { self.rm().await } } impl<'a> From<&'a MemoryPath> for String { fn from(path: &'a MemoryPath) -> String { path.path.clone() } } impl PartialEq for MemoryPath { fn eq(&self, other: &MemoryPath) -> bool { self.path == other.path } } #[cfg(test)] mod tests { use super::*; use futures::executor::block_on; // use futures::StreamExt; // use std::io::{Read, Result, Seek, SeekFrom, Write}; use VPath; use {VMetadata, VFS}; #[test] fn mkdir() { block_on(async move { let fs = MemoryFS::new(); let path = fs.path("/foo/bar/baz"); assert!(!path.exists().await, "Path should not exist"); path.create_dir().await.unwrap(); assert!(path.exists().await, "Path should exist now"); assert!( path.metadata().await.unwrap().is_dir(), "Path should be dir" ); assert!( !path.metadata().await.unwrap().is_file(), "Path should be not be a file" ); assert!( path.metadata().await.unwrap().len() == 0, "Path size should be 0" ); }); } #[test] fn mkdir_fails_for_file() { block_on(async { let fs = MemoryFS::new(); let path = fs.path("/foo"); path.open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); assert!( path.create_dir().await.is_err(), "Path should not be created" ); }); } /*#[tokio::test] async fn read_empty_file() { let fs = MemoryFS::new(); let path = fs.path("/foobar.txt"); path.open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, ""); } #[tokio::test] async fn rm() { let fs = MemoryFS::new(); let path = fs.path("/foobar.txt"); path.open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); path.rm().await.unwrap(); assert!(!path.exists().await); } #[tokio::test] async fn rmdir() { let fs = MemoryFS::new(); let path = fs.path("/foobar"); path.mkdir().await.unwrap(); path.rm().await.unwrap(); assert!(!path.exists().await); } #[tokio::test] async fn rmrf() { let fs = MemoryFS::new(); let dir = fs.path("/foo"); dir.mkdir().await.unwrap(); let path = fs.path("/foo/bar.txt"); path.open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); dir.rm_all().await.unwrap(); assert!(!path.exists().await); assert!(!dir.exists().await); } #[tokio::test] async fn access_directory_as_file() { let fs = MemoryFS::new(); let path = fs.path("/foo"); path.mkdir().await.unwrap(); assert!( path.open(OpenOptions::new().write(true).create(true).truncate(true)) .await .is_err(), "Directory should not be openable" ); assert!( path.open(OpenOptions::new().write(true).create(true).append(true)) .await .is_err(), "Directory should not be openable" ); assert!( path.open(OpenOptions::new().read(true)).await.is_err(), "Directory should not be openable" ); } #[tokio::test] async fn write_and_read_file() { let fs = MemoryFS::new(); let path = fs.path("/foobar.txt"); { let mut file = path .open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); write!(file, "Hello world").unwrap(); write!(file, "!").unwrap(); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "Hello world!"); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); file.seek(SeekFrom::Start(1)).unwrap(); write!(file, "a").unwrap(); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "Hallo world!"); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.seek(SeekFrom::End(-1)).unwrap(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "!"); } { let _file = path .open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, ""); } } #[tokio::test] async fn append() { let fs = MemoryFS::new(); let path = fs.path("/foobar.txt"); { let mut file = path .open(OpenOptions::new().write(true).create(true).append(true)) .await .unwrap(); write!(file, "Hello").unwrap(); write!(file, " world").unwrap(); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "Hello world"); } { let mut file = path .open(OpenOptions::new().write(true).create(true).append(true)) .await .unwrap(); write!(file, "!").unwrap(); } { let mut file = path.open(OpenOptions::new().read(true)).await.unwrap(); let mut string: String = "".to_owned(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "Hello world!"); } } #[tokio::test] async fn resolve() { let fs = MemoryFS::new(); let path = fs.path("/"); assert_eq!(path.to_string(), "/"); let path2 = path.resolve(&"foo".to_string()); assert_eq!(path2.to_string(), "/foo"); let path3 = path2.resolve(&"bar".to_string()); assert_eq!(path3.to_string(), "/foo/bar"); assert_eq!(path.to_string(), "/"); let path4 = path.resolve(&"foo/bar".to_string()); assert_eq!(path4.to_string(), "/foo/bar"); } #[tokio::test] async fn parent() { let fs = MemoryFS::new(); let path = fs.path("/foo"); let path2 = fs.path("/foo/bar"); assert_eq!(path2.parent().unwrap().to_string(), path.to_string()); assert_eq!(path.parent().unwrap().to_string(), "/"); assert!(fs.path("/").parent().is_none()); } #[tokio::test] async fn read_dir() { let fs = MemoryFS::new(); let path = fs.path("/foo"); let path2 = fs.path("/foo/bar"); let path3 = fs.path("/foo/baz"); path2.mkdir().await.unwrap(); path3 .open(OpenOptions::new().write(true).create(true).truncate(true)) .await .unwrap(); let mut entries: Vec<String> = path .read_dir() .await .unwrap() .map(Result::unwrap) .map(|path| path.to_string().into_owned()) .collect() .await; entries.sort(); assert_eq!(entries, vec!["/foo/bar".to_owned(), "/foo/baz".to_owned()]); } #[tokio::test] async fn file_name() { let fs = MemoryFS::new(); let path = fs.path("/foo/bar.txt"); assert_eq!(path.file_name(), Some("bar.txt".to_owned())); assert_eq!(path.extension(), Some(".txt".to_owned())); assert_eq!(path.parent().unwrap().extension(), None); } #[tokio::test] async fn path_buf() { let fs = MemoryFS::new(); let path = fs.path("/foo/bar.txt"); assert_eq!(None, path.to_path_buf()); } */ }
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn main() { input! { n: usize, q: usize, ab: [(usize, Usize1); n], cd: [(Usize1, Usize1); q], } let m = 200000; let mut place = vec![0; n]; let mut players = vec![BTreeSet::new(); m]; for i in 0..n { let (ai, bi) = ab[i]; place[i] = bi; players[bi].insert(Reverse((ai, i))); } let mut max_scores = BTreeSet::new(); for j in 0..m { if !players[j].is_empty() { let Reverse((ai, i)) = *players[j].range(..).nth(0).unwrap(); max_scores.insert((ai, i)); } } for &(c, d) in &cd { let x = place[c]; let y = d; place[c] = d; let Reverse((x_max, x_max_i)) = *players[x].range(..).nth(0).unwrap(); max_scores.remove(&(x_max, x_max_i)); if !players[y].is_empty() { let Reverse((y_max, y_max_i)) = *players[y].range(..).nth(0).unwrap(); max_scores.remove(&(y_max, y_max_i)); } players[x].remove(&Reverse((ab[c].0, c))); players[y].insert(Reverse((ab[c].0, c))); if !players[x].is_empty() { let Reverse((new_x_max, new_x_max_i)) = *players[x].range(..).nth(0).unwrap(); max_scores.insert((new_x_max, new_x_max_i)); } let Reverse((new_y_max, new_y_max_i)) = *players[y].range(..).nth(0).unwrap(); max_scores.insert((new_y_max, new_y_max_i)); // eprintln!("{:?}", max_scores); println!("{}", max_scores.range(..).nth(0).unwrap().0); } }
use std::collections::HashMap; mod state_transition; pub struct GameState { pub stars: HashMap<StarId, Star>, pub ships: Vec<ShipGroup>, pub carriers: HashMap<CarrierId, Carrier>, pub players: HashMap<PlayerId, Player>, } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct StarId(pub u32); #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct PlayerId(pub u32); #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct CarrierId(pub u32); #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct Player { pub id: PlayerId, pub cash: u32, pub planets_owned: u16, pub weapons_research: u8, pub terraforming_research: u8, pub experimentation_research: u8, pub scanning_research: u8, } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct Star { pub id: StarId, pub owned_by: PlayerId, pub location: (i16, i16), pub size: u8, pub economy: u8, pub infrastructure: u8, pub science: u8, } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub enum Either<A, B> { Left(A), Right(B), } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct Travel { pub from: StarId, pub to: StarId, pub ticks_to_reach: i16, } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct ShipGroup { pub at: StarId, pub owner: PlayerId, pub count: u32, } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct Carrier { pub id: CarrierId, pub at: Either<StarId, Travel>, pub owner: PlayerId, pub count: u32, } impl GameState { pub fn new() -> GameState { GameState { stars: HashMap::new(), ships: Vec::new(), carriers: HashMap::new(), players: HashMap::new(), } } pub fn carrier(&self, id: CarrierId) -> Result<&Carrier, String> { match self.carriers.get(&id) { None => Err(format!(r#"no ship with id "{:?}""#, id)), Some(c) => Ok(c) } } pub fn carrier_mut(&mut self, id: CarrierId) -> Result<&mut Carrier, String> { match self.carriers.get_mut(&id) { None => Err(format!(r#"no ship with id "{:?}""#, id)), Some(c) => Ok(c) } } pub fn player(&self, id: PlayerId) -> Result<&Player, String> { match self.players.get(&id) { None => Err(format!(r#"no player with id "{:?}""#, id)), Some(c) => Ok(c) } } pub fn player_mut(&mut self, id: PlayerId) -> Result<&mut Player, String> { match self.players.get_mut(&id) { None => Err(format!(r#"no player with id "{:?}""#, id)), Some(c) => Ok(c) } } pub fn star(&self, id: StarId) -> Result<&Star, String> { match self.stars.get(&id) { None => Err(format!(r#"no star with id "{:?}""#, id)), Some(c) => Ok(c) } } pub fn star_mut(&mut self, id: StarId) -> Result<&mut Star, String> { match self.stars.get_mut(&id) { None => Err(format!(r#"no star with id "{:?}""#, id)), Some(c) => Ok(c) } } }
#[lambda_attributes::lambda] fn main() {}
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::runtime::integer_to_string::decimal_integer_to_string; #[native_implemented::function(erlang:integer_to_list/1)] pub fn result(process: &Process, integer: Term) -> exception::Result<Term> { let string = decimal_integer_to_string(integer)?; let charlist = process.charlist_from_str(&string); Ok(charlist) }
#![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(html_root_url = "https://docs.rs/tokio-executor/0.1.8")] // Our MSRV doesn't allow us to fix these warnings yet #![allow(rust_2018_idioms)] //! Task execution related traits and utilities. //! //! In the Tokio execution model, futures are lazy. When a future is created, no //! work is performed. In order for the work defined by the future to happen, //! the future must be submitted to an executor. A future that is submitted to //! an executor is called a "task". //! //! The executor is responsible for ensuring that [`Future::poll`] is called //! whenever the task is notified. Notification happens when the internal //! state of a task transitions from *not ready* to *ready*. For example, a //! socket might have received data and a call to `read` will now be able to //! succeed. //! //! This crate provides traits and utilities that are necessary for building an //! executor, including: //! //! * The [`Executor`] trait spawns future object onto an executor. //! //! * The [`TypedExecutor`] trait spawns futures of a specific type onto an //! executor. This is used to be generic over executors that spawn futures //! that are either `Send` or `!Send` or implement executors that apply to //! specific futures. //! //! * [`enter`] marks that the current thread is entering an execution //! context. This prevents a second executor from accidentally starting from //! within the context of one that is already running. //! //! * [`DefaultExecutor`] spawns tasks onto the default executor for the current //! context. //! //! * [`Park`] abstracts over blocking and unblocking the current thread. //! //! # Implementing an executor //! //! Executors should always implement `TypedExecutor`. This usually is the bound //! that applications and libraries will use when generic over an executor. See //! the [trait documentation][`TypedExecutor`] for more details. //! //! If the executor is able to spawn all futures that are `Send`, then the //! executor should also implement the `Executor` trait. This trait is rarely //! used directly by applications and libraries. Instead, `tokio::spawn` is //! configured to dispatch to type that implements `Executor`. //! //! [`Executor`]: trait.Executor.html //! [`TypedExecutor`]: trait.TypedExecutor.html //! [`enter`]: fn.enter.html //! [`DefaultExecutor`]: struct.DefaultExecutor.html //! [`Park`]: park/index.html //! [`Future::poll`]: https://docs.rs/futures/0.1/futures/future/trait.Future.html#tymethod.poll extern crate crossbeam_utils; extern crate futures; mod enter; mod error; mod executor; mod global; pub mod park; mod typed; pub use enter::{enter, exit, Enter, EnterError}; pub use error::SpawnError; pub use executor::Executor; pub use global::{spawn, with_default, DefaultExecutor}; pub use typed::TypedExecutor;
use crate::Score; #[derive(Debug, Clone)] pub struct RecentFiles(Vec<String>); impl From<Vec<String>> for RecentFiles { fn from(inner: Vec<String>) -> Self { Self(inner) } } impl RecentFiles { pub fn calc_bonus(&self, bonus_text: &str, base_score: Score) -> Score { if self.0.iter().any(|s| s.contains(bonus_text)) { base_score / 3 } else { 0 } } }
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(generators, generator_trait)] use std::ops::Generator; use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static A: AtomicUsize = ATOMIC_USIZE_INIT; struct B; impl Drop for B { fn drop(&mut self) { A.fetch_add(1, Ordering::SeqCst); } } fn main() { t1(); t2(); t3(); } fn t1() { let b = B; let mut foo = || { yield; drop(b); }; let n = A.load(Ordering::SeqCst); drop(unsafe { foo.resume() }); assert_eq!(A.load(Ordering::SeqCst), n); drop(foo); assert_eq!(A.load(Ordering::SeqCst), n + 1); } fn t2() { let b = B; let mut foo = || { yield b; }; let n = A.load(Ordering::SeqCst); drop(unsafe { foo.resume() }); assert_eq!(A.load(Ordering::SeqCst), n + 1); drop(foo); assert_eq!(A.load(Ordering::SeqCst), n + 1); } fn t3() { let b = B; let foo = || { yield; drop(b); }; let n = A.load(Ordering::SeqCst); assert_eq!(A.load(Ordering::SeqCst), n); drop(foo); assert_eq!(A.load(Ordering::SeqCst), n + 1); }
use super::InternalEvent; use metrics::counter; #[derive(Debug)] pub struct ChunkProcessed { pub byte_size: usize, } impl InternalEvent for ChunkProcessed { fn emit_metrics(&self) { counter!("k8s_stream_chunks_processed", 1); counter!("k8s_stream_bytes_processed", self.byte_size as u64); } }
#[doc = "Reader of register DC6"] pub type R = crate::R<u32, super::DC6>; #[doc = "USB Module 0 Present\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum USB0_A { #[doc = "1: USB0 is Device Only"] DEV = 1, #[doc = "2: USB is Device or Host"] HOSTDEV = 2, #[doc = "3: USB0 is OTG"] OTG = 3, } impl From<USB0_A> for u8 { #[inline(always)] fn from(variant: USB0_A) -> Self { variant as _ } } #[doc = "Reader of field `USB0`"] pub type USB0_R = crate::R<u8, USB0_A>; impl USB0_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, USB0_A> { use crate::Variant::*; match self.bits { 1 => Val(USB0_A::DEV), 2 => Val(USB0_A::HOSTDEV), 3 => Val(USB0_A::OTG), i => Res(i), } } #[doc = "Checks if the value of the field is `DEV`"] #[inline(always)] pub fn is_dev(&self) -> bool { *self == USB0_A::DEV } #[doc = "Checks if the value of the field is `HOSTDEV`"] #[inline(always)] pub fn is_hostdev(&self) -> bool { *self == USB0_A::HOSTDEV } #[doc = "Checks if the value of the field is `OTG`"] #[inline(always)] pub fn is_otg(&self) -> bool { *self == USB0_A::OTG } } #[doc = "Reader of field `USB0PHY`"] pub type USB0PHY_R = crate::R<bool, bool>; impl R { #[doc = "Bits 0:1 - USB Module 0 Present"] #[inline(always)] pub fn usb0(&self) -> USB0_R { USB0_R::new((self.bits & 0x03) as u8) } #[doc = "Bit 4 - USB Module 0 PHY Present"] #[inline(always)] pub fn usb0phy(&self) -> USB0PHY_R { USB0PHY_R::new(((self.bits >> 4) & 0x01) != 0) } }
use rusoto_core::RusotoError; use rusoto_secretsmanager::{ SecretsManager, GetRandomPasswordRequest, GetRandomPasswordError, }; use std::time::Duration; use crate::{ RotatorError, RotatorResult, SM_CLIENT, }; pub fn get_random_password(timeout: Duration) -> RotatorResult<String> { SM_CLIENT.get_random_password(GetRandomPasswordRequest { exclude_characters: Some(r#"/@"'\"#.to_string()), ..Default::default() }) .with_timeout(timeout) .sync() .map_err(|e| match e { RusotoError::Service(GetRandomPasswordError::InvalidParameter(msg)) => { RotatorError::InvalidPasswordParameter { message: msg, } }, e => RotatorError::GetRandomPassword(format!("{:?}", e)) }) .and_then(|response| { response.random_password.ok_or(RotatorError::GetRandomPassword("missing password in response".to_string())) }) }
mod cli; mod rendering; mod taskmanager; extern crate prettytable; extern crate dirs; use crate::cli::Cli; use crate::rendering::{ confirm_task_moved, confirm_task_removed, confirm_the_task, greet_the_user, render_all_tasks, }; use crate::taskmanager::{Status, Task, Tasks}; use chrono::Utc; use std::fs::OpenOptions; use structopt::StructOpt; use std::path::PathBuf; use std::str::FromStr; const STD_OUT_ERR_MSG: &str = "Unable to write message in standard output"; fn main() { let filepath: PathBuf = [dirs::data_local_dir().unwrap(), PathBuf::from_str("ruban.json").unwrap()].iter().collect::<PathBuf>(); let source = OpenOptions::new() .read(true) .write(true) .create(true) .open(filepath.as_os_str()) .expect("Unable to open file"); let destination = OpenOptions::new() .read(true) .write(true) .create(true) .open(filepath.as_os_str()) .expect("Unable to open file"); let mut tasks = Tasks::from(&source); greet_the_user(&mut std::io::stdout()).expect(STD_OUT_ERR_MSG); match Cli::from_args() { Cli::Add { description, tags } => { let task = Task { number: 0, tags: Some(tags), description, creation_date: Utc::now().to_rfc3339(), status: Status::ToDo, }; tasks.add(&task); destination .set_len(0) .expect("Unable to clear content from file"); tasks.save(&destination); confirm_the_task(&task, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); render_all_tasks(&tasks, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); } Cli::Ls {} => { render_all_tasks(&tasks, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); } Cli::Rm { number } => { tasks.remove(number); destination .set_len(0) .expect("Unable to clear content from file"); tasks.save(&destination); confirm_task_removed(number, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); render_all_tasks(&tasks, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); } Cli::Mv { number, status } => { let new_status: Status; match status.to_lowercase().as_str() { "wip" => new_status = Status::WIP, "todo" => new_status = Status::ToDo, "done" => new_status = Status::Done, _ => new_status = Status::WIP, }; tasks.change_status_to(number, new_status); destination .set_len(0) .expect("Unable to clear content from file"); tasks.save(&destination); confirm_task_moved(number, &status, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); render_all_tasks(&tasks, &mut std::io::stdout()).expect(STD_OUT_ERR_MSG); } } }
//! Regular smart contract. use near_bindgen::near_bindgen; use borsh::{BorshDeserialize, BorshSerialize}; #[near_bindgen] #[derive(Default, BorshDeserialize, BorshSerialize)] struct Incrementer { value: u32, } #[near_bindgen] impl Incrementer { pub fn inc(&mut self, by: u32) { self.value += by; } } fn main() {}
use crate::game::{State, Transition}; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::ui::{ShowEverything, UI}; use abstutil::MultiMap; use ezgui::{hotkey, EventCtx, GfxCtx, ItemSlider, Key, Line, Text}; use geom::Duration; use map_model::{Map, Traversable}; use sim::{ CarID, DrawCarInput, DrawPedCrowdInput, DrawPedestrianInput, GetDrawAgents, PedestrianID, }; use std::collections::BTreeMap; pub struct InactiveTimeTravel { should_record: bool, moments: Vec<(StateAtTime, Text)>, } struct StateAtTime { time: Duration, cars: BTreeMap<CarID, DrawCarInput>, peds: BTreeMap<PedestrianID, DrawPedestrianInput>, cars_per_traversable: MultiMap<Traversable, CarID>, peds_per_traversable: MultiMap<Traversable, PedestrianID>, } impl InactiveTimeTravel { pub fn new() -> InactiveTimeTravel { InactiveTimeTravel { should_record: false, moments: Vec::new(), } } pub fn start(&mut self, ctx: &mut EventCtx, ui: &UI) -> Transition { self.should_record = true; // In case we weren't already... self.record(ui); // Temporarily move our state into the new one. let items = std::mem::replace(&mut self.moments, Vec::new()); Transition::Push(Box::new(TimeTraveler { slider: ItemSlider::new( items, "Time Traveler", "moment", vec![vec![(hotkey(Key::Escape), "quit")]], ctx, ), })) } // TODO Now that we take big jumps forward in the source sim, the time traveler sees the same // granularity when replaying. pub fn record(&mut self, ui: &UI) { if !self.should_record { return; } let map = &ui.primary.map; let sim = &ui.primary.sim; let now = sim.time(); if let Some((ref state, _)) = self.moments.last() { // Already have this if now == state.time { return; } // We just loaded a new savestate or reset or something. Clear out our memory. if now < state.time { self.moments.clear(); } } let mut state = StateAtTime { time: now, cars: BTreeMap::new(), peds: BTreeMap::new(), cars_per_traversable: MultiMap::new(), peds_per_traversable: MultiMap::new(), }; for draw in sim.get_all_draw_cars(map).into_iter() { state.cars_per_traversable.insert(draw.on, draw.id); state.cars.insert(draw.id, draw); } for draw in sim.get_all_draw_peds(map).into_iter() { state.peds_per_traversable.insert(draw.on, draw.id); state.peds.insert(draw.id, draw); } let label = Text::from(Line(state.time.to_string())); self.moments.push((state, label)); } } struct TimeTraveler { slider: ItemSlider<StateAtTime>, } impl State for TimeTraveler { // Returns true if done. fn event(&mut self, ctx: &mut EventCtx, _: &mut UI) -> Transition { self.slider.event(ctx); ctx.canvas.handle_event(ctx.input); if self.slider.action("quit") { let moments = self.slider.consume_all_items(); return Transition::PopWithData(Box::new(|state, _, _| { let mut sandbox = state.downcast_mut::<SandboxMode>().unwrap(); sandbox.time_travel.moments = moments; })); } Transition::Keep } fn draw(&self, g: &mut GfxCtx, ui: &UI) { ui.draw(g, DrawOptions::new(), self, &ShowEverything::new()); self.slider.draw(g); } } impl TimeTraveler { fn get_current_state(&self) -> &StateAtTime { self.slider.get().1 } } impl GetDrawAgents for TimeTraveler { fn time(&self) -> Duration { self.get_current_state().time } fn step_count(&self) -> usize { self.slider.get().0 } fn get_draw_car(&self, id: CarID, _map: &Map) -> Option<DrawCarInput> { self.get_current_state().cars.get(&id).cloned() } fn get_draw_ped(&self, id: PedestrianID, _map: &Map) -> Option<DrawPedestrianInput> { self.get_current_state().peds.get(&id).cloned() } fn get_draw_cars(&self, on: Traversable, _map: &Map) -> Vec<DrawCarInput> { let state = self.get_current_state(); // TODO sort by ID to be deterministic? state .cars_per_traversable .get(on) .iter() .map(|id| state.cars[id].clone()) .collect() } // TODO This cheats and doesn't handle crowds. :\ fn get_draw_peds( &self, on: Traversable, _map: &Map, ) -> (Vec<DrawPedestrianInput>, Vec<DrawPedCrowdInput>) { let state = self.get_current_state(); ( state .peds_per_traversable .get(on) .iter() .map(|id| state.peds[id].clone()) .collect(), Vec::new(), ) } fn get_all_draw_cars(&self, _map: &Map) -> Vec<DrawCarInput> { self.get_current_state().cars.values().cloned().collect() } fn get_all_draw_peds(&self, _map: &Map) -> Vec<DrawPedestrianInput> { self.get_current_state().peds.values().cloned().collect() } }
use std::io; use std::io::Write; use std::collections::HashMap; use std::io::Read; const TAPE_LEN: usize = 30000; #[derive(PartialEq, Eq, Hash, Debug)] enum Bracket { Open(usize), Close(usize), } fn make_mapping(prog: &str) -> HashMap<Bracket, Bracket> { let mut stack: Vec<usize> = vec![]; let mut result: HashMap<Bracket, Bracket> = HashMap::new(); for (i, c) in prog.chars().enumerate() { match c { '[' => { stack.push(i); } ']' => { match stack.pop() { Some(open) => { result.insert(Bracket::Open(open), Bracket::Close(i)); result.insert(Bracket::Close(i), Bracket::Open(open)); } None => panic!("Mismatched ] at {}", i), } } _ => {} } } if let Some(i) = stack.pop() { panic!("Mismatched [ at {}", i); } result } pub fn interpret(prog: &str) { let chars: Vec<char> = prog.chars().collect(); let prog_len = prog.len(); let mut tape: [u8; TAPE_LEN] = [0; TAPE_LEN]; let mut cursor: usize = 0; let mut ip: usize = 0; let matches = make_mapping(prog); while ip < prog_len { match chars[ip] { '>' => { if cursor == TAPE_LEN - 1 { panic!("Exceeded length of tape"); } cursor += 1; } '<' => { if cursor == 0 { panic!("Attempted to move off the left side of the tape"); } cursor -= 1; } '+' => { tape[cursor] = if tape[cursor] == 0xff { 0 } else { tape[cursor] + 1 } } '-' => { tape[cursor] = if tape[cursor] == 0 { 0xff } else { tape[cursor] - 1 } } '.' => { print!("{}", tape[cursor] as char); io::stdout().flush().expect("Could not flush stdout"); } ',' => { match io::stdin().bytes().next() { Some(Ok(c)) => tape[cursor] = c, _ => panic!("Failed to read input"), } } '[' => { if tape[cursor] == 0 { match matches[&Bracket::Open(ip)] { Bracket::Close(next) => ip = next, _ => panic!("Invalid bracket match"), } } } ']' => { if tape[cursor] != 0 { match matches[&Bracket::Close(ip)] { Bracket::Open(next) => ip = next, _ => panic!("Invalid bracket match"), } } } _ => {} }; ip += 1; } }
//use criterion::Criterion; //use test_utils; // //fn product(c: &mut Criterion) { // c.bench_function_over_inputs("TabularFactor_product", |b, &size| { // let nodes_left = test_utils::create_vec_node_index(0, size); // let factor_left = test_utils::create_factor::<f64, u32>(nodes_left); // // let nodes_right = test_utils::create_vec_node_index(size/2, size); // let factor_right = test_utils::create_factor::<f64, u32>(nodes_right); // b.iter(|| factor_left.product(&factor_right)) // },vec![2usize, 4, 6, 8, 10, 12, 14]); //} // //criterion_group!(product_group, product); // //criterion_main!(product_group);
//! Thread-safe task notification primitives. mod atomic_task; pub use self::atomic_task::AtomicTask;